public class IntToStringExample1
{
public static void main(String args[])
{
int i = 200;
String s = String.valueOf(i);
System.out.println(i + 100); // 300 because + is binary plus operator
System.out.println(s + 100); // 200100 because + is string concatenation operator
}
}
Step-by-Step Explanation
1. Class Declaration:
public class IntToStringExample1 {
The class IntToStringExample1 is declared. This class contains the main method where the program logic resides.
2. Main Method:
public static void main(String args[]) {
The main() method is the entry point of the Java application. This is where the execution begins.
3. Integer Declaration:
int i = 200;
An int variable i is declared and initialized with the value 200.
4. Converting Integer to String:
String s = String.valueOf(i);
- String.valueOf(i) converts the integer i (which is 200) to a string.
- The result is the string “200” stored in the variable s.
5. First Println (Integer Addition):
System.out.println(i + 100); // 300 because + is binary plus operator.
- The expression i + 100 is evaluated.
- As i is an integer (200) and 100 is an integer, too, the + operator performs binary addition, summing the two integer values together.
- The result of 200 + 100 is 300 and this gets printed to the console.
6. Second Output (String Concatenation):
System.out.println(s + 100); // 200100 because + is string concatenation operator
- The expression s + 100 is evaluated.
- Here s is a string (“200”), and 100 is an int. When this line is read by the program in Java the + operator acting on a string and an integer will result in the conversion of the int into a string as well and it then strings which are then combined.
- Therefore the result of the “200”+100 statement on the screen becomes “200100” to output.
Output
There is following Output to console.
300
200100
Explanation of the Output
- First Output (300): The + operator does integer addition since the two operands i and 100 are integers.The result of 200 + 100 is 300, which prints.
- Second Result (200100): The + operator is applied for string concatenation since one of the operands (s) is a string (“200”), and the other operand (100) is an integer. The integer 100 is converted to the string “100”, and then the two strings (“200” and “100”) are concatenated, yielding the string “200100”, which is printed.
1. Integer Addition: When the operands are both integers, + executes binary addition and simply adds the numbers together.
2. String Concatenation: When one operand is a string and the other is some other type (like a number), Java converts the number to a string, then concatenates the two strings together.
int i = 200; // Integer value 200
String s = String.valueOf(i); // Convert integer 200 to string “200”
System.out.println(i + 100); // 200 + 100 = 300 (integer addition)
System.out.println(s + 100); // “200” + 100 = “200100” (string concatenation)