• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Got Doubt about final local variable usage in switch block

 
Narayana Bojja
Ranch Hand
Posts: 135
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Here num2 variable is declared and initialized in a single line. so  it is a compile time constant . So It prints 4.




Here num2 variable is declared and initialized in a seperate lines. why num2 can't be compile time constant. Why the program giving the following error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
case expressions must be constant expressions



I thought that if variable declaration and initialization done in separate  statements , variable assignment goes at run time . Am I wright ??
 
Stephan van Hulst
Bartender
Pie
Posts: 6503
83
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. For something to be a compile time constant, it must be initialized and declared at the same time.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Narayana Bojja wrote:I thought that if variable declaration and initialization done in separate  statements , variable assignment goes at run time . Am I wright ??

Yes, you are absolutely spot-on!

Time for another (free) pop quiz question. What is the result of this code snippet?

Hope it helps!
Kind regards,
Roel
 
Narayana Bojja
Ranch Hand
Posts: 135
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here num2 is an object . object creation done by the JVM at run time. So, num2 is not a compile time constant. So we get compile time error . If I am wrong , please correct me.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Narayana Bojja wrote:Here num2 is an object

That's not 100% accurate! num2 is not an object, but it is a reference variable which refers to an Integer object.

Narayana Bojja wrote:So, num2 is not a compile time constant. So we get compile time error.

You are spot-on! An object can NEVER be a compile-time constant. A compile-time constant (or a constant expression) can only be a primitive data type or String. In this topic you'll find an explanation about what's a compile-time constant.

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic