Reputation:
I have been trying to find out the Why am I getting a ' '
when I print a char variable which was initialized with the default value of '\u0000'
?
Also I know that float and double has a default value of "0.0f" and "0.0d", but here when I print their default values the suffix "f" and "d" are not printed. So why are these suffixes not printed with the values?
Here's the code:
class Check{
char c;
float f;
double d;
public static void main(String a[]) {
Check obj = new Check();
System.out.println("Default value of char : " + obj.c);
System.out.println("Default value of float : " + obj.f);
System.out.println("Default value of double: " + obj.d);
}
}
In the code for default value of char is printed as ' '. For float it is "0.0" and for double is "0.0". In short my question is: Why am I getting a ' ' instead of '\u0000' or null (or something like this) for char? Why the suffix present in the default values of float and double are not printed? (like "0.0f" and "0.0d")
Note: There are other questions like: Primitives/Objects Declaration, default initialization values and what's the default value of char?, but unlike my question these questions discuss only about their default values not about printing them.
Upvotes: 3
Views: 974
Reputation: 97
Things that come to my mind right now:
In your code you miss the final "}", for class Check.
Have you try printing just
System.out.println(obj.c); // Without the String
Adding the String may read the null ass a '' and the d and f as part of the format, so it just print 0.0.
When you print ascii code for some values java compiler reads it as a the intended valu, with this I mean that probably when you print the char it prints a "\u0000", but when the compiler reads it he makes it a '', same with the format of float and double values. In context is like printing a \n, you just can't because of interpreted as a semicolon.
Upvotes: -2
Reputation: 17524
Those suffixes have no meaning outside of java code, so they will never get printed to the console, or a file, or a Socket
.
The same goes for "\u" prefix (java does internally use Unicode), when you print a char value, you are actually printing the corresponding character .
The default character
value '\u0000' is not null, and is a non-printable character, giving different outputs depending on your system : empty, a square...
If you attempt to print one, the system is supposed to output something, the 'something' will depend on the platform, but it isn't supposed to ignore your print EVEN THOUGH it has no way to display it correctly.
Upvotes: 3