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.Notes:
The reason this is necessary is because
32is anintliteral, and the addition of acharand anintis performed usingintarithmetic, and gives anintresult.Assigning an
intto acharpotentially 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” acharto achar.