In this java examples of java tutorial, we will study about Java operators example and we will study about Java plus operator or Java + operator. We will study about Java plus operator with example and why we use Java plus + operator.
What is Plus(+) operator in Java
Plus operator is one of the Java operator in Java programming language. Sign of the plus operator in <strong>+</strong>
.
Plus operator is widely used in Java Programming language. Plus operator has couple of uses in Java.
Purpose of plus operator in Java
Now, we will talk about the purpose of plus operator in Java or why plus operator is used. As its name suggest, it will plus means it will add the numbers or numeric values, i.e correct, but when same plus operator is used to Java Strings, it perform differently.
Plus operator is used in both with Strings and integers, but the purpose of plus operator is different in both the cases.
Plus operator with Strings
Strings are combination of character values and String is one of the data type in Java language. Use of Plus (+) operator is strings is to concatenate two or more Strings.
Example of plus operator with String
Let’s see one example where plus operator is used to concatenate two or more String.
# Write a program to display firstName and lastName as fullName in Java
public class JavaExamples { public static void main(String[] args) { //Java plus operator with String example in Java String firstName="Byte"; String lastName="Array"; String fullName=firstName + lastName; System.out.print("fullName is:"+fullName); } }
Output
fullName is:ByteArray
Explanation
In the above java plus operator with Strings example, There are two String variables firstName
and lastName
. These two variables are concatenated through java plus operator + and concatenated value is saved into third variable fullName
.
Plus operator with integers
Integers are numeric values like 1,2,3 etc. Use of plus operator with integers is to add the integer values like if two integers 5 and 6 are used with plus operator, then it will become plus operation (addition program).
Example of plus operator with integers
Let’s see the example where plus operator is used with integers in Java.
#Program to find the sum of two given numbers 10,20.
public class JavaExamples { public static void main(String[] args) { //Java plus operator with integers example in Java by ByteArray.in int firstNumber=10; int secondNumber=20; int sum=firstNumber + secondNumber; System.out.print("sum is:"+sum); } }
Output
sum is:30
Explanation
In above Java plus operator with integers example, there are two integer variables firstNumber
and secondNumber
.
when plus operator is applied on two integers, it add up the integers and value is stored in third variable i.e sum
variable.