This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pattern Matching Query from Exam LAb

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





The first segment gives compiler error .

while,the second one compiles and runs fines..
In both of the codes,mt.group() is outside of while
Any reason for this ???
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first segment gives compiler error

No it doesn't. It compiles fine but generates an exception at runtime as there is no match for group method to return. In the second case you don't get an exception as there is a match which is returned by the group method...
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit garg wrote:
generates an exception at runtime as there is no match for group method to return. In the second case you don't get an exception as there is a match which is returned by the group method...


why does mt.group() in the first code fails to give any result (outside of while) ?
I read from java API that it returns the last Found match
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You already found the last match inside of the loop in the first piece of code. Then when the loop ends there is nothing to match, that's why you get an exception. Your second code will also fail if you add another call to group method like this
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Ankit

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic