2. Generating Outputs in Java

  • In Java, the + symbol is used to join (combine) text and numbers when displaying output.
  • This process is called string concatenation (which simply means “joining text together”).
  • Example:

public class joinTextnNum{
  public static void main(String[] args) {
    int age = 20;
    System.out.println("I am " + age + " years old.");
  }
}
    
  • Java automatically converts the number 20 into text and joins it with "I am " and " years old.".

  • Example 2: Performing Calculations Before Joining

If we want to perform a calculation before displaying the result, we must use parentheses ().


public class joinTextnNum{
  public static void main(String[] args) {
    int num = 10;
    System.out.println("Double of " + num + " is " + (num * 2));

  }
}
    
  • Java calculates num * 2 first (because of the parentheses), then joins it with the text.

⚠️ Common Mistake

If you forget the parentheses, Java will join the text first, then add the number as text instead of doing the math:


public class joinTextnNum{
  public static void main(String[] args) {
    System.out.println("10 + 5 = " + 10 + 5);
  }
}
    

Fix: Use parentheses () to ensure the calculation happens first:


public class joinTextnNum{
  public static void main(String[] args) {
    System.out.println("10 + 5 = " + (10 + 5));
  }
}
    

What is the output of the following Java code?

int num = 10;
System.out.println("Double of " + num + " is " + (num * 2));

Pages: 1 2 3