Elements of Java Programs

Programs (also called applications or scripts) in just about any language feature expressions, variables, and types. What do these things look like in Java?

The Basic Java Application

All Java programs are made up of one or more classes. Classes have fields, methods and constructors. If you are writing a standalone Java application, there must be a method in its "main class" which is public, static, void, named main, defined with only one parameter of type String[].

public class Greeter {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

Don't worry about all that crazy terminology just now.... It will all become clear later.

Java Types

Programs manipulate values. A type is (essentially) a set of values. Values are expressed in a program with literals.

Java has eight, and only eight, primitive types:

The 8 Primitive Types
TypeExample
Literals
Description
boolean true
false
The two truth values true and false.
byte 100
-128
Whole numbers in the range -128 to 127.
short 0
7822
Whole numbers in the range -32768 to 32767.
int 93563321
0x3C8A
Whole numbers in the range -2147483648 to 2147483647.
long 35423566443334L
-1L
Whole numbers in the range -9223372036854775808 to 9223372036854775807.
float -3.14159f
0.0f
IEEE 754 34-bit floating point values. This type has values between -340282346638528859811704183484516925440 and 340282346638528859811704183484516925440 (technically that's from 2104−2128 to 2128−2104), as well as the special values -Infinity, Infinity, and NaN. More than half of the representable values are between -1 and 1. The farther from zero you get, the more spread out the representable numbers become.
double 7.22e-37
0.0
-11.64533424e200
IEEE 754 64-bit floating point values. This has values between 2971−21024 to 21024−2971, which is approximately -1.797693134862315708×10308 to 1.797693134862315708×10308. Also includes the special values -Infinity, Infinity, and NaN. More than half of the representable values are between -1 and 1. The farther from zero you get, the more spread out the representable numbers become.
char 'W'
'%'
'\u265B'
'\xe9'
'\n'
'\t'
'\''
'\\'
Supposedly the type of characters, but actually the type of UTF-16 codepoints.

Any type that is not a primitive type is called a reference type. There are a potentially infinite number of these. These types are created in one of four ways:

In Java, there are thousands of classes predefined for you, and you can create an unlimited number of your own.

One of most useful classes is String. Here are some examples of string literals:

""
"$"
"Hello, World"
"DO NOT\nENTER"
"I\xf1es said, \"It's me.\""
"1.\tf3\te5\n2.\tg4\t\u265bh4++"

Here are some array literals

new String[] {"uno", "dos", "tres"}
new int[] {27, 36, 18, -2}
new double[] {1.5, -34.53423, -3.5E-33, 2.117e92}
new long[] {}

When you make a new type with an enum declaration, you specify all the literals:

enum Direction {NORTH, EAST, SOUTH, WEST};
// Now there are four literals:
Direction.NORTH;
Direction.EAST;
Direction.SOUTH;
Direction.WEST;

To summarize:

Every type in Java is either a primitive type or a reference type. There are only eight primitive types. All other types, including all types you create yourself, are reference types.

The difference between primitives and references may be one of the most fundamental and philosophically important concepts in programming. We are not quite ready to cover it. We have to wait until we get to classes and objects.

Java Expressions

An expression is a chunk of code which you evaluate. Evaluation means producing a value or throwing an exception. Examples:

5                          ==> 5
2 * 4                      ==> 8
3 + 10 * 2                 ==> 23
(3 + 10) * 2               ==> 26
9 / 4                      ==> 2
9.0 / 4                    ==> 2.25
9 / 4.0                    ==> 2.25
9.0 / 4.0                  ==> 2.25
5.0 / 0                    ==> Infinity
0.0 / 0.0                  ==> NaN
23 % 7                     ==> 2
15 - 2 - 7                 ==> 6
Math.cos(Math.PI)          ==> -1.0
Math.sqrt(400)             ==> 20
3 > 5                      ==> false
3 >= 3                     ==> true
100 == 100                 ==> true
7 != 7                     ==> false
100 < 30                   ==> false
25 <= 70                   ==> true
!false                     ==> true
!true                      ==> false
true && false              ==> false
7 > 2 || 1 == 2            ==> true
1 == 1 ? 8 : 100           ==> 8
3 > 5 ? 6 : 5              ==> 5
"abcdefg".length()         ==> 7
"abcdefg".charAt(0)        ==> 'a'
"abcdefg".charAt(1)        ==> 'b'
"abcdefg".indexOf('e')     ==> 4
"abcdefg".indexOf('p')     ==> -1
"abcdefg".toUpperCase()    ==> "ABCDEFG"
"  ab cdef  g   ".trim()   ==> "ab cdef  g"
"abcdefgh".substring(2,6)  ==> "cdef"
"ab".equals("aB")          ==> false
"ab".equalsIgnoreCase("aB")==> true
"dog".compareTo("dots")    ==> some number less than 0
"dog".compareTo("dog")     ==> 0
"dog".compareTo("abc")     ==> some number greater than 0
"dog" + "house"            ==> "doghouse"
"dog " + "house"           ==> "dog house"
"dog" + 200                ==> "dog200"
true + "dog"               ==> "truedog"
"mar" + 'k'                ==> "mark"
"catch" + 2 + 2            ==> "catch22"
"catch" + (2 + 2)          ==> "catch4"
"" + 89                    ==> 89
String.valueOf(89)         ==> "89"
Integer.parseInt("203")    ==> 203
Double.parseDouble("3.1")  ==> 3.1
Integer.parseInt("dog")    ==> throws a NumberFormatException

Variables

A variable is a named storage location for a value. In Java, you

int total;
double principal = 1322.50;
String message = "Try again later";
char separator = '/';
double rate = 0.04625;
double interest;

interest = principal * rate;
principal = principal + interest;
principal += interest;
total = 0;
total++;
++total;
total--;
--total;
principal *= 1.08;

int[] a = new int[]{4, 5, 6};
a[0] = 3;
a[2] = a[1] + 5;
int x = a[3];           // throws an ArrayIndexOutOfBoundsException

Final variables

If a variable is marked final, it can only be assigned a value once.

final int SECONDS_IN_MINUTE = 60;
final int NUMBER_OF_PLAYERS = 4;
final boolean ENCRYPTED = true;

Type conversion

If you try to use a value of one type where a value of a different type is expected, either your code will not compile, or Java will automatically find the closest value of the expected type to use. This kind of type conversion is called coercion:

int total = 4.66;            // WON'T COMPILE
double amount = 5;           // COERCED TO 5.0
short size = 3;
total = size;                // No problem, there's an int for every short

Sometimes Java is not willing to coerce automatically for you, but you can often force a type conversion by using a cast:

double x = 4.66;            // WON'T COMPILE
int y = (int)x;             // ASSIGNS 4
short size = (short)y;      // Must be explicit because might not fit
Exercise: Research the rules for when Java will do the automatic coercion, and when you must do the cast.