Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

char primitive initialization values

 
B Barnett
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings:
I was doing Marcus Green's Mock Exam # 2 and question #28 is as follows:
public class As{
int i = 10;
int j;
char z= 1; //**This line is what I have a question about**
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);
}
}
I assumed there would be a compiler error becaucse I was under the impression that char primitives had to be initilized using single quotes ( '' ). Unfortunately, I have not been able to find much documention on this, only the Character class. Please let me know what are valid initializers for the char primitive.
Thank you
B Barnett
 
Hirok Sanyal
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel since the char is an unsigned integer, hence integer values within the specified range of values of a char data type can be assigned to a char variable.
 
Mohnish Sharma
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I modified the code a little bit
public class As{
char z= 1; //**This line is what I have a question about**
public static void main(String argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println("\u0001"); // new stuff ******
System.out.println(z);
}
}

and the output was two DOS smiley faces. I think the compiler is assuming z = 1 to be equal to unicode \u0001.

 
Sathvathsan Sampath
Ranch Hand
Posts: 96
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,
Chars can take a value btw 0 to (2^16-1). Therefore, all integer literals within the abouve range can be assigned to a char without explicit cast.
Also, remember that the internal storage for all chars & strings are done under unicode format.
Hope this helps

------------------

- Sathvathsan Sampath
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic