Chapter 2d - Char Data Type
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':
char x = 'a';
System.out.print(x);
๐งช Try the code out!
The ASCII codeโ
char x = 97;
System.out.println(x); //Should print 'a'
๐งช Try the code out!
Upper and Lower Caseโ
public class Main
{
public static void main(String[] args)
{
char ch1 = 'a';
char ch2 = 'B';
System.out.println(Character.toUpperCase(ch1));//converts lowercase to uppercase
System.out.println(Character.toLowerCase(ch2));//converts uppercase to lowercase
}
}
๐งช Try the code out!
Chars and ASCII In Practiceโ
โ Try the following examples in this playground
What happens when we try to store a char value in an integer?
public class Main {
public static void main(String args[]) {
int val='A';
System.out.println("val = " +val);
}`
}
What happens when we typecast an int value to a char type?
public class Main {
public static void main(String[] args) {
int x = 5;
char y = (char)x;
System.out.println(x + y);
}
}
What happens we try to add a char to an integer?
Java will take ASCII value of char and add it to the int, so the result will be unpredicted. Try this:
int x = 5;
char y = '5';
System.out.println (x + y);
OUTPUT: 58 (because it will take ASCII value of '5' that is 53 and add it to 5)
What is the output seen when combining int and String variables?
if x = 5 and y = โ6โ, then output is 56 (string concatenation). Anything added to string is converted to string in java.
public class Main {
public static void main(String[] args)
{
int x = 5;
String y = "6";
System.out.println(x + y);
}
}