This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt 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 Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on byte literals" Watch "Doubt on byte literals" New topic

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

Joined: Jul 29, 2008
Posts: 3698

Please check this one.

Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774

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,

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

Joined: Aug 03, 2008
Posts: 9434

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.

I agree. Here's the link:
subject: Doubt on byte literals
It's not a secret anymore!