A Lecture Number 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

OOP (java)

MSc. Mohammed AL-Sayani


Java Break and Continue

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.

This example stops the loop when i is equal to 4:

Example

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


if (i == 4) {
break;
}
System.out.println(i);
}

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.

This example skips the value of 4:

Example

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


if (i == 4) {
continue;
}
System.out.println(i);
}

Break and Continue in While Loop


You can also use break and continue in while loops:

Break Example

int i = 0;
while (i < 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}

Continue Example

int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}

Test Yourself With Exercises


Exercise:
Stop the loop if i is 5.

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


if (i == 5) {

;
}
System.out.println(i);
}

Java Arrays

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,
you can 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 can access an array element by referring to the index number.

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

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

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

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
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

Test Yourself With Exercises


Exercise:
Create an array of type String called cars.

= {"Volvo", "BMW", "Ford"};

ays Loop

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.

The following example outputs all elements in the cars array:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Loop Through an Array with For-Each


There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:

Syntax
for (type variable : arrayname) {
...
}

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);
}

The example above can be read like this: for each String element (called i - as in
index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method
is easier to write, it does not require a counter (using the length property), and it is
more readable.

Test Yourself With Exercises


Exercise:
Loop through the items in the cars array.

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

(String i : ) {
System.out.println(i);
}

Java Multi-Dimensional Arrays

Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular form, like
a table with rows and columns.

To create a two-dimensional array, add each array within its own set of curly braces:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

Access Elements
To access the elements of the myNumbers array, specify two indexes: one for the
array, and one for the element inside that array. This example accesses the third
element (2) in the second array (1) of myNumbers:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7

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

Change Element Values


You can also change the value of an element:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7

Loop Through a Multi-Dimensional Array


We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):

Example
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}

Test Yourself With Exercises


Exercise:
Insert the missing part to create a two-dimensional array.

myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

Java Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
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
}
}

1. 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!"

A method can also be called multiple times:

Example
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!

In the next chapter, Method Parameters, you will learn how to pass data (parameters)
into a method.

Test Yourself With Exercises


Exercise:
Insert the missing part to call myMethod from main.

static void myMethod() {


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

public static void main(String[] args) {

;
}

Java Method Parameters

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

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

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
Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.

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:

Example
public class Main {
static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

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)

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!"

Test Yourself With Exercises


Exercise:
Add a fname parameter of type String to myMethod, and output "John Doe":

static void myMethod( ) {

System.out.println( + " Doe");


}

public static void main(String[] args) {


myMethod("John");
}
Java Method Overloading

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)

Consider the following example, which has two methods that add numbers of
different type:

Example
static int plusMethodInt(int x, int y) {
return x + y;
}

static double plusMethodDouble(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}

Instead 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);
}

Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.

Java Scope

Java Scope
In Java, variables are only accessible inside the region they are created. This is called
scope.

Method Scope
Variables declared directly inside a method are available anywhere in the method
following the line of code in which they were declared:

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

// Code here CANNOT use x

int x = 100;

// Code here can use x


System.out.println(x);
}
}

Block Scope
A block of code refers to all of the code between curly braces {}.

Variables declared inside blocks of code are only accessible by the code between the
curly braces, which follows the line in which the variable was declared:

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

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x


System.out.println(x);

} // The block ends here

// Code here CANNOT use x

}
}

A block of code may exist on its own or it can belong to an if, while or for
statement. In the case of for statements, variables declared in the statement itself are
also available inside the block's scope.

Java Recursion

Java Recursion
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to
solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:

Example

Use recursion to add all of the numbers up to 10.

public class Main {


public static void main(String[] args) {
int result = sum(10);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just returns 0.
When running, the program follows these steps:

(8) )10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns
the result.

You might also like