I am learning Java.
I am supposed to write a program that converts all uppercase letters to lowercase and all lowercase to uppercase. It said in the book I just need to subtract 32 from uppercase and add 32 to lowercase.
Here is my code...
class Caseconv {
public static void main(String args[])
throws java.io.IOException {
char ch;
do {
ch = (char) System.in.read();
if (ch >= 97 & ch <= 122) ch = ch - 32;
if (ch >= 65 & ch <= 90) ch = ch + 32;
System.out.print(ch);
} while (ch != '\n');
}
}
But the compiler doesn't want to do this, I get this error.
Caseconv.java:13: error: possible loss of precision
if (ch >= 97 & ch <= 122) ch = ch - 32;
^
required: char
found: int
Caseconv.java:14: error: possible loss of precision
if (ch >= 65 & ch <= 90) ch = ch + 32;
^
required: char
found: int
2 errors
What am I supposed to be doing to subtract from the char?
You need to add a type cast to convert the result of the expression to char
. For example.
ch = (char)(ch + 32)
Notes:
The reason this is necessary is because 32
is an int
literal, and the addition of a char
and an int
is performed using int
arithmetic, and gives an int
result.
Assigning an int
to a char
potentially results in truncation. Adding the type cast effectively says to the compiler: "Yes. I know. It is OK. Just do it."
The parentheses around the +
subexpression are necessary because type-cast has higher precedence than +
. If you leave them out, the type-cast makes no difference because it "casts" a char
to a char
.
Type casting is required, try this code:
if (ch >= 97 & ch <= 122)
ch = (char) (ch - 32);
if (ch >= 65 & ch <= 90)
ch = (char) (ch + 32);
The result of arithmetic
between a char
and an int
is an int
and you cannot store an int
in a char
without explicit typecasting
- by which you tell to compiler that I know what I'm doing, now do it for me
So, you need to do a typecast: -
char ch = 'a';
if (ch >= 97 & ch <= 122) {
ch = (char)(ch - 32);
}
System.out.println(ch); // Prints `A`
But, you have already method
in Character
class, that will do it for you: -
char ch = 'a';
ch = Character.toUpperCase(ch);
System.out.println(ch); // Prints `A`
Try
ch = (char) (ch + 32);
if you're sure that ch + 32 won't be bigger than what a char can hold.
That is because you trying to assign an int value (Ascii value) to the char. But you need to explicitly convert the result value int to char. Just cast int to char.
ch= (char) (ch+32);
ch= (char) (ch-32);
It will work with out any Exception.