Google+

42. 'char' data type






Unlike the old programming languages C/C++, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all the characters found in all human languages. The range of char in Java is 0 to 65536.



Program demonstrating char variables:

class CharDemo
{
    public static void main(String args[])
    {
         char ch1, ch2;
     
          ch1 = 88;  // Unicode value which represents the letter X
          ch2 = 'Y';

          System.out.print("ch1 and ch2: ");
          System.out.println(ch1+ " " + ch2);
     }
}

Output for this program:

ch1 and ch2: X  Y



Program to show that the char variables behave like integers:

class CharDemo2
{
    public static void main(String args[])
    {
         char ch1='X';
         System.out.println("ch1 before increment: "+ch1);

         ch1++; //Increment ch1 char variable by one
         System.out.println("ch1 after increment: "+ch1);
     }
}

Output of this program:

ch1 before increment: X
ch1 after increment: Y






Please comment below to feedback or ask questions.

How to use the 'boolean' data type will  be explained in the next post




4 comments:

Neha Jain said...

In first program, output X and Y should be on second line because of println. Hence it should display:
ch1 and ch2:
X Y

Arun Motoori said...

@Neha Updated. Thanks.

ShivvBlog said...

I got out put as like Arun mentioned in first program: i didn't get it as like

ch1 and ch2:
X Y

Here is my program:
class Chardemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1=88;
ch2='y';
System.out.print("ch1 and ch2 ");
System.out.println(ch1+" "+ch2);
}
}

sandip said...

@ShivvBlog: your answer is correct, as well as Arun's output is correct. See in the first line of print"print" is used and that makes all the difference. Use "println" in place "print" and you will have both the output in different lines.

Blog Index