File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes for loop and byte to int coversion. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "for loop and byte to int coversion." Watch "for loop and byte to int coversion." New topic
Author

for loop and byte to int coversion.

Rajiv Chopra
Ranch Hand

Joined: Dec 19, 2008
Posts: 62
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.


Rajeev Kumar
SCJP 6.0 Certified 96%
Tapio Niemela
Ranch Hand

Joined: Jan 06, 2006
Posts: 77
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

Joined: Dec 19, 2008
Posts: 62
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
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for loop and byte to int coversion.