What's the default value of char? - java

char c = '\u0000';
When I print c, it shows 'a' in the command line window.
So what's the default value of a char type field?
Someone said '\u0000' means null in Unicode; is that right?

The default value of a char attribute is indeed '\u0000' (the null character) as stated in the Java Language Specification, section §4.12.5 Initial Values of Variables .
In my system, the line System.out.println('\u0000'); prints a little square, meaning that it's not a printable character - as expected.

'\u0000' is the default value for a character. Its decimal equivalent is 0.
When you are declaring some char variable without initializing it, '\u0000' will be assigned to it by default.
see this code
public class Test {
char c;
public static void main(String args[]) throws Exception {
Test t = new Test();
char c1 = '\u0000';
System.out.println(t.c);
System.out.println(c1);
System.out.println(t.c == c1);
}
}
This code will print true for the last print.

Default value of Character is Character.MIN_VALUE which internally represented as MIN_VALUE = '\u0000'
Additionally, you can check if the character field contains default value as
Character DEFAULT_CHAR = new Character(Character.MIN_VALUE);
if (DEFAULT_CHAR.compareTo((Character) value) == 0)
{
}

'\u0000' stands for null . So if you print an uninitialized char variable , you'll get nothing.

It's '\u0000'. See here for more information.

The default char is the character with an int value of 0 (zero).
char NULLCHAR = (char) 0;
char NULLCHAR = '\0';

its tempting say as white space or integer 0 as per below proof
char c1 = '\u0000';
System.out.println("*"+c1+"*");
System.out.println((int)c1);
but i wouldn't say so because, it might differ it different platforms or in future. What i really care is i ll never use this default value, so before using any char just check it is \u0000 or not, then use it to avoid misconceptions in programs. Its as simple as that.

The default value of a char data type is '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
You can see the info here.

Note that there is a distinct difference between null and zero.
In http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html (referenced above), the statement is made :-
There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.
That is why the following statements will give you an error and not the other :-
char a = null; //Type mismatch: cannot convert from null to char.
char b = 0; //Valid syntax.

\u0000 is the default value for char type in Java
As others mentioned, you can use comparison to check the value of an uninitialized variable.
char ch;
if(ch==0)
System.out.println("Default value is the null character");

I think it is '\u00000' or just '' rather than '\u0000'
(The 1st one has 5 zeros while the last one has four zeroes.)

Default value for char is \u0000
public class DefaultValues {
char varChar;
public static void main(String...l)
{
DefaultValues ob =new DefaultValues();
System.out.println(ob.varChar=='\u0000');
}
}
This will return true

The default value of char is null which is '\u0000' as per Unicode chart. Let us see how it works while printing out.
public class Test_Class {
char c;
void printAll() {
System.out.println("c = " + c);
}
public static void main(String[] args) {
Test_Class f = new Test_Class();
f.printAll();
} }
Note: The output is blank.

The default value of a char primitive type is '\u0000'(null character) as stated in the Java Language Specification.
The shortcut for 'u0000' is '\0', So the null can be represented either by 'u0000' or '\0'.
The below Java program validates null representations using instance char field 'c'.
public class DefaultValueForchar {
char c;
public static void main(String[] args) {
char c0 = '\0';
char cu0000 = '\u0000';
DefaultValueForchar obj = new DefaultValueForchar();
System.out.println(obj.c);
System.out.println(c0);
System.out.println(cu0000);
System.out.println(c0==cu0000);
System.out.println(obj.c==c0);
System.out.println(obj.c==cu0000);
}
}

Related

How to Output int from char in JAVA after storing it [duplicate]

This question already has answers here:
Char - Java not working as intended / my code
(4 answers)
Closed 3 years ago.
I am seeing a tutorial on udemy and there the instructor says that we can store the integer variable in the char data type. But when I try to print the value ... nothing shows up
I tried assigning the "char one" value to integer variable and then get the output from int variable,It works but why can not I use the char to output the value
public static void main(String[] args) {
char one = 10;
System.out.println(one);
}
If you look at the ASCII table you would see that the character 10 represents the newline character.
This can be proved by the code below:
public static void main(String[] args) {
char one = 10;
//no newline added by print, but println adds a newline implicitly
System.out.print("Test");
System.out.print(one);
System.out.print("Test");
}
The output is:
Test
Test
Although I used System.out.print a newline was still added in the output after the first Test. So you see something was actually printed.
Furthermore, when you pass a char to the System.out.println() the char is converted to its String representation as per the ASCII table by invoking the String.valueOf(char) as char is a primitive.
For Objects when you pass a reference in the System.out.println() the toString() method of the object would be called to get its String representation.
If you change the value to char one = 65 you would see the letter A printed.
In Java char type is an int, therefore they can be converted char <-> int.
When you print an int - you get an integer number. When you print char - you get an ASCII character. char ch = 10 - is not printable character.
char ch = 'A';
System.out.println(ch); // print 'A'
int code = ch;
System.out.println(code); // print 65 - ASCII code of 'A'
Adding to the above answers, if you want to output the int value from the variable "one", a cast would work:
char one = 10;
System.out.println((int) one);
If you take a look at the ASCII Table, you can see the value of 10 is LF which is a new line. If you print this alone, it will appear to be doing nothing because it is just a new line.
However if you modify the code a bit to print some actual characters on both side of the LF char:
char c1 = 70;
System.out.print(c1);
char one = 10;
System.out.print(one);
char c2 = 71;
System.out.print(c2);
This will output:
F
G
On separate lines due to the newline in between, without it they would have printed on the same line.
Additionally you can see on that table 70 corresponds with F, and 71 with G.
Note: Java does not technically use ASCII, but rather a different encoding depending on your environment(commonly UTF-16 or ISO-8859-1), however, the characters are usually equivalent to ASCII for the amount of values the ASCII table contains (a superset). For example char c1 = 202 will print Ê for me, which is not an ASCII value.
You are misinterpreting your output and drawing the wrong conclusion.
A char is a UTF-16 code unit. UTF-16 is a character encoding for the Unicode character set. UTF-16 encodes a Unicode codepoint with one or two UTF-16 code units. Typically, if it might be two code units, you'd use String or char[] instead of char. But if your codepoint is known to take only one UTF-16 code unit, you could use char.
The codepoint you are using is U+000A 'LINE FEED (LF)'. It does take one UTF-16 code unit \u000a, which is convertible from the integer value 0xa or 10. If you inspect your output carefully, you'll "see". Perhaps adding output before and after would help.

What is the use of '\u' and why does my program print a different value if I use quotes or not?

In the following code snippet :
public static void main(String[] args) {
int a = \u0030;
System.out.println(a); // A
int b = '\u0030';
System.out.println(b); // B
}
Statement A is printing 0 whereas statement B is printing 48.
Why is there a difference when I use single quotes?
Also, if a change the declaration for a to:
int a = \u0029;
Why do I get the error?
Syntax error on token ")", invalid VariableInitializer
In:
int a = \u0030;
The string \u0030 is the number literal 0 in your source code. It's as if you literally typed 0 instead.
why it is giving compilation [error] if i use any number for below 30 and more then 40.
exception when i use \u0029 is Syntax error on token ")", invalid VariableInitializer
Characters 0x30 to 0x39 are digits 0-9, which of course are literals you can assign to an int. The others are not valid integer literals.
Your compilation error example:
int a = \u0029;
Is the same as:
int a = ); // clearly not valid!
Going back to your original example, perhaps you meant:
int a = '\u0030'; // notice the single quotes
Now you are assigning a character literal to an integer. Now you can assign other characters, not just unicode 0x30-0x39. Note that the integer will have the ordinal value of that character. So the variable a in this case would be 0x30 or in decimal 48.

Character.charValue() vs toString in JAVA

What is the difference between charValue() and toString() methods of class Character. Both of them return the same i.e, the character value held by the object of the class character as in following code.
public class OtherCharMethods
{
public static void main(String[] args)
{
Character c1 = 'A';
Character c2 = 'A';
System.out.printf(
"c1 = %s\nc2 = %s\n\n", c1.charValue(), c2.toString());
if (c1.equals(c2))
System.out.println("c1 and c2 are equal\n");
else
System.out.println("c1 and c2 are not equal\n");
}
} // end class OtherCharMethods
The one method returns a single char value (primitive type); the other one returns a String (reference type).
That is all there is to this.
Given your comment: the thing to understand - that returned string will of course contain exactly one character; the one that charValue() returns to you.
But: those are still two different things. As the literals "a" and 'a' also contain one char; but in the end mean different things. If you just print the variables to System.out; of course that gives the same result. But that doesn't make a char the same as a String.
Character#charValue() returns a char, Character#toString() returns an string OBJECT, that is a huge difference between those two, one is a primitive, the other an object
charValue() will represent certain value of the character and toString() function will convert the value into string. so both the operation are different.. if you try to give more than one character in the charvalue() function's object, it will give a compile time error but in toString() case its different you can pass any kind of object and any number of characters which capable to convert it to string.

Why are the default values of char, double and float printed like that?

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.
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.
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.

Java CASE why do i get a complete differet int back with and without using ' '

As a Java beginner I'm playing around with a case statement at this point.
I have set: int d = '1'; And with: System.out.println("number is: " + d);, this returns 51.
Now I found out that if I set it as: int d = 1;, it does return 1.
Now my question is why does it return 49 when I set it as '3'? What difference do the ' ' make?
My code that returns 49:
int a = '1';
switch(a)
{
case '1' :
System.out.println("Good");
break;
case '2' :
case '3' :
System.out.println("great");
break;
default :
System.out.println("invalid");
}
System.out.println("value: " + a);
'1' is the character '1', whose integer value is 49. Each character has a numeric value in the range from 0 to 2^16-1. Therefore 1 and '1' are different integer values.
With ' (single quotes) around a character you tell the compiler that the value in between is a character (variable type char in Java). Generally, computers only understand numbers so characters get represented as numbers in memory as well. The value of the character '1' is 49. You want to actually save the value 1 in memory and use that to calculate things. So, you have to tell the compiler that you want this to be interpreted as an actual number and not as a character.
To summarize:
'1' is the character that prints the number 1
1 is the actual number 1
This means 1 and '1' have different integer values.
You can look at the integer value of the most commonly used characters in coding here: ASCII Table
In Java the character values are stored as int internally. That means when you assign a char value using 'A' to an int type, the compiler casts the char value into int and thus the UTF-16 Code unit value is stored into the int variable.
Try this one as well:
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
1 is interpreted as a character whose value is 49.
Do:
int a = 1;
switch(a) {
case 1:
...
Or, if you go with your current code:
System.out.println("value: " + Integer.parseInt((char)a+'');
It is happens because for some weird reason java treat char type as short.
Your '1' expression is constant expression of type char. It is stored internally as some numeric value. Usually all goes fine with this approach for example System.out.println('1') will print exactly what you expect.
But when you write int a = '1'; you char value is converted to int value because char behave like short int there.
PS: if there was no implicit conversion between char and int (which anyway have no sense) you just got compilation error.
When you declare int d='1'; then 1 is not treated as integer it is a character. It is converted to 49 according its unicode value. similarly character '3' will coverted to 51. Jvm do implicit type casting from character to integer.
you should try this code
char c = '3';
int a ='1';
System.out.println(c);
System.out.println((int)c);
You will get output as
3
51
49

Categories