Free Java Tutorials >> Table of contents >> Expressions

1. Expressions and Variables

What is an expression

Take a look at this program:

public class MyProgram {
    public static void main(String[] args) {
        System.out.println("Hi"); //A String expression
		System.out.println(42);   //An int (integer) expression
		System.out.println(4.2);  //A double (floating point decimal) expression
		System.out.println('#');  //A char (character) expression
    }
}

Expressions are values that become a piece of information. As we see above, information can be a number, some text, or even a single character. We will see more complex expressions later, such as 1+2, which becomes the int 3. However, the important thing to note for now is that you cannot run an expression in Java. Only statements (so far all ending in semicolons) can run.

Expression Types

Expressions in Java have a type. We will see later on that there are actually eight different fundamental "primitive types" in Java: byte, short, int, long, float, double, boolean, and char. However, we will start with three types:

  • The primitive int type, which stores an integer (whole number). Because of the way Java stores ints (32-bit signed two's complement), the biggest int is 2 to the power of 32 minus 1, or 2147483647. The smallest int is -2147483648. For example: 4, 1, -5, 0, and 2001 are all ints.
  • The primitive double type, which stores floating point numbers (decimal values). For example, 4.2, 1.00003, and 10.0 are all doubles . Note that some editors (such as Processing) use the "float" type instead of double. Advanced programmers should note that doubles are 64 bit IEEE 754 floating point values.
  • The object String type, which stores multiple characters. For example, "Cat", "Hello World", and "#dicey" are all strings.

Variable declarations

You can store and re-use an expression in a variable. A variable is a container that equals some value. For example, we can create a variable in this variable declaration int x = 5;, and output it with println:

public class MyProgram {
    public static void main(String[] args) {
		int x = 5;  //A variable declaration
        System.out.println(x);  //This does not output "x", it outputs 5
		
		double y = 2.5; //A decimal number equal to 2.5
		System.out.println(y);
		
		String z = "mimi the cat"; //A string (multi-characeter) type
		System.out.println(z);
		
		//Print "mimi the cat ate 5 cakes. Yum!"
		System.out.print(z);
		System.out.print(" ate ");
		System.out.print(x);
		System.out.print(" cakes.");
		System.out.println(" Yum!");
    }
}

Variable declarations are always variable_type variable_name; and usually we use the form variable_type variable_name = initial_value. These are all legal variable declarations

Thus, in our example int x = 5;, the variable type is int. The variable name here is x, and the initial value is 5.

Advanced programmers should note that you can create multiple variables of the same type with this notation:

public class MyProgram {
    public static void main(String[] args) {
		int var = 5, varyay = 42;    //varyay is also an int of value 42
        System.out.println(var);     //5
		System.out.println(varyay);  //42
    }
}

One equal "=" means assignment

Unlike in math, = means "put the right side into the left side". The direction (from right to left) matters. Thus, after creating a variable, you can assign it a new value. You cannot create variables with the same name more than once (until we learn about methods and classes). Thus, simply reassign variable values like so:



			
Run

2. Swapping Values

A temporary variable

Take a look at this program:

public class MyProgram {
    public static void main(String[] args) {
        int x = 5;
		int y = 4;
    }
}

How do we swap x and y such that x equals 4 and y equals 5? One way is like this:

public class MyProgram {
    public static void main(String[] args) {
        int x = 5;
		int y = 4;
		
		//Begin swapping x and y:
		x = 4;
		y = 5;
		System.out.println(x); //prints 4
		System.out.println(y); //prints 5
    }
}

But if we did did not know what x and y were before the swap, this would not work.

Let's try using a temporary variable to save the value of x:



			
Run

3. "Casting" to change variable types

Java is strictly ("strongly") typed

You may have already made an error like this:

public class MyProgram {
    public static void main(String[] args) {
        double appleCost = 2.5;
		double orangeCost = 3.5;
		
		//This line is an ERROR:
		int average = (appleCost + orangeCost)/2; 
		
		System.out.println("The average cost is:");
		System.out.println(average);
    }
}

Java's variables and expressions usually cannot automatically be converted from one type to another. Even a simple line of code line int x = 2.0; will fail, because 2.0 is a double, and you cannot put a double into an int.

Type Casting

To convert between one type and another, you must perform a "type cast". Sometimes people will just call this a "cast":

public class MyProgram {
    public static void main(String[] args) {
        double appleCost = 2.5;
		double orangeCost = 3.5;
		
		double decimalAverage = (appleCost + orangeCost)/2; 
		
		//(int)decimalAverage converts decimalAverage to an int:
		int average = (int)decimalAverage;
		
		System.out.println("The average cost is:");
		System.out.println(average); //prints 3
    }
}

You can freely convert between any of the eight primitive types. Thus all these lines compile and run:

public class MyProgram {
    public static void main(String[] args) {
        int a = (int)2.2; //Becomes 2
		int b = (int)2.9; //Also becomes 2
		int c = (int)5;   //Casts an int to an int, which is not exciting
		double d = (double)5;  //5.0
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
		System.out.println(d);
    }
}

You cannot use casting for strings

We will learn the Integer.parseInt, Float.parseFloat, Double.parseDouble, and toString (with radix) functions later. For now, do not try to cast a String or any double quoted text.

Truncation

When you cast from a decimal type (like a double or float) to an integer (byte, short, int, or long), the non-integer portion is removed. Thus, (int)9.99 is the same as 9. (int)-9.99 becomes -9. Notice that this is different from rounding down, since negative numbers get rounded up.

Go ahead and try casting between different variable types:

Warning for advanced programmers: the operator precedence of casting is very high. (int)3.5+2.5 is the same as ((int)(3.5)) + 2.5, which is 5.5. Use parenthesis to cast an arithmetic expression. For example: (int)(3.5+2.5) becomes 6.



			
Run

Previous: Hello World

Next: Arithmetic