Evaluate Java expressions with operators

A complete guide to the Java operator types and writing Java expressions in Java 12

Table of Contents

Evidence More

Coffee applications procedure data by evaluating expressions, which are combinations of literals, method calls, variable names, and operators. Evaluating an expression typically produces a new value, which can be stored in a variable, used to make a decision, and so on.

In this tutorial, you will learn how to write expressions for your Java programs. In many cases you'll use operators to write your Java expressions, and there are many types of operators to know how to use. I'll briefly introduce Java's operator types (including the additive, bitwise, logical, conditional, shift, and equality types) and their operands. Y'all'll also learn about of import concepts such as operator overloading and operator precedence, and y'all'll meet a sit-in of primitive-blazon conversion. I'll conclude with a small-scale Coffee program that you tin use to practice primitive-blazon conversions on your own.

download

Download the source lawmaking for example applications in this tutorial. Created by Jeff Friesen for JavaWorld.

Elementary expressions

A uncomplicated expression is a literal, variable name, or method call. No operators are involved. Hither are some examples of uncomplicated expressions:

                52                         // integer literal age                        // variable proper noun Arrangement.out.println("ABC"); // method call "Java"                     // string literal 98.6D                      // double precision floating-indicate literal 89L                        // long integer literal              

A simple expression has a type, which is either a primitive type or a reference type. In these examples, 52 is a 32-bit integer (int);Organization.out.println("ABC"); is void (void) because information technology returns no value;"Java" is a string (Cord);98.6D is a 64-bit double precision floating-indicate value (double); and 89L is a 64-flake long integer (long). We don't know historic period'due south type.

Experimenting with jshell

You can easily try out these and other simple expressions using jshell. For example, enter 52 at the jshell> prompt and you'll receive something like the following output:

                $ane ==> 52              

$1 is the name of a scratch variable that jshell creates to shop 52. (Scratch variables are created whenever literals are entered.) Execute System.out.println($1) and yous'll see 52 equally the output.

Y'all can run jshell with the -v command-line argument (jshell -v) to generate verbose feedback. In this instance, entering 52 would event in the post-obit message, revealing that scratch variable $i has int (32-bit integer) type:

                |  created scratch variable $1 : int              

Next, try entering age. In this example, yous'll probably receive an fault message that the symbol was not establish. The Java Shell assumes that age is a variable, but it doesn't know its blazon. You would have to include a type; for example, see what happens if yous enter int age.

Compound expressions

A compound expression consists of one or more unproblematic expressions integrated into a larger expression via an operator, which is a sequence of instructions symbolically represented in source code. The operator transforms its expression operand(s) into another value. For instance, in 6 * 5, the multiplication operator (*) transforms operands 6 and 5 into 30.

Compound expressions can be combined into larger expressions. For instance, 6 * 5 + 10 presents compound expression vi * 5 and a chemical compound expression consisting of their product, improver operator +, and the number 10. The club of evaluation (multiply first and then add) is dictated by Java's rule of precedence, which nosotros'll become to before long.

Operators and operands

Java's operators are classified past their number of operands:

  • A unary operator has ane operand, for case unary minus (e.g., -5).
  • A binary operator has two operands, examples are multiplication and addition.
  • A ternary operator has three operands; an instance is the conditional operator (?:).

Java's operators are also classified by position:

  • A prefix operator is a unary operator that precedes its operand (e.g., -5).
  • A postfix operator is a unary operator that follows its operand (due east.g., age++; -- add ane to historic period's numeric value).
  • An infix operator is a binary or ternary operator between the operator'southward operands (e.g., historic period + v).

Another jshell example

I'll introduce more operators in the post-obit sections, where I present examples in the form of applications. Y'all could also try out these operators with jshell, like and so:

                jshell> 6 + ii $1 ==> viii  jshell> seven * $1 $2 ==> 56              

In this case, we first enter expression 6 + 2, which jshell evaluates, assigning the resulting 8 to scratch variable $1. Next, nosotros multiply $one past 7, which stores 56 in scratch variable $2. This case demonstrates that you tin use scratch variables in Java expressions.

Operator types in Java

Condiment operators

The additive operators increase or decrease a numeric value through addition and subtraction. Additive operators include addition (+), subtraction (-), postdecrement (--), postincrement (++), predecrement (--), and preincrement (++). String concatenation (+) is besides considered to be additive. Here's a formal definition for each of these operators:

  • Addition: Given operand1 + operand2 , where each operand must exist of character or numeric type, add operand2 to operand1 and return the sum. Example: 4 + 6.
  • Subtraction: Given operand1 - operand2 , where each operand must be of graphic symbol or numeric type, decrease operand2 from operand1 and render the difference. Instance: 4 - 6.
  • Postdecrement: Given variable--, where variable must exist of character or numeric blazon, subtract 1 from variable 's value (storing the result in variable ) and return the original value. Example: x--;.
  • Postincrement: Given variable++, where variable must be of character or numeric type, add 1 to variable 'south value (storing the consequence in variable ) and return the original value. Example: x++;.
  • Predecrement: Given --variable , where variable must exist of character or numeric type, subtract 1 from its value, store the outcome in variable , and return the new decremented value. Case: --ten;.
  • Preincrement: Given ++variable , where variable must be of grapheme or numeric type, add i to its value, store the result in variable , and return the new incremented value. Example: ++ten;.
  • Cord concatenation: Given operand1 + operand2 , where at least one operand is of String type, append operand2 'southward string representation to operand1 'due south string representation and return the outcome. Instance: "A" + "B".

The addition, subtraction, postdecrement, postincrement, predecrement, and preincrement operators can generate values that overflow the limits of the result type. For example, adding two large positive 64-scrap integer values can produce a value that cannot be represented in 64 $.25. The resulting overflow is not detected or reported by Java'due south additive operators.

Instance awarding: Additive operators

Listing 1 presents a small application for playing with Java'due south additive operators.

Listing 1. Additive operators in Java (AddOp.java)

                class AddOp {    public static void main(String[] args)    {       System.out.println(125 + 463);       Organisation.out.println(two.0 - 6.3);       int historic period = 65;       Organisation.out.println(historic period);       System.out.println(historic period--);       System.out.println(age++);       System.out.println(--age);       Organisation.out.println(++age);       System.out.println("A" + "B");    } }              

You lot learned in the previous tutorial how to use the JDK'southward javac tool to compile Java source lawmaking and the java tool to run the resulting application. Execute the following command to compile Listing 1:

                javac AddOp.java              

Bold successful compilation, y'all should notice an AddOp.class file in the electric current directory. Execute the following control to run it:

                coffee AddOp              

AddOp responds by producing the following output:

                588 -four.iii 65 65 64 64 65 AB              

Studying this output offers insight into the postincrement, postdecrement, preincrement, and predecrement operators. For postincrement/postdecrement, age's current value is output before the increment/decrement performance. For preincrement/predecrement, the operation is performed and its event is stored in age, and then age's new value is output.

Array alphabetize operator

The assortment index operator ([]) accesses an assortment element past providing the chemical element's index (position). This operator is placed after the assortment variable's name, as in grades[0] (admission the first element in the array assigned to grades; the get-go chemical element is stored at index 0). Here'due south a formal definition:

Given variable[index], where index must be of integer (int) type, read a value from or store a value into variable 's storage element at location index . Example: temperatures[1]

The value passed to index is a 32-scrap integer that is either 0 or a positive value ranging to one less than the array's length, which is indicated by appending .length to the name of the assortment. For example, grades.length returns the number of elements in the array assigned to grades.

Instance application: Array index operator

List 2 presents the source lawmaking to an example awarding that lets yous play with the array index operator.

Listing 2. Assortment alphabetize operator in Java (ArrayIndexOp.coffee)

                class ArrayIndexOp {    public static void main(Cord[] args)    {       int[] grades = { 89, 90, 68, 73, 79 };       System.out.println(grades[ane]);       grades[i] = 91;       Arrangement.out.println(grades[1]);       int index = 4;       System.out.println(grades[index]);       System.out.println(grades['C' - 'A']); //      System.out.println(grades[1D]);    } }              

Listing 2 is somewhat more interesting than Listing 1. After creating a five-chemical element, 1-dimensional array of integers (via an array initializer) and assigning the assortment'due south reference to grades, main() proceeds to access various elements. Two items are of special interest:

  • The array index operator's index must ultimately be a 32-bit integer (0 or a positive value). You can specify the proper name of an integer variable (e.g., index), which contains the index value, as the index.
  • You can specify a adding involving character literals. (Later in this tutorial I'll introduce type conversions, and you'll notice why 'C' - 'A' produces an integer (ii), which serves as a valid index.)

The final instance, which passes 1D as an index to the assortment alphabetize operator, is commented out because information technology will not compile. If you uncomment the line and attempt to compile Listing ii, you volition receive an fault message most incompatible types: "possible lossy conversion from double to int.."

Compile Listing 2 (javac ArrayIndexOp.java) and run the application (java ArrayIndexOp). Yous should notice the following output:

                xc 91 79 68              

Assignment operators

The assignment operator (=) assigns an expression'southward value to a variable (e.g., i = 6;), including an array element (e.k., x[0] = fifteen;). The expression and variable must be assignment compatible, significant their types must agree. For example, you lot cannot assign a cord literal to an integer variable. I'll explain more about this when nosotros hash out type conversions.

The compound assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=) evaluate expressions and assign the results to variables in 1 step. Each expression and variable must exist assignment uniform. Each operator serves as a useful shortcut. For example, instead of specifying 10 = ten + three;, y'all can specify the shorter and equivalent x += three;.

Bitwise operators