The int keyword is a primitive data type in Java. An int data type can hold values ranging from -231(-2147483648) to 231-1 (2147483647).
public class JavaExample { public static void main(String[] args) { int num = 123456; System.out.println(num); } }
Output:
123456
Note:
- Size of the integer is 32 bit (4 bytes).
- The default value of int type variable is 0.
Keyword int as a return type of a method
Here, we have a method with int return type. A method with int return type returns an integer value. In the following example, the method add()
accepts two int arguments and returns sum (which is an int value) of these arguments as a result.
public class JavaExample { //return type is int public static int add(int a, int b){ return a+b; } public static void main(String[] args) { int sum = add(10,20); System.out.println(sum); } }
Output:
30
Can int variable hold float or double value?
An int type variable cannot hold double or float value as they are incompatible types. When we run the following program, it throws an error as shown in the output screenshot.
public class JavaExample { public static void main(String[] args) { int a = 5.55; //double value System.out.println(a); } }
Output:
Similarly when float value is assigned to an int variable, the programs throws an error as shown below:
public class JavaExample { public static void main(String[] args) { int a = 5.55f; //float value System.out.println(a); } }
Output:
What happens when a char value is assigned to an int variable in Java?
When char values are assigned to the int type variables, the int variables holds the ASCII values of the assigned chars. In the following example, the variable a
prints ASCII value 65 (which represents the uppercase A) and the variable b
prints the value 97 (ASCII value of small case a).
public class JavaExample { public static void main(String[] args) { int a = 'A'; //char value int b = 'a'; //It prints the ASCII values of the assigned characters System.out.println(a); System.out.println(b); } }
Output
65 97