The basic building blocks of programming
By the end of this lesson you should:
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:
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.
public static void main(String[] args) {
// Your code here
}
The main method is made of a few key words:
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);
}
}
Java provides the fundamental types with which people can (and have) built everything
Among those are basic data types that we are concerned with:
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.
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.
Java lets you to choose between a number that:
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)
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"
A true/false value
These are used in all decision making, i.e.
public class UsingBooleans {
public static void main(String[] args) {
var enabled = true;
System.out.println(enabled);
}
}
In Greeting.java, define a Boolean variable isHungry with the value true or false depending on whether or not you are hungry.
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.
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
}
}
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 is only true if both the left and right value are true.
| true | false | |
|---|---|---|
| true | true | false |
| false | false | false |
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 reverses the boolean it is applied to.
| original | !original |
|---|---|
| true | false |
| false | true |
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");
}
}
}
Using isHungry in Greeting.java. Write an if statement to print "Food time!" if true and "No snacking!" if
false.
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):
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
To make reading other peoples' code easier, programming languages have agreed coding conventions.
Naming conventions differ for certain cases:
Some other essential rules for Java:
public class Calculator { ... } must exist in Calculator.java.