JAVA
in this blog we will explain type casting and ASCII codes in java
To explain the type casting let us ask question , if we have the code this code bellow , what the value will store in the variable num at the end of this code ?
public class test{
public static void main(String[]args){
int num;
num = 7/2;
}
}
yes , you are right num will contain 3 , but let me ask another two questions , is 7/2 really equals 3 ? and why it's contain 3 , not 3.5 ?
of course it's contain 3 because it's defined as integer variable , and if we want to store a decimal number on it , we have to convert it from integer to double or float , in another words we have to make type casting for it
So , the Type Casting in java is The process of converting the value of one primitive data type to another data type
so now we can say that "we can change either the value of a variable or it's data type
And the ASCII is a code for representing English characters as numbers, each letter of english alphabets is assigned a number ranging from 0 to 127
Now let us give an example to explain all of this ,
Q: write a java program in which you define a variable that contain one English letter , then the program must check if the letter is in big case , convert it to small case , and the opposite
So the code can be just as :
public class test{
public static void main(String[]args){
char letter = 'A';
if((int)letter >= 65 && (int)letter < 97){
letter = (char)((int)letter+32);
System.out.println("the letter was capital converted to small "+letter);
}
if((int)letter <= 129 && (int)letter >= 97){
letter = (char)((int)letter-32);
System.out.println("the letter was small converted to capital "+letter);
}
}
}
and the output will be as bellow
No comments:
Post a Comment