Lesson 2

The basic building blocks of programming

Lesson Outcomes

By the end of this lesson you should:

  • Have run your first program in Java
  • "Translated" some of your pseudocode into a runnable program
  • Have used some of Java's provided functionality
  • Be able to read and understand a Java program

In this lesson we'll be meeting Java, and its syntax that corresponds to our pseudocode

We'll be meeting a few more aspects of programming, alongside some old ones:

  • Variables and Types
  • Operators on these types
  • if-statements (aka Conditional Execution)
  • Collections and Loops
  • Rules and Conventions of Java
Hello, world!

The first program everyone writes:


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

There are a few new things here that we'll explain


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

Lines 1 and 5 define a class

A class lets you bundle related functionality into one file, and can then be used in another class.

All code must be defined inside a class!


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

Lines 2 and 4 define the main method

The main method is the starting point of every Java program, and must be written in this way.

When the program is run, whatever is inside the main runs.


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

Line 3 is a method call which prints (outputs) a piece of text (a String) to the terminal/console.

Bonus slide, the main method

public static void main(String[] args) {
  // Your code here
}
          

The main method is made of a few key words:

  • public is an access modifier - it says who can see and use this. Everyone can see public definitions.
  • static means only one of the defined things will ever exist, and would be shared between whoever called it.
    This means it exists and is usable immediately (very handy for Java).
  • void is the return type - it defines what sort of thing you get back if you use this method in your program. Void however means that nothing is returned.
Variables

As we've seen before, variables are for storing values we can refer to and update later in our program.

Java is strictly typed - meaning the type of value stored cannot change.

We can either define our variable by first declaring the type, or with var, we will prefer var for the course.

This is the general pattern:


ObjectType myVariable = value;
          

or


var myVariable = value;
          

Here are some concrete examples:


public class VariablesAndTypes {
  public static void main(String[] args) {
    var greeting = "Hello";
    System.out.println(greeting);

    var myFavouriteNumber = 17;
    System.out.println(myFavouriteNumber);

    var isThisJava = true;
    System.out.println(isThisJava);
  }
}
          
Types

Java provides the fundamental types with which people can (and have) built everything

Among those are basic data types that we are concerned with:

  • Strings (type String)
  • Numbers (types Integer and Double)
  • Booleans or true/false values (type Boolean)
String

Represents text in your program, they must be enclosed in quote marks ("")


public class UsingStrings {
  public static void main(String[] args) {
    var teacherName = "Ben";
    var courseName = "Java for beginners";
    var statement = teacherName + " teaches " + courseName;

    System.out.println(statement);
  }
}
          

Notice that we can use + to append/glue Strings to each other.

Whiteboard Exercise

Create a new file Greeting.java, write a class and a main method in it.

In the main method, define a String variable myName that has your own name as a value.

Numbers

Java lets you to choose between a number that:

  • Only does whole numbers (type Integer or Long)
  • Has a decimal place (type Float or Double)
  • Handles even larger numbers (at the cost of memory)

By default Java uses Integer and Double, which will happen when you use var to define variables.


public class UsingNumbers {
  public static void main(String[] args) {
    // These can all be defined using var too

    Integer i1 = 123;
    System.out.println(i1);

    Long l1 = 123l; // Notice the "l" after the Long
    System.out.println(l1);

    Float f1 = 123.45f; // Notice the "f" after the Float
    System.out.println(f1);

    Double d1 = 123.45;
    System.out.println(d1);
  }
}
          
(Variable types declared for emphasis only, var also works)

Whiteboard Exercise

In Greeting.java, define an Integer variable myAge that has your own age as a value.

Print a message using your name and age variables, e.g. "I'm Ben and I'm definitely 24"

Boolean

A true/false value

These are used in all decision making, i.e.

  • if-statements
  • the counter on for loops
  • the check on while loops to continue

public class UsingBooleans {
  public static void main(String[] args) {
    var enabled = true;
    System.out.println(enabled);
  }
}
          

Whiteboard Exercise

In Greeting.java, define a Boolean variable isHungry with the value true or false depending on whether or not you are hungry.

Operators

Mathematical Operators

Along with the fundamental number types, Java gives us convenient operators to do math:


public class MathOperators {
  public static void main(String[] args) {
    var plus = 1 + 2;
    var minus = 1 - 2;
    var divide = 1 / 2;
    var multiply = 1 * 2;
    var power = Math.pow(1, 2); // 1 to the power of 2
    // Modulus % gives you the remainder of division
    var modulus = 1 % 2; // remainder of 1 divided by 2
  }
}
          

These operators follow BODMAS, you can use brackets as normal to control the order.

Comparison Operators

In addition to mathematical calculators, Java also provides handy number comparison:


public class MathComparisons {
  public static void main(String[] args) {
    var lessThan = 1 < 2;
    var greaterThan = 1 > 2;
    var lessThanOrEqual = 1 <= 2;
    var greaterThanOrEqual = 1 >= 2;
    var equal = 1 == 2; // note it is double equals signs
  }
}
          
Boolean Operators

Boolean Operators

Java also provides operators for booleans:


public class BooleanOperators {
  public static void main(String[] args) {
    var inclusiveOr = true || false;
    var and = true && false;
    var not = !true;
  }
}
          

AND &&

AND is only true if both the left and right value are true.

true false
true true false
false false false

OR ||

OR is true if either the left or right value are true.

It is only false when both values are false.

This is also known as inclusive OR

true false
true true true
false true false

NOT !

NOT reverses the boolean it is applied to.

original !original
true false
false true
if-statements

Another familiar tool, if gives us conditional execution in our code.


public class IfStatements {
  public static void main(String[] args) {
    var condition = true;

    if (condition) {
      System.out.println("The condition is true");
    }

    if (condition) {
      System.out.println("The condition is still true");
    } else {
      System.out.println("The condition is false");
    }
  }
}
          

In these examples we're using a Boolean variable, but you can use any expression that returns a Boolean.

This example compares numbers


public class IfStatementsContinued {
  public static void main(String[] args) {
    var numberToCheck = 5;

    if (numberToCheck < 0) {
      System.out.println("The number is too small");
    } else if (numberToCheck > 100){
      System.out.println("The number is too large");
    } else {
       System.out.println("The number is between 0 and 100");
    }
  }
}
          

Whiteboard Exercise

Using isHungry in Greeting.java. Write an if statement to print "Food time!" if true and "No snacking!" if false.

Code Structure

Code Structure

The lines of code you write need to know what context they are being run in.

{Braces} group statements in a dedicated block with its own context.

Variables declared inside a set of braces cannot be used after that set has ended, e.g.


public class Braces {
  public static void main(String[] args) {
    var sayHello = true;

    if (sayHello) { 
      // sayHello is accessible here, because this block is inside main

      var helloMessage = "Hello there!";
      System.out.println(helloMessage);

    } 
    // helloMessage is inaccessible here, we're not in the if statement's context
  }
}
          

[Brackets] let you define and access arrays - fixed-size lists that are very efficient.


public class Brackets {
  public static void main(String[] args) {

    // Create an array containing 1, 2, and 3
    var numbers = new Integer[] { 1, 2, 3 };

    var firstNumber = numbers[0];
    System.out.println(firstNumber);

    var secondNumber = numbers[1];
    System.out.println(secondNumber);

    var thirdNumber = numbers[2];
    System.out.println(thirdNumber);
  }
}
            

(Parentheses):

  • Override BODMAS in mathmatical calculations.
  • Define and provide required arguments for functions - code written elsewhere which you can call to get a value.

public class Parentheses {
  public static void main(String[] args) {
    var day = "Wednesday";
    if (day.toLowerCase().equals("wednesday")) {
      System.out.println("It is Wednesday my dudes");
    }
  }
}
          

In this example, toLowerCase takes no arguments.

equals takes one, a string to compare the day.

System.out.println takes one, a string to print to the console

Coding Conventions

To make reading other peoples' code easier, programming languages have agreed coding conventions.

Naming conventions differ for certain cases:

  • Variables, function names, and function arguments, are written in lowerCamelCase.
  • Classes are UpperCamelCase
  • Constant values are UPPER_SNAKE_CASE

Some other essential rules for Java:

  • The name of a class must match the name of the file it's in. i.e. public class Calculator { ... } must exist in Calculator.java.
  • You cannot name variables after reserved words i.e. words used in the core Java language features.

Exercises

Variables and Basic Operators

click here for the exercise sheet