Java Code Example: convert specific datatype to int

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:

  1. Converting a 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.
  2. Converting a 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.
  3. Converting a char to int: The char value ch is implicitly converted to an int by assigning it to the int variable intChar.
  4. Converting a 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);  
  }
}
Output
1
123
52
200000