wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initializes char to an integer !!! Funny result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initializes char to an integer !!! Funny result" Watch "Initializes char to an integer !!! Funny result" New topic
Author

Initializes char to an integer !!! Funny result

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi everyone!!
the below program initializes char z to an integer. I was expecting it to give error but if show a funny result at run time. can anyone explain this.
Output is
0
false

public class As{
int i = 10;
int j;
char z= 1;
boolean b;
public static void main(String argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println(j);
System.out.println(b);
System.out.println(z);
}
}
shankar
Chris Cleverley
Greenhorn

Joined: Mar 09, 2007
Posts: 22
I wonder as to why you were expecting it to give an error.
It's nothing unexpected too, it's the usual junk that you'd expect while printing out such characters.
BTW you'll get the same result if you print char c = '\u0001'.
Chris
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
The reason you see that is that the compiler knows the type of each of those variables and applies a conversion to String accordingly. The int and boolean convert to String representations but the compiler assumes you want the char printed as a character so you get that box which is typical display for characters that dont have a font representation.
Bill
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
When you say,

char c=1

the compiler knows that the number 1 will fit in a char variable and assigns a character whose value is 1 to the variable c;
the following code will assign 'A' to c1 and 'a' to c2

char c1=65
char c2=97

but the following will not compile saying that need to cast an int to char

int i=65;
char c=i;

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Chris, william and srini,
thanks for ur explanation. As i am new to java i did not know about these.
shankar
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Initializes char to an integer !!! Funny result