Characters
Within Java, the data type used to store characters is char. Moreover, C/C++ programmers beware: char in Java is not the similar as char in C or C++. Within C/C++ char is an integer type which is 8 bits huge. This is not the case in Java. Alter, Java uses Unicode to represent characters. A Unicode describes a fully international character set which can represent all of the characters found in all human languages. Therefore, in Java char is a 16 bit type. A range of a char is 0 to 65,536. There are negative chars. A standard set of characters known as ASCII still ranges from 0 to 127 as always and the extended 8 bit character set, ISO-Latin-1, ranges from 0 to 255. In the given program which describes char variables.
// Demonstrate char data type.
Class Chardemo {
public static void main (string args [ ] ) {
char ch1,ch2;
ch1=88; // code for X
Ch2 = 'Y' ;
System.out.print ("ch1 and ch2 :") ;
System.out.print1n(ch1 + " " + ch2);
}
}
This program shows the output;
ch1 and ch2 : X Y
Remember that ch1 is assigned the value 88 that is the ASCII (and Unicode) value which corresponds to the letter X. As mentioned previously, the ASCII character set occupies in which first 127 values in the Unicode character set. For that reason, all the "old tricks" that you have used along with characters in the past will work in Java, also.
Even through chars are not integers, in various cases you could operate on them as if they were integers. This permits you to add two characters both, or to increment the value of a character variable. For instance, let consider the following program.
// char variables behave like integers.
class chardemo2
public static void main (string args [ ]) {
char ch1 ch1= 'X';
System.out.print1n ("ch1 contains" +ch1);
ch1++; // increment ch1
System.out.print1n("ch1 is now" + ch1);
}
}
The output produce through this program is shown here.
ch1 contains X
ch1 is now Y
Here, ch1 is first providing the value X. Further, ch1 is incremented. This concludes in ch1 holding Y, the next character in the ASCII (and Unicode) sequence.