• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop and byte to int coversion.

 
Rajiv Chopra
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class ContinueGotcha {

public static void main(String[] args){
for(byte i =0 ; i<10; i++){
System.out.println("Value of i = " + i);

}}}

Why the above code works fine and below one not. Only difference is increment difference in for loop.

public class ContinueGotcha {
public static void main(String[] args){
for(byte i =0 ; i<10; i=i+1){
System.out.println("Value of i = " + i);

}}}

Can someone explain me in detail . Thanks in advance. I was thinking that both will not work but the above code is working.
 
Tapio Niemela
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because i=i+1 is automatically converting byte to int, where ++ isn't. You must also explicitly tell to compiler that the result is really byte type..


 
Rajiv Chopra
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tapio Niemela wrote:Because i=i+1 is automatically converting byte to int, where ++ isn't. You must also explicitly tell to compiler that the result is really byte type..





Thanks Niemela for a good explanation.

I think same explanation works with all operators like. +=, -=, ++, --, *= etc.

like

byte i =10;
//i += 1; // will not give any compilation error.
i = i +1; //will give error cannot convert int to byte. you need explicit cast here to make it work.

similar with others
 
Henry Wong
author
Marshal
Pie
Posts: 21497
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

For those who like a pointer to the specification...

The reason "i++" works is defined in section 15.14.2. Notice that an implicit primative narrowing conversion is one of the operations which may be applied.

The reason "i += 1" works (although not shown in example in this topic) is defined in section 15.26.2. Notice the cast when the expression is expanded.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic