• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initializes char to an integer !!! Funny result

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris, william and srini,
thanks for ur explanation. As i am new to java i did not know about these.
shankar
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic