Home CPSC 220

Java Basics

Structure of a Java Program

Below is the hello world program:

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

Every Java program consists of a class. The name of the class must be the same as the name of the file it resides in. So the program above must be in a file called "Hello.java"

Every Java program also must have a function called "main" which is declared as "public static void". We'll see what each of these means as we go along.

This function takes an array of Strings as its arguments. We'll see how we can use these later.

Curly braces in Java mark blocks of code. So the class Hello contains the main function, and the main function contains the output statement.

The line System.out.println("Hello World!"); is a call to a function called println which is inside a library called System.out. I Java the "." means that something is a part of something else.


Variables

Variables are an important part of programming. They store the data that our programs work on as they run.

Each variable has a name that you use to refer to it. Names start with either a letter or underscore. After that, they contain any number of letters, underscores, and numbers. Variable names are technically allowed to contain dollar signs, but this is rarely used.

Which of the following are legal names:


price
length&width
Distance_In_Feet
name7
amount-paid
3d_distance
____

Variable names can be any length are case-sensitive.

Variable names should be descriptive. By convention, we will use camel-case to separate multiple words in variables:


amountPaid
distanceInFeet
firstName

You also cannot name your variable the same as a Java reserved word. These are the built-in building blocks of the language such as "class, public, void" and so on.


Number Types

Along with a name, each variable must have a type. The type indicates what kind of data can be stored in the variable.

The following types are for storing numbers in Java:

TypeDescriptionTypical Size
byteA single byte1 bytes
shortA small integer2 bytes
intA regular integer4 bytes
longA large integer8 bytes
floatA small number with a decimal point4 bytes
doubleA regular number with a decimal point8 bytes

Typically "int" is used for most integers. For numbers with decimal points, double is the most common. You rarely need to worry about which one you choose.

In Java all of our variables need to be declared before we can use them. This is done in the following examples:


int count;
double distance;
short year;

Assignments

To actually use our variables, we need to assign something to them. This can be done at the time when they are first created:


int count = 5;
double distance = 18.234;
short year = 2014;

It can also be done after they are declared:


count = 4;
distance = 13.23;
year = 2015;

It is good practice to always assign a variable when it is declared!


Strings

We can also create String variables for storing text:


String name = "Ian Finlayson";

String variables can be assigned any text withing double-quote characters, called string literals. A string literal must be on only one line, however.


Output

As we have seen, the "System.out.println" function allows us to output text to the screen in Java. This function takes one parameter and prints it to the screen. The argument can be a String, as in Hello World, or a numeric value.

There is also the "System.out.print" function. The only difference between them is that the "println" prints a line break, while the "print" does not.

In Java, a string can be concatenated with a numeric value with the "+" operator:


int number = 42;
System.out.println("The answer is " + number);

Input

Input is slightly more complicated in Java. In order to perform input, we must create a "Scanner" object. To do this, we first have to import the Scanner library:


import java.util.Scanner;

Then, we can create a Scanner object in the main function with this line of code:


Scanner in = new Scanner(System.in);

This creates an object called "in". Like regular variables, we can call it whatever we want, but I always use the name "in" for this.

We can then use this object to read different types of data:

CallValue Returned
in.next()One word as a String, containing no spaces.
in.nextLine()One line as a String, possibly containing spaces.
in.nextByte()One byte.
in.nextShort()One short.
in.nextInt()One int.
in.nextLong()One long.
in.nextFloat()One float.
in.nextDouble()One double.

The following program demonstrates these functions:


import java.util.Scanner;

public class Input {

    public static void main(String args[]) {
        // create the scanner object
        Scanner in = new Scanner(System.in);
        
        // a single word
        System.out.print("Enter a single word: ");
        String word = in.next();
        System.out.println("You entered: " + word);
        
        // a whole line
        System.out.print("Enter a line: ");
        String line = in.nextLine();
        System.out.println("You entered: " + line);
        
        // an integer
        System.out.print("Enter an integer: ");
        int integer = in.nextInt();
        System.out.println("You entered: " + integer);
        
        // a double
        System.out.print("Enter a double: ");
        double value = in.nextDouble();
        System.out.println("You entered: " + value);
    }
}

Note that the "nextLine" function does not really work as written above. The issue is that when we call "next", it leaves the enter key in the input, and "nextLine" sees it, returning right away.

To fix this, we can insert a "dummy" call to "nextLine" to read the extra new line, before reading the line we actually want. The program below does this:


mport java.util.Scanner;

public class Input {

    public static void main(String args[]) {
        // create the scanner object
        Scanner in = new Scanner(System.in);
        
        // a single word
        System.out.print("Enter a single word: ");
        String word = in.next();
        System.out.println("You entered: " + word);
        
        // read the left-over newline!
        in.nextLine();
        
        // a whole line
        System.out.print("Enter a line: ");
        String line = in.nextLine();
        System.out.println("You entered: " + line);
        
        // an integer
        System.out.print("Enter an integer: ");
        int integer = in.nextInt();
        System.out.println("You entered: " + integer);
        
        // a double
        System.out.print("Enter a double: ");
        double value = in.nextDouble();
        System.out.println("You entered: " + value);
    }
}

Doing Math in Java

The left-hand side of an assignment statement is a variable. The right-hand side can be not only just a number value, but a mathematical expression.

For example, the following program reads in a distance travelled, and time elapsed, and computes the speed:


import java.util.Scanner;

public class Speed {

    public static void main(String args[]) {
        // declare the variables
        double distance, time, speed;
        
        // create the scanner
        Scanner in = new Scanner(System.in);

        // get input from user
        System.out.print("Enter distance travelled: ");
        distance = in.nextDouble();
        System.out.print("Enter time taken: ");
        time = in.nextDouble();

        // average speed is distance divided by time
        speed = distance / time;

        // print output
        System.out.println("Speed is " + speed);
    }
}
Java also provides the following mathematical operators (in order of precedence)
OperatorMeaning
*Multiplication
/Division
%Remainder Division
+Addition
-Subtraction

Parenthesis can be used to override precedence.

When dividing integers, Java behaves differently than you may expect. Java always rounds down.

The % operator (also called modulus) gives the remainder when dividing. The following program illustrates this:


import java.util.Scanner;

public class Division {

    public static void main(String args[]) {
        int a, b;
        Scanner in = new Scanner(System.in);
        
        System.out.println("Enter two numbers:");
        a = in.nextInt();
        b = in.nextInt();
        
        System.out.println(a + "/" + b + " = " + (a / b));
        System.out.println(a + "%" + b + " = " + (a % b));
    }
}

Modulus is useful in certain instances, such as finding out if numbers are even or odd.

How could we write a program to input a monetary amount, and output that amount with a 15% tip added in?






Java also offers a number of shortcut operators:

OperatorMeaning
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x++x = x + 1
x--x = x - 1

These can save a little bit of typing. The last two are most commonly used.

Because numbers in Java are of a limited size, we can actually run into problems. The following program demonstrates this by adding one to the largest positive number that fits in a 32-bit integer:


public class Overflow {

    public static void main(String args[]) {
        int number = 2147483647;
        System.out.println(number);
        number++;
        System.out.println(number);
    }
}

What does this program output?


Characters

In addition to numerical data, Java can also deal with textual data. The "char" type facilitates this.

The char type is actually just an integer one byte large indicating which character is represented. The mapping of numbers to characters is given by the ASCII code. Character values can be given in single quotes.

The following program illustrates chars.


public class Chars {

    public static void main(String args[]) {
        // set the character to a constant
        char a = 'A';
        System.out.println(a);

        // set the character to an ASCII value
        char b = 66;
        System.out.println(b);
    }
}

What if we want to put the quote character itself in a character? The following won't work:


    char a = ''';
Java gets confused because the second single-quote ends the character and the third one is unmatched. To do this, we need an escape sequence:

    char a = '\''
The backslash indicates that the two characters together form one character. The following table gives some common escape sequences:
SequenceMeaning
\'The single-quote character.
\"The double-quote character.
\nA new line (similar to endl).
\tA tab character.
\\An actual backslash character.

Note that characters are simply numbers, we can even do math on them!

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.