Addition and Concatenation in Java


'+' operator in java can be used to add numbers and concatenate strings. Following rules should be considered.

  • Only numbers as operands then result will be a number.

  • Only strings as operands then result will be a concatenated string.

  • If both numbers and strings as operands, then numbers coming before string will be treated as numbers.

  • If both numbers and strings as operands, then numbers coming after string will be treated as a string.

  • Above rule can be overridden using brackets().

Example

Create a java class named Tester.

Tester.java

Live Demo

public class Tester {
   public static void main(String args[]) {      
      //Scenario 1: Only numbers as operands to + operator
      System.out.print("Scenario 1: (1 + 2)  = ");      
      System.out.println(1 + 2);

      //Scenario 2: Only Strings as operands to + operator
      System.out.print("Scenario 2: (\"tutorials\" + \"point.com\") = ");      
      System.out.println("tutorials" + "points.com");

      //Scenario 3: both numbers and strings as operands to + operator
      //numbers will be treated as non-text till a string comes
      System.out.print("Scenario 3: (1 + 2 + \"tutorials\" + \"point.com\") = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com");

      //Scenario 4: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      System.out.print("Scenario 4: (1 + 2 + \"tutorials\" + \"point.com\" + 3 + 4 ) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + 3 + 4);

      //Scenario 5: both numbers and strings as operands to + operator
      //if string comes first, numbers will be treated as text.
      //Use brackets to treat all numbers as non-text
      System.out.print("Scenario 5: (1 + 2 + \"tutorials\" + \"point.com\" + (3 + 4)) = ");      
      System.out.println( 1 + 2 + "tutorials" + "points.com" + (3 + 4));
   }
}

Output

Compile and Run the file to verify the result.

Scenario 1: (1 + 2)  = 3
Scenario 2: ("tutorials" + "point.com") = tutorialspoints.com
Scenario 3: (1 + 2 + "tutorials" + "point.com") = 3tutorialspoints.com
Scenario 4: (1 + 2 + "tutorials" + "point.com" + 3 + 4 ) = 3tutorialspoints.com34
Scenario 5: (1 + 2 + "tutorials" + "point.com" + (3 + 4)) = 3tutorialspoints.com7

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

912 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements