Skip to content

Java Basics

William Wood edited this page Dec 3, 2018 · 2 revisions

Java Basics

This page is intended to give an overview of the basics of programming in Java. This includes:

  • Varaibles
  • Methods
  • Classes and objects
  • Layout of a Java program

We will assume that you are familiar with at least one other programming language and do not need the fundamental concepts of programming explained to you.

Varaibles

In Java, variables are "strongly typed", meaning whenever you declare a variable you must also declare what type of variable it is. Java has 8 different types you can use in total, listed below:

int     integer              = 304;              // "Whole number"
short   shortInteger         = 3;                // A short "whole number"
long    longInteger          = 3000000000000000; // A long "whole number"
float   decimalNumber        = 3.45;             // A floating-point number (ie not an integer)
double  preciseDecimalNumber = 3.45867474637395; // A floating-point number with double the places
char    singleCharacter      = 'A';              // A single text character
boolean trueOrFalse          = true;             // Boolean, can be true or false
byte    oneByteOfData        = 100;              // A single byte (8 binary digits)

However, you are very unlikely to use anything outwise of int, double and boolean in the context of JISA.

Strings are technically not one of the basic variables, but are actually objects. However, since they are so important they get special treatment in Java, so they can sort of be thought of as being variables.

Methods

As well as defining what type a variable is, when defining a function/method you will also need to specify what type of variable it will return. For example, below is a method that takes two double arguments and returns their sum:

double addNumbers(double number1, double number2) {
    
    double number3 = number1 + number2;
    return number3

}

If your method is not to return any value then you should specify its return type as void:

void outputNumber(double number1) {

    // Prints the number to the terminal
    System.out.println(number1);

}

Classes and objects

Beyond simple variables we have "objects". These look just like variables in-code but can contain other variables/objects and methods "inside" them, accessed by use of a dot: ..

For example, let's suppose that myObject is an object and has two variables named var1 and var2 and a method called doTheThing(), we would access them like so

myObject.doTheThing();
myObject.var1;
myObject.var2;

The structure of an object is defined by its "class". Classes are written like so:

public class MyClass {

  public double var1;
  public double var2;

  public void doTheThing() {
    // The thing is done here
  }

}

Here we have defined the class MyClass as having two variables var1 and var2 along with the method doTheThing(). This is actually the class used to create our object myObject from before. Creating an object from a class is called "instantiation" (since we're basically creating an "instance" of the class) and is done like so:

MyClass myObject = new MyClass();

As we can see, much like with variables, we need to state what "type" of object we have. The type of the object is simple which class it has been created from, so in our case it's MyClass as we have written above. On the right-hand side of the = we have new MyClass(). By writing this we are telling Java that we want MyClass myObject to be a new instance of MyClass. This is called a "constructor". You can define constructors in the class that take arguments like so:

public class MyClass {

  public double var1;
  public double var2;

  public MyClass(double var1, double var2) {
    this.var1 = var1;
    this.var2 = var2;
  }

}

(we put this. before the var1 and var2 here to let Java know we're talking about the var1 and var2 defined in that object rather than the var1 and var2 that we defined as arguments in the constructor)

This means that when we create an object of MyClass now it will look like this:

MyClass myObject = new MyClass(5.4, 23.5);

which will create a MyClass object and assign the values 5.4 and 23.5 to its var1 and var2 class variables respectively.

The public keyword before each definition tells Java that we want things outside of this class to be able to access them. (The public in-front of the class defines that code written outside this program can also access this class). If, instead, you only want code written inside this class to be able to access them you would swap public for private like so:

public class MyClass {

  private double var1;
  private double var2;

  private void doTheThing() {
    // The thing is done here
  }

}

Further to public or private, you can also declare a method or variable as being static like so:

public class MyClass {

  public static double var1;
  public static double var2;

  public static void doTheThing() {
    // The thing is done here
  }

}

Variables and methods that are static no-longer belong to individual objects of the class but instead just belong to the class (ie there will only ever be one copy of them) and you access them like so:

MyClass.doThThing();
MyClass.var1 = 15;
MyClass.var2 = 30;

Loops

Loops are present in almost every programming language. Java is no different. Java loops are the same as they are in most other languages, particularly like C/C++.

For Loop

For loops are defined with three parts.

  1. Starting value of the variable
  2. Condition on the variable for the loop to continue
  3. What to do with the variable on each loop

For example, if I wanted to loop the integer i from 0 to 3 I would write:

for (int i = 0; i <= 3; i ++) {

}

Essentially this says "set i to 0, keep going so long as i is 3 or less and increment it by 1 each time we go round the loop".

While Loop

While loops keep going so long as a certain condition is met. You specify them like so:

int myInteger = 0;
while (myInteger != 3) {

}

This loop will keep going so long as the expression inside the (...) evaluates as true. In this case, so long as the integer myInteger does not equal 3. Alternatively you can use a do { ... } while (...) structure if you want to guarantee that the loop will run the first time:

int myInteger = 3;
do {

} while (myInteger != 3);

This loop will run at least once since the condition is checked at the end of each loop rather than at the beginning.

Arrays

You can have an array of any variable type or object class. If you don't know, an array is essentially list. To denote a variable as being an array of something instead of just a single instance you use square brackets [] like so:

int   singleInteger;
int[] arrayOfIntegers;

Arrays like this are of fixed length once they're created. To create a new array you use the following syntax:

int[] arrayOfIntegers = new int[15];

In this case I created a 15-element long array of integers.

To access a single element in an array, you specify the element index (number) in square brackets:

int element = arrayOfIntegers[5];

The above example will put the 6th element in arrayOfIntegers into element (it's 6th because array indices start at 0 in Java, like most languages except MATLAB).

It's likely that you won't have to do this but rather you will want to repeat an action on each element in an array (ie you'll want to loop over each element in the array).

If you don't know the length of an array, you can get it by using .length like so:

int length = arrayOfIntegers.length;

In our case the variable length will now equal 15.

To loop over each element in an array, the "traditional" way is to use a standard for loop:

for (int i = 0; i < arrayOfIntegers.length; i ++) {
    int element = arrayOfIntegers[i];
    // Do something with element
}

However, Java offers a much neater way of doing this using a for loop:

for (int element : arrayOfIntegers) {
    // Do something with element
}

This is essentially just short-hand for the previous, more traditional, for loop but reads much better. It's essentially saying "for every integer, which we shall call element, that is in arrayOfIntegers... do this".

Input/Output From/To Terminal

Programs running on a computer use what are called "streams" to deal with input and output. When writing a program to run in the terminal, there are three main streams: "in", "out" and "err". In sends what the user types into the terminal to the program, out sends what the program outputs to the terminal and err sends error messages from the program to the terminal (normally highlighted red when shown to the user).

In Java, these are represented as Stream objects that you can access as System.in, System.out, System.err. The out and err streams are easy to work with. Quite simply, to send a line of text use the println(...) method to write the text to the terminal then start a new line or just print(...) to send the text but not start a new line:

System.out.println("A line of text to send to the terminal!");
System.out.print("And another ");
System.out.println("line of text!");

System.err.println("An error or something!");
System.err.print("Very");
System.err.println(" scary :o");

this would result in the following being printed to the terminal:

  A line of text to send to the terminal!
  And another line of text!
- An error or something!
- Very scary :o

If you want to insert a variable into the text you're outputting, try printf(...) like so:

int    wholeNumber = 10;
double nonInteger  = 15.2;
String text        = "doggo";

System.out.printf(
  "The thing about the number %d is that it is not %f, as was first told by %s\n",
  wholeNumber, 
  nonInteger, 
  text
);

which will output

The thing about the number 10 is that it is not 15.2, as was first told by doggo

Each %... is a placeholder. The letter after the % represents what type of variable we will be inserting here:

  • %d means "decimal integer goes here"
  • %f means "floating-point number goes here"
  • %s means "string/text goes here"
  • \n means "new line"

You then specify which variables you want to replace those placeholders in-order as the rest of the arguments of printf(...).

You can do the same but have the text be returned as a String rather than be output by using String.format(...) like so:

String text = String.format("This is some %s!", "Text");

Input is slightly more tricky since you need to know what sort of input you're wanting from the user (ie a number or text?). However Java provides a class called Scanner that makes getting user input easy:

Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");
double number = input.nextDouble();   // Waits for the user to input a number

System.out.print("Now enter some text: ");
String text = input.nextLine();       // Waits for the user to input a line of text

If you plan on using the terminal for user interaction with your programme then you may find it useful to create the following static objects:

public class Main {

    static PrintStream out = System.out;
    static Scanner     in  = new Scanner(System.in);

    public static void main(String[] args) {

        out.println("Now you can just use 'out' and 'in'!");
        out.print("What's your name? ");

        String name = in.nextLine();

        out.printf("It's great, isn't it, %s?\n", name);

    }

}

Main Method

We now know enough to be able to see how we can begin writing a program in Java. In Java, everything must be within a class, you can't just have code floating about in some random file. This raises the issue of how does Java know where to start, which lines of code does it run first?

The answer is that Java looks for a static method called main() in your main class, normally called Main by default (although you can change this if you really want to). Therefore, you will have a file called Main.java which inside will look like so:

public class Main {

  public static void main() {

    System.out.println("Hello world!");

  }

}

Thus when this Java application is run it will output the line "Hello World!" to the terminal.

Example Program

This is an example program that has two files in total, shown below:

Main.java

public class Main {

  public static double  myNumber = 10;
  public static Scanner input    = new Scanner(System.in);

  public static void main() {

    System.out.println("Welcome to my program!");
    System.out.printf("My number for today is %d!\n", myNumber);
    System.out.print("Enter your name: ");

    String      name     = input.nextLine();
    NameHandler handler  = new NameHandler(name);

    System.out.println(handler.getGreeting());
    System.out.println(handler.getMessage());
    System.out.println(handler.getBye());

  }

}

NameHandler.java

public class NameHandler {

  private String name;

  public NameHandler(String name) {
    this.name = name;
  }

  public String getGreeting() {
    return String.format("Hello %s!", name);
  }

  public String getMessage() {
    return String.format("It is very nice to meet you indeed, %s.", name);
  }

  public String getBye() {
    return String.format("It's time to go now though, goodbye %s!", name);
  }

}

Running the program will look like this:

Welcome to my program!
My number for today is: 10!
Enter your name: xxKoolDood11xx
Hello xxKoolDood11xx!
It is very nice to meet you indeed, xxKoolDood11xx.
It's time to go now though, goodbye xxKoolDood11xx!

Comparisons

Just like with most other languages Java lets you perform comparisons between variables using the standard operators:

  • == - "is equal to"
  • != - "is not equal to"
  • > - "is greater than"
  • >= - "is greater than or equal to"
  • < - "is less than"
  • <= - "is less than or equal to"

However, these can only be used on the 8 basic types of variables. Since String objects are not actually variables but objects, to check whether two strings are equal you must use the .equals(...) method like so:

String myString = "Fun times!";
if (myString.equals("Fun times!")) {
  System.out.println("The string says fun times!");
} else {
  System.out.println("The string does not say fun times!");
}

Trying to use myString == "Fun times!" would not work.

Passing Code as an Argument

Particularly when working with a GUI, you will often need to define some code to run after something else has happened (for example, code to run when a button is clicked). In such cases you can do one of two things. The simplest is to define a method with the code in it and give a reference to that function.

For example, let's assume there's a function call to add a button to a toolbar and it needs the text for the button and what to do when it's clicked:

public class Main {

  public static void run() {
     // ... code here ...
     window.addToolbarButton("Do The Thing!", Main::doTheThing);
     // ... code here ...
  }

  public static void doTheThing() {
    // ... code to do the thing goes here ...
  }

}

Essentially we have told it that when the button is clicked, that it should run the method called doTheThing inside the class Main.

Alternatively you can write the code directly in the argument by use of a so-called "lambda expression":

window.addToolbarButton("Do The Thing!", () -> {
  // ... code to do the thing goes here ...
});
Clone this wiki locally