This Java program demonstrates how to convert different data types to int
.
The code first declares some variables of different data types: doubleNum
, str
, ch
, and longInt
.
Next, the program performs the following conversions:
double
to int
: The double
value doubleNum
is cast to an int
using the (int)
type casting operator. The result of this conversion is stored in intNum
.String
to int
: The String
value str
is converted to an int
using the Integer.parseInt
method. The result of this conversion is stored in intStr
.char
to int
: The char
value ch
is implicitly converted to an int
by assigning it to the int
variable intChar
.long
to int
: The long
value longInt
is cast to an int
using the (int)
type casting operator. The result of this conversion is stored in intLong
.Finally, the program prints out the results of the conversions to the console using the System.out.println
method.
public class ConversionToInt {
public static void main(String args[]){
double doubleNum = 1.6;
String str = "123";
char ch = '4';
long longInt = 200000;
int intNum =(int)doubleNum;
int intStr = Integer.parseInt(str);
int intChar = ch;
int intLong = (int)longInt;
System.out.println(intNum);
System.out.println(intStr);
System.out.println(intChar);
System.out.println(intLong);
}
}
1
123
52
200000