Addition And Concatenation
Addition And Concatenation in Java
In this article we will be discussing about Addition and Concatenation in Java.
Addition and Concatenation is an example of polymorphism in Java. “+” operator is used to add or concat two Integers or Strings.
Addition
An Addition (‘+’) operator in Java is a binary operator and takes two operands. When the operands that are passed to the ‘+’ operator are numbers, an addition operation that returns the sum of two numbers is performed.
Example:
import java.util.*; public class Main{ public static void main(String[] args){ // Initializing variables int a = 10 int b = 20; // Printing the sum of the two variables System.out.println(a+b); } }
Output: 30
Concatenation
When operands change to String type, the ‘+’ operator does not add the String objects but concatenates or joins the contents of the string to form a resultant third string.
Example:
import java.util.*; public class Main{ public static void main(String[] args){ // Initializing the String Variables String str1 = "Prep"; String str2 = "Insta"; // Printing the concatenation of two Strings System.out.println(str1+str2); } }
Output: PrepInsta
Addition and Concatenation
When two operands changes to String type and in integer type as well i.e. of of the operand is number and other of the operand is String or a character, the ‘+’ operator does not add the String objects and integer objects but concatenates or joins the contents of the string and integer to form a resultant third string.
Example:
import java.util.*; public class Main{ public static void main(String[] args){ // Initializing the integer variable int a = 100; // Initializing the integer variable String str2 = "Insta"; System.out.println(a+str2); } }
Output: 100Insta
Output Explanation: This unpredictable output is caused by the compiler evaluating the given expression from left to right because the operators have equal precedence. Once it encounters a string, it treats the rest of the expression as a string (again based on the order of precedence of the expression).
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment