Now that we have defined the different primitive data types, we can start looking into how can we use variables of the different data types and perform operations with them.
The operations are specified via operators that will take one or more operands and return a resulting value.
As is the case in most programming languages, you can perform simple arithmetic operations between variables in Java as well, and where possible the symbols/operators used follow the ones used in mathematics, i.e. + for addition, - for subtraction, * for multiplication, / for division. The one that doesn’t follow the mathematical convention is the % that is used to calculate the remainder of a division.
To elaborate with some examples:
int cores = 4;
int memoryInGB = 256;
// The + symbol is used for addition
int result1 = memoryInGB + 256;
// result1 is 512
System.out.println(memoryInGB + " + 256 = " + result1);
// The - symbol is used for subtraction
int result2 = cores - 3;
// result2 is 1
System.out.println(cores + " - 3 = " + result2);
// The * symbol is used for multiplication
int result3 = cores * 2;
// result3 is 8
System.out.println(cores + " * 2 = " + result3);
// The / symbol is used for division
int result4 = cores / 2;
// result4 is 2
System.out.println(cores + " / 2 = " + result4);
// The % symbol is used to get the remainder of a division
int result5 = cores % 3;
// result5 is 1
System.out.println(cores + " % 3 = " + result5);
Output:
256 + 256 = 512
4 - 3 = 1
4 * 2 = 8
4 / 2 = 2
4 % 3 = 1
The plus sign and String objects
The plus sign in Java, when used with String objects, provides us with String concatenation. You have seen it in several of the examples we’ve shown in this course, like in all the System.out.println(…)
invocations in the example above.
Another example:
String start = "This is a ";
String end = "sentence";
System.out.println(start + end);
Output:
This is a sentence
In this case, we are concatenating 2 objects of type String, printing out This is a sentence
as a result.
If one of the operands is a String and the other operand is not of type String, Java will convert it into a String value for concatenation.
String concatenation using the plus sign is not recommended for code where performance is a concern. Take a look at StringBuilder and StringBuffer that you can use for that purpose depending on your needs. We’ll cover both of these in a separate course. |