Sunday, 16 November 2014

Use Character Data type in java programming

In java we use ‘char’ to store the character data type in variables. Maybe it looks same like ‘char’ we use in c and c++ programming. But it’s different. In c and c++ programming we use ‘char’ that is 8 bit wide. Btu for java programming it is 16 bit wide. As java use Unicode to define characters. Unicode is define a fully international character set that defines all character found in human languages. As java is made to use in worldwide it is significant to use Unicode.
Let’s write a program
public class useChar {
public static void main(String args[])
{
char chr1,chr2;
chr1 = 66;
chr2 = 'B';
System.out.println("chr1 and chr2 presnts "+chr1+" and "+chr2);
}
}
Let’s see output of above program
chr1 and chr2 presnts B and B
In above program we can see that ‘chr1’ hold a number but it print a character. It’s happen because of ASCII value. The number 66 represent character ‘B’. The ASCII character set occupies the first 127 values in the Unicode character set.
We can do arithmetic operation with char value as it is can also be thought of as an integer type. Let’s try an example
public class useChar {
public static void main(String args[])
{
char ch;
ch = 65;
System.out.println("chr presnts "+ch);
ch++;
System.out.println("chr presnts "+ch);
}
}
Output of above program
chr presnts A
chr presnts B
In above program we use increment operator where ch is a character type. It shows that it’s possible to do arithmetic operations with character data types.

0 comments:

Post a Comment