Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on byte literals

 
bhanu chowdary
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 4316
233
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check this one.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
Ankit Garg
Sheriff
Posts: 9511
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
bhanu chowdary
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now. Thank you Devaka, Prithvi, Ankit for your replies.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome Bhanu.

Cheers,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic