Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Conditional statements and truth values

So far, our programs have progressed from one command to another in a straightforward manner. In order for the program to branch to different execution paths based on e.g. user input, we need conditional statements.

int number = 11;

if (number > 10) {
    System.out.println("The number was greater than 10");
}

The condition (number > 10) evaluates into a truth value; either true or false. The if command only handles truth values. The conditional statement above is read as “if the number is greater than 10”.

Note that the if statement is not followed by semicolon as the condition path continues after the statement.

After the condition, the opening curly brace { starts a new block, which is executed if the condition is true. The block ends with a closing curly brace }. Blocks can be as long as desired.

The comparison operators are:

int number = 55;

if (number != 0) {
    System.out.println("The number was not equal to 0");
}

if (number >= 1000) {
    System.out.println("The number was greater than or equal to 1000");
}

A block can contain any code including other if statements.

int x = 45;
int number = 55;

if (number > 0) {
    System.out.println("The number is positive!");
    if (number > x) {
        System.out.println(" and greater than the value of variable x");
        System.out.println("after all, the value of variable x is " + x);
    }
}

The comparison operators can also be used outside the if statements. In such case the truth value will be stored in a truth value variable.

int first = 1;
int second = 3;

boolean isGreater = first > second;

In the example above the boolean (i.e. a truth value) variable isGreater now includes the truth value false.

A boolean variable can be used as a condition in a conditional sentence.

int first = 1;
int second = 3;

boolean isLesser = first < second;

if (isLesser) {
    System.out.println(first + " is less than " + second + "!");
}
1 is less than 3!

else if

If there are more than two conditions for the program to check, it is recommended to use the else if command. It works like the else command, but with an additional condition. else if comes after the if command. There can be multiple else if commands.

int number = 3;

if (number == 1) {
    System.out.println("The number is one.");
} else if (number == 2) {
    System.out.println("The number is two.");
} else if (number == 3) {
    System.out.println("The number is three!");
} else {
    System.out.println("Quite a lot!");
}

Let us read out loud the example above: If number is one, print out “The number is one.”. Otherwise if the number is two, print out “The number is two.”. Otherwise if the number is three, print out “The number is three!”. Otherwise print out “Quite a lot!”.

Comparing strings

Strings cannot be compared using the equality operator (==). For string comparison, we use the equals. command, which is always associated with the string to compare.

String text = "course";

if (text.equals("marzipan")) {
    System.out.println("The variable text contains the text marzipan");
} else {
    System.out.println("The variable text does not contain the text marzipan");
}

The equals command is always attached to the string variable with a dot in between. A string variable can also be compared to another string variable.

String text = "course";
String anotherText = "horse";

if (text.equals(anotherText)) {
    System.out.println("The texts are the same!");
} else {
    System.out.println("The texts are not the same!");
}

When comparing strings, it is crucial to make sure that both string variables have been assigned some value. If a value has not been assigned, the program execution terminates with a NullPointerException error, which means that variable has no value assigned to it (null).

Exercise if-1 : Greater number

Create a program that asks the user for two numbers and prints the greater of those two. The program should also handle the case in which the two numbers are equal.

Example outputs:

Type the first number: ~~5~~
Type the second number: ~~3~~

Greater number: 5
Type the first number: ~~5~~
Type the second number: ~~8~~

Greater number: 8
Type the first number: ~~5~~
Type the second number: ~~5~~

The numbers are equal!

Exercise if-2 : Grades and points

Create a program that gives the course grade based on the following table.

Points Grade
0-29 failed
30-34 1
35-39 2
40-44 3
45-49 4
50-60 5

Example outputs

Type the points [0-60]: ~~37~~

Grade: 2
Type the points [0-60]: ~~51~~

Grade: 5

Logical operations

The condition statements can be made more complicated using logical operations. The logical operations are:

Below we will use the AND operation && to combine two individual conditions in order to check if the value of the variable is greater than 4 and less than 11 (i.e. in the range 5 - 10).

System.out.println("Is the number between 5-10?");
int number = 7;

if (number > 4 && number < 11) {
    System.out.println("Yes! :)");
} else {
    System.out.println("Nope :(")
}
Is the number between 5-10?
Yes! :)
Next up is the OR operation   , which will be used to check if the value is less than 0 or greater than 100. The condition evaluates to true if the value fulfills either condition.
System.out.println("Is the number less than 0 or greater than 100?");
int number = 145;

if (number < 0 || number > 100) {
    System.out.println("Yes! :)");
} else {
    System.out.println("Nope :(")
}
Is the number less than 0 or greater than 100?
Yes! :)

Now we will use the negation operation ! to negate the condition:

System.out.println("Is the string equal to 'milk'?");
String text = "water";

if (!(text.equals("milk"))) {  // true if the condition text.equals("milk") is false
    System.out.println("No!");
} else {
    System.out.println("Yes")
}
Is the text equal to 'milk'?
No!

For complicated conditions, we often need parentheses:

int number = 99;

if ((number > 0 && number < 10) || number > 100 ) {
    System.out.println("The number was in the range 1-9 or it was over 100");
} else {
    System.out.println("The number was equal to or less than 0 or it was in the range 10-99");
}
The number was equal to or less than 0 or it was in the range 10-99

Exercise if-3 : Age check

Create a program that asks for the user’s age and checks that it is reasonable (at least 0 and at most 120).

How old are you? ~~10~~
OK
How old are you? ~~55~~
OK
How old are you? ~~-3~~
Impossible!
How old are you? ~~150~~
Impossible!

Exercise if-4 : Usernames

Create a program that recognizes the following users:

Username Password
alex mightyducks
emily cat

The program should check for the username and password as follows:

Type your username: ~~alex~~
Type your password: ~~mightyducks~~
You are now logged into the system!
Type your username: ~~emily~~
Type your password: ~~cat~~
You are now logged into the system!
Type your username: ~~emily~~
Type your password: ~~dog~~
Your username or password was invalid!

Exercise if-5 : Leap year

A year is a leap year if it is divisible by 4. But if the year is divisible by 100, it is a leap year only when it is also divisible by 400.

Create a program that checks whether the given year is a leap year. Make sure you only have one if-else statement, no else-if is needed

Type a year: ~~2011~~
The year is not a leap year.
Type a year: ~~2012~~
The year is a leap year.
Type a year: ~~1800~~
The year is not a leap year.
Type a year: ~~2000~~
The year is a leap year.

Changing variables

We usually want to change the value of an existing variable. This can be done using the normal assignment statement. In the next example, we increase the value of the variable age by one:

int age = 1;

System.out.println(age);  // prints 1
age = age + 1;            // the new value of age is the old value of age + 1
System.out.println(age);  // prints 2

The age = age + 1 statement increments the value of the variable age by one. It is also possible to increment a variable by one as below:

int age = 1;

System.out.println(age);  // prints 1
age++;                    // means the same as age = age + 1
System.out.println(age);  // prints 2

Another example:

int length = 100;

System.out.println(length);  // prints 100
length = length - 50;
System.out.println(length);  // prints 50
length = length * 2;
System.out.println(length);  // prints 100
length = length / 4;
System.out.println(length);  // prints 25
length--;                    // means the same as length = length - 1;
System.out.println(length);  // prints 24

else

If the truth value of the comparison is false, another optional block can be executed using the else command.

int number = 4;

if (number > 5) {
    System.out.println("Your number is greater than five!");
} else {
    System.out.println("Your number is equal to or less than five!");
}

Exercise if-6 : Sum of three numbers

Create a program that asks the user for three numbers and then prints their sum. Use the following structure in your program:

Scanner reader = new Scanner(System.in);
int sum = 0;
int read;

// WRITE YOUR PROGRAM HERE
// USE ONLY THE VARIABLES sum, reader AND read!

System.out.println("Sum: " + sum);
Type the first number: ~~3~~
Type the second number: ~~6~~
Type the third number: ~~12~~

Sum: 21