In Java, integer is a primitive data type that represents a 32-bit signed two’s complement integer. This means that an int variable can hold any whole number between -2,147,483,648 and 2,147,483,647, inclusive. The int data type is frequently used for numeric values in Java, such as counting and indexing in loops, storing numerical values in variables, and performing arithmetic operations. It is also commonly used as the return type of methods that perform integer calculations.
Ways to Print an Integer in Java :
1. Using the System.out.println() method:The System.out.println() method is the easiest way to print an integer to the console.
Syntax :
int num = 1234;
System.out.println(num);
2. Using the System.out.printf() method with format specifiers:The System.out.printf() method is another way to print an integer to the console.
Syntax :
int num = 1234;
System.out.printf("%d", num);
3. Using the String.valueOf() method to convert the integer to a string:The String.valueOf() method is a static method that converts an integer to a string.
Syntax :
int num = 1234;
String numStr = String.valueOf(num);
System.out.println(numStr);
4. Using the Integer.toString() method to convert the integer to a string:The Integer.toString() method is a static method that converts an integer to a string.
Syntax :
int num = 1234;
String numStr = Integer.toString(num);
System.out.println(numStr);
5.Using the StringBuilder class to build a string containing the integer:The StringBuilder class is a mutable string class that can be used to convert an integer to a string.
Syntax :
int num = 1234;
StringBuilder sb = new StringBuilder();
sb.append(num);
System.out.println(sb.toString());
public class Main {
public static void main(String[] args) {
int i = 1234;
// Using the System.out.println() method:
System.out.println(i);
// Using the System.out.printf() method with format specifiers:
System.out.printf( "%d", i);
}
}
Output :
1234
1234
Explanation : In this Example we have used different ways to print the Integer on the console .The first method we used is System.out.Println and the second method is printf .
public class Main {
public static void main(String[] args) {
int i = 13545;
// Using the String.valueOf() method to convert the integer to a string:
System.out.println(String.valueOf(i));
// Using the Integer.toString() method to convert the integer to a string:
System.out.println(Integer.toString(i));
// Using the StringBuilder class:
System.out.println(new StringBuilder().append(i).toString());
}
}
Output :
13545
13545
13545
Explanation : In this example we have used three different ways to print the Integer value like using valueOf() Method
, toString() and StringBuilder() method .
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment