This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on byte literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on byte literals" Watch "Doubt on byte literals" New topic
Author

Doubt on byte literals

bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
Doing some code snippets during my preparation and i encountered this. The below code throws a compiler error

but if i put the modifier final to both s and s1 it is compiling.

Am i missing something here? why is the compiler not throwing an error?
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3013
    
  35

Please check this one.


Founder of ExamLab and Systemup
See how I can help you to become an awesome programmer
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Hello,

It is because i believe this conversion is taking place at compile time rather then at run-time as variables are declared final.
As they are within the range of the byte, that is why it is not giving any compilation error. Lets say



It will start giving compile time error as it has gone out of range. But above conversion i suppose is happening at compile
time rather then at run-time. I would love if someone else will comment.

Am i right or not.

Best Regards,


Prithvi,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

In the second case, both s and s1 are compile time constants. This means that the compiler knows their value at compile time. So when you say s+s1, the compiler is able to find the result of that expression i.e. the compiler knows that s+s1 will be 20, so it replaces the expression by its value. So your code after compilation becomes


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
I got it now. Thank you Devaka, Prithvi, Ankit for your replies.
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
You are welcome Bhanu.

Cheers,
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt on byte literals
 
Similar Threads
confusion on casting
return type
polymorphism question
Why doesn't the subclass variable hide it?
Compile time constant