You are on page 1of 42

Oop final lab topics

A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example
Create a method inside Main:

public class Main {

static void myMethod() {

// code to be executed

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the Main class and not an object
of the Main class. You will learn more about objects and how to access
methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn
more about return values later in this chapter

Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when


it is called:

Example
Inside main, call the myMethod() method:
public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

Try it Yourself »

A method can also be called multiple times:

Java Method Parameters
❮ PreviousNext ❯

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

Example
public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Multiple Parameters
You can have as many parameters as you like:

Example
public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:

This example returns the sum of a method's two parameters:

Example
public class Main {

static int myMethod(int x, int y) {

return x + y;
}

public static void main(String[] args) {

System.out.println(myMethod(5, 3));

// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read
and maintain):

Example
public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);

System.out.println(z);

// Outputs 8 (5 + 3)

Try it Yourself »
A Method with If...Else
It is common to use if...else statements inside methods:

Example
public class Main {

// Create a checkAge() method with an integer variable called age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old enough!");

// If age is greater than, or equal to, 18, print "access granted"

} else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an age of 20

}
}

// Outputs "Access granted - You are old enough!"

Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:

Example
int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

nstead of defining two methods that should do the same thing, it is better to
overload one.

In the example below, we overload the plusMethod method to work for


both int and double:

Example
static int plusMethod(int x, int y) {

return x + y;

static double plusMethod(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);


double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

Output:
int: 13
double: 10.559999999999999

Static vs. Non-Static


You will often see Java programs that have either static or public attributes and
methods.

In the example above, we created a static method, which means that it can be


accessed without creating an object of the class, unlike public, which can only
be accessed by objects:

Example
An example to demonstrate the differences
between static and public methods:

public class Main {

// Static method

static void myStaticMethod() {

System.out.println("Static methods can be called without creating


objects");

// Public method

public void myPublicMethod() {

System.out.println("Public methods must be called by creating


objects");

}
// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method on the object

Try it Yourself »

Output

Static methods can be called without creating objects


Public methods must be called by creating objects

Access Methods With an Object


Example
Create a Car object named myCar. Call
the fullThrottle() and speed() methods on the myCar object, and run the
program:

// Create a Main class

public class Main {

// Create a fullThrottle() method


public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

// Create a speed() method and add a parameter

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

// Inside main, call the methods on the myCar object

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

// The car is going as fast as it can!

// Max speed is: 200

Using Multiple Classes


Like we specified in the Classes chapter, it is a good practice to create an object
of a class and access it in another class.

Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:

 Main.java
 Second.java
Main.java
public class Main {

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

Second.java
class Second {

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

22

Java Class Attributes


In the previous chapter, we used the term "variable" for x in the example (as
shown below). It is actually an attribute of the class. Or you could say that
class attributes are variables within a class:

Example
Create a class called "Main" with two attributes: x and y:

public class Main {

int x = 5;

int y = 3;

Another term for class attributes is fields.

Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):

The following example will create an object of the Main class, with the


name myObj. We use the x attribute on the object to print its value:

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

5
Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class Main {

int x;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

40

Or override existing values:

Example
Change the value of x to 25:

public class Main {

int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // x is now 25


System.out.println(myObj.x);

25

If you don't want the ability to override existing values, declare the attribute
as final:

Example
public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error: cannot assign a value to a


final variable

System.out.println(myObj.x);

The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).

The final keyword is called a "modifier". 

Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:

Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

myObj2.x = 25;

System.out.println(myObj1.x); // Outputs 5

System.out.println(myObj2.x); // Outputs 25

5
25

Multiple Attributes
You can specify as many attributes as you want:

Example
public class Main {

String fname = "John";

String lname = "Doe";

int age = 24;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Age: " + myObj.age);


}

Name: John Doe


Age: 24

Java Conditions and If Statements


Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition
is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax
if (condition) {

// block of code to be executed if the condition is true


}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

Example
int x = 20;

int y = 18;

if (x > y) {

System.out.println("x is greater than y");

x is greater than y

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.

Syntax
if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {
System.out.println("Good evening.");

// Outputs "Good evening."

Try it Yourself »

Good evening.

The else if Statement


Use the else if statement to specify a new condition if the first condition
is false.

Syntax
if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

Example
int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 20) {

System.out.println("Good day.");
} else {

System.out.println("Good evening.");

// Outputs "Good evening."

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later
in this chapter

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

// Outputs "Thursday" (day 4)


The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;

case 7:

System.out.println("Today is Sunday");

break;

default:

System.out.println("Looking forward to the Weekend");

// Outputs "Looking forward to the Weekend"


Try it Yourself »

Note that if the default statement is used as the last statement in a switch


block, it does not need a break.

Looking forward to the Weekend

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:

Example
int i = 0;

while (i < 5) {
System.out.println(i);

i++;

0
1
2
3
4

Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {

System.out.println(i);

i++;
}

while (i < 5);

Try it Yourself »

0
1
2
3
4

Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

ava For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

System.out.println(i);

}
0
1
2
3
4

Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {

System.out.println(i);

Try it Yourself »

0
2
4
6
8
10

For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:

Syntax
for (type variableName : arrayName) {

// code block to be executed

The following example outputs all elements in the cars array, using a "for-


each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

System.out.println(i);

Volvo
BMW
Ford
Mazda

Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

public class Main {

public static void main(String[] args) {

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

if (i == 4) {

break;

System.out.println(i);

0
1
2
3
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

public class Main {

public static void main(String[] args) {

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

if (i == 4) {

continue;

System.out.println(i);

0
1
2
3
5
6
7
8
9

Break and Continue in While Loop


You can also use break and continue in while loops:

public class Main {

public static void main(String[] args) {

int i = 0;

while (i < 10) {


System.out.println(i);

i++;

if (i == 4) {

break;

}0
1
2
3

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values
to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

public class Main {


public static void main(String[] args) {

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

}
Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Loop Through an Array


You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.

public class Main {

public static void main(String[] args) {

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

System.out.println(cars[i]);

}Volvo
BMW
Ford
Mazda

Array Length
To find out how many elements an array has, use the length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

// Outputs 4

Java Inheritance (Subclass and


Superclass)
In Java, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

class Vehicle {

protected String brand = "Ford"; // Vehicle attribute

public void honk() { // Vehicle method

System.out.println("Tuut, tuut!");

class Car extends Vehicle {

private String modelName = "Mustang"; // Car attribute

public static void main(String[] args) {

// Create a myCar object

Car myCar = new Car();


// Call the honk() method (from the Vehicle class) on the myCar
object

myCar.honk();

// Display the value of the brand attribute (from the Vehicle class)
and the value of the modelName from the Car class

System.out.println(myCar.brand + " " + myCar.modelName);

Tuut, tuut!
Ford Mustang

Did you notice the protected modifier in Vehicle?

We set the brand attribute in Vehicle to a protected access modifier. If it was


set to private, the Car class would not be able to access it.

Why And When To Use "Inheritance"?


- It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.

Tip: Also take a look at the next chapter, Polymorphism, which uses inherited


methods to perform different tasks.

Java ArrayList
The ArrayList class is a resizable array, which can be found in
the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size
of an array cannot be modified (if you want to add or remove elements to/from
an array, you have to create a new one). While elements can be added and
removed from an ArrayList whenever you want. The syntax is also slightly
different:

Example
Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList


object

Add Items
The ArrayList class has many useful methods. For example, to add elements to
the ArrayList, use the add() method:

Example
import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

System.out.println(cars);

[Volvo, BMW, Ford, Mazda]


Access an Item
To access an element in the ArrayList, use the get() method and refer to the
index number:

cars.get(0);

,,,,,,,,,,,,,,,,,example,,,,,,,,,,,,

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

System.out.println(cars.get(0));

}Volvo

Remember: Array indexes start with 0: [0] is the first element. [1] is the
second element

Change an Item
To modify an element, use the set() method and refer to the index number:

cars.set(0, "honda");

import java.util.ArrayList;
public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

cars.set(0, "honda");

System.out.println(cars);

[honda, BMW, Ford, Mazda]

Remove an Item
To remove an element, use the remove() method and refer to the index number:

cars.remove(0);

Example

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");
cars.add("Ford");

cars.add("Mazda");

cars.remove(0);

System.out.println(cars);

} [BMW, Ford, Mazda]

To remove all the elements in the ArrayList, use the clear() method:

cars.clear();

[]

ArrayList Size
To find out how many elements an ArrayList have, use the size method:

cars.size();

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

System.out.println(cars.size());

} 4
Java Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).

Java try and catch


The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if an


error occurs in the try block.

The try and catch keywords come in pairs:

Syntax
try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

Example

public class Main {

public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!
}

} This will generate an error, because myNumbers[10] does not exist.

The output will be something like this:

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 10
        at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some
code to handle it:

Example
public class Main {

public static void main(String[ ] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

The output will be:

Something went wrong.


Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:

Example
public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword


The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many


exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, Secu
rityException, etc:

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or
older, print "Access granted":

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least


18 years old.");

else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

} The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access


denied - You must be at least 18 years old.
        at Main.checkAge(Main.java:4)
        at Main.main(Main.java:12)

Example
checkAge(20);
The output will be:

Access granted - You are old enough!


Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set
initial values for object attributes:

Example
Create a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This will
call the constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5

Note that the constructor name must match the class name, and it cannot
have a return type (like void).

Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a
parameter to the constructor (5), which will set the value of x to 5:

Example
public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

// Outputs 5

You can have as many parameters as you want:

Example
public class Main {

int modelYear;

String modelName;

public Main(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Main myCar = new Main(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

// Outputs 1969 Mustang

You might also like