Content area
Full Text
Java applications process 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. You'll also learn about important concepts such as operator overloading and operator precedence, and you'll see a demonstration of primitive-type conversion. I'll conclude with a small Java program that you can use to practice primitive-type conversions on your own.
Note that the Java programming examples in this tutorial are based on Java 12.
download
Get the code
Download the source code for Java programming examples used in this tutorial. Created by Jeff Friesen for JavaWorld.
Simple expressions
A simple expression is a literal, variable name, or method call. No operators are involved. Here are some examples of simple expressions:
52 // integer literal
age // variable name
System.out.println("ABC"); // method call
"Java" // string literal
98.6D // double precision floating-point 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); System.out.println("ABC"); is void (void) because it returns no value; "Java" is a string (String); 98.6D is a 64-bit double precision floating-point value (double); and 89L is a 64-bit long integer (long). We don't know age's 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:
$1 ==> 52
$1 is the name of a scratch variable that jshell creates to store 52. (Scratch variables are created whenever literals are entered.) Execute System.out.println($1) and you'll see 52 as the output.
You can run jshell with the -v command-line argument (jshell -v) to generate verbose feedback. In this case, entering 52 would result in the...