Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Java Programming Basics

This document provides an introduction to Java programming, covering its basic concepts, structure, and advantages. It outlines the anatomy of a Java program, including class definitions, the main method, and data types, while also discussing control statements and user input handling. The document aims to equip students with the skills to write and run their first Java program using the IntelliJ IDEA IDE.

Uploaded by

adeboyedaniel002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java Programming Basics

This document provides an introduction to Java programming, covering its basic concepts, structure, and advantages. It outlines the anatomy of a Java program, including class definitions, the main method, and data types, while also discussing control statements and user input handling. The document aims to equip students with the skills to write and run their first Java program using the IntelliJ IDEA IDE.

Uploaded by

adeboyedaniel002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 239

Java Programming Basics &

Anatomy of a Java Program

1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)

Author
Liang, Y. Daniel

Download for your progressive learning


Learning Objectives

▪ At the end of this lecture, the student is expected to:


▪ Understand what the Java programming language is about
▪ Understand the structure of a Java program
▪ Be able to write and run your first Java program on the IntelliJ IDEA
IDE

3
How Popular is the Java Programming Language, Source:
4
https://www.tiobe.com/tiobe-index/
Source: https://pypl.github.io/PYPL.html 5
What is Java?

▪ It is a Class-based, Object-Oriented Programming


language
▪ It is a preferred language for meeting many organizations enterprise
programming needs

6
The Inventor of Java

7
Why Java was created

▪ It is originally designed to allow consumer electronic


devices to communicate with each other.
▪ Java’s ability to provide interactivity and multimedia
showed that it was particularly well suited for the Web.

8
Java and other Languages at the Time

▪ Usually, Code in other languages is first translated by a compiler into instructions for
a specific type of computer.
▪ The Java compiler instead turns code into something called Bytecode.
▪ The Bytecode is then interpreted by software called the Java Runtime Environment
(JRE), or the Java virtual machine (JVM).
▪ The JRE acts as a virtual computer that interprets Bytecode and translates it for the host
computer.
▪ Because of this, Java code can be written the same way for many platforms.

9
How Java got its name

▪ It was initially called Oak after an


Oak tree that stood outside
Gosling’s office.
▪ It was later renamed “Green” and
finally Java, from Java coffee
▪ Hence the logo

10
What are the uses of Java?

▪ It is general-purpose computer programming language.


▪ It can be used for
▪ Desktop/Stand-alone Application Development,
▪ Web Application Development
▪ Mobile App development
▪ The Android SDK uses the Java language as the basis for
writing Android applications
11
Some Companies that Use Java in their Tech Stack

12
Advantages of Java (1 of 2)

▪ Simple
▪ Java is straightforward to use, write, compile, debug, and learn than alternative
programming languages.
▪ Java is less complicated than C++;
▪ Java uses automatic memory allocation and garbage collection.
▪ Memory allocation
▪ In Java, memory is divided into two parts one is heap and another is stack.
▪ When a variable is declared, the JVM gives memory from either stack or heap space.
▪ It helps to keep the information and restore it easily.

13
Advantages of Java (2 of 2)
▪ Multithreaded
▪ It has the potential for a program to perform many tasks at the
same time.
▪ Useful in many gaming applications
▪ Platform-Independent
▪ Java code runs on any machine that doesn’t need any special
software to be installed, but the JVM needs to be present on the
machine.
▪ Write Once Run Anywhere (WORA) 14
Write Once Run Anywhere

15
Let’s now write our first Java program

16
Hands-on

▪ Download and install IntelliJ IDEA IDE and run the


HelloWorldApp program using the steps defined in the
notes.

▪ You can follow the first link that comes out as the result of
the following Google search: “intellij idea download”
17
HelloWorld.java

▪ Create a new project by going through File -> New -> Project
▪ or simply create a new project based on the prompt for a new
installation
▪ Select Java amongst the options that contain Java, JavaFX,
Android, …
▪ Check “Create project from template”
▪ Type in the name of the project, e.g. HelloWorldApp, finish/enter.
18
My First Java Program
(Main.java within HelloWorldApp)
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;

public class Main {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

19
Running a Java Program on IntelliJ IDEA

▪ Click the Green “play” button


▪ The output of Main.Java is displayed on the console
▪ To view your source files, click on “Project tab” on the left
hand side of the IDE
▪ Navigate through HelloWorldApp -> src -> com.company
▪ You will be able to view all your Java source files

20
The Basic Anatomy of a Java Program

▪ Class Definition
▪ Main Method
▪ Variables
▪ Java Statements

21
The Basic Anatomy of a Java Program

▪ Class Definition
▪ Java programs will always start with a class definition.
▪ Begin with the word "class" followed by the name of the program.
▪ Use curly braces to start and end the class definition.

22
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;

public class Main {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

23
The Basic Anatomy of a Java Program

▪ Main Method
▪ In java there are many different kinds of classes.
▪ A class with a main method is a program.
▪ The main method is where program execution starts and stops.
▪ Although, the main method can call other classes, objects, methods or
parts of the java language
▪ This is the general structure of a main method in java.
24
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;

public class Main { // class definition starts here


public static void main(String[] args) {
System.out.println("Hello World");
}
} // class definition ends here

25
The Basic Anatomy of a Java Program

▪ Java Statements
▪ A statement represents an action to be carried out.
▪ Statements in java are similar to sentences in English
▪ Statements in java are terminated using a semicolon
▪ The same way that we end sentences in English using a period

26
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;

public class Main {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

27
Hands-on (2)

▪ Write a program to display 5 sentences about yourself on


the screen and format it such that it has a line spacing and
each sentence is on different lines.

28
Hands-on (3)

29
Data Types and Control
Structures in Java

1
Data Types

▪ A Data Type refers to a set of values and a set of operations on those


values.
▪ It is the nature of data that can be represented in a Java program and the
operations to manipulate such data.
▪ In mathematical terms, data types are characterized by the following:
▪ A Domain, - a set of possible values (e.g., integer numbers, real numbers, etc.);
▪ A set of Operations on the elements of the domain (e.g., sum, multiplications, etc.);
▪ A set of Literals, denoting mathematical constants (e.g., 23).
Common Data Types in Java

▪ Primitive Data Type (are ▪ Double

inbuilt data types) ▪ Non Numerical Primitive Data


type
▪ Numerical Primitive Data Type
▪ Boolean
▪ Byte
▪ Char
▪ Short
▪ Int
▪ Long
▪ Float
3
Data Types Available contd.

▪ Reference/Object Data Type


▪ They are created using construct classes to access objects.
Examples of Object Data Types include
▪ Array Variables,
▪ Data Structures (List, HashMap, Sets)
▪ Class Objects, etc.

4
Java Primitive Data types 5
Tokens

▪ In a Java program, all 1. Identifier


characters are grouped into 2. Keywords
symbols called Tokens. 3. Literals
4. Separators
▪ They define the structure of the
programming language 5. Operators
▪ Token sets can be divided into 6. Comments
Six (6) categories.

▪ The categories includes the


following:
6
Identifier

▪ Identifier refers to the name given to a Package, Class,


Interface, Method, or Variable which allows a programmer
to refer to the item from other places in the program.
▪ There are different rules surrounding the Identifiers:
1. Identifiers can be composed of Letters, Numbers, the
Underscore (_) and the Dollar sign ($).

7
Identifier rules contd.

▪ There are different rules surrounding the Identifiers:


2. Identifiers may Only Begin with a Letter, the Underscore or a Dollar
sign.
3. Identifiers cannot be a Reserved word,
▪ e.g. public, class, static, void etc.
4. Identifiers cannot be true, false, or null.
5. Identifiers can be of any length
8
Keywords

▪ These are also known as a Reserved Words.


▪ Keywords are identifiers that Java reserves for its own use that
have a Specific Meaning to the compiler.
▪ These identifiers have built-in meanings that cannot change
▪ Therefore they cannot use these identifiers for anything other than their
built-in meanings.
▪ Examples include: boolean, char, try, catch, null.

9
Operators

▪ Operators is a symbol that Operates on one or more


Operands to produce a Result.
▪ Java includes 37 operators and each of these operators
consist of 1, 2, or at most 3 special characters.

10
Arithmetic Operators 11
Precedence of Arithmetic Operators 12
Equality and Relational Operators 13
Expressions

▪ Expressions are essential building blocks of any Java program


which are built using Values, Variables, operators and Method
Calls. E.g.
▪ int value = 0;
▪ anArray[0] = 100;
▪ int sum = 3 + 2; // sum is now 5
▪ if (value1 == value2)
▪ System.out.println("value1 == value2");
14
More on Expressions

▪ The data type of the value returned by an expression depends on the elements used
in the expression.
▪ The expression value = 0 returns an int because the assignment operator returns a value of the
same data type as its left-hand operand;
▪ in this case, value is an int.
▪ An expression can return other types of values as well, such as boolean or String.
▪ Java programming language allows for the construction of compound expressions
from various smaller expressions as long as the data type required by one part of the
expression matches the data type of the other.

15
Expression examples

▪ 3 * 4 * 5
▪ In this example, the order of evaluation of the expression is not important
because the result of multiplication is independent of order;
▪ the outcome is always the same, no matter the order the multiplications are
applied. However, this does not hold true for all expressions.
▪ a + b / 20
▪ the following expression is ambiguous and gives different results, depending on
whether the addition or the division operation executes first:

16
Expression Examples

▪ (a + b) / 20 // unambiguous, recommended
▪ If the order for the operations to be performed is not explicitly indicated, the order is
determined by the precedence assigned to the operators in use within the expression.
▪ Operators that have a higher precedence get evaluated first. For example, the division
operator has a higher precedence than does the addition operator.
▪ a + (b / 20) // unambiguous, recommended
▪ When writing compound expressions, it is better to be explicit and indicate with
parentheses which operators should be evaluated first.
▪ This practice makes codes easier to read and maintain.

17
Receiving Inputs with the Scanner class

▪ In Java, the major way of receiving inputs is via the Scanner


class
▪ An object of the scanner class is created, then it is used to
receive inputs via the keyboard
▪ An example on the next slide.

18
import java.util.Scanner;

public class Main { Object of Scanner, can be any identifier

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine(); // for a string input
System.out.print("How old are you: ");
int age = in.nextInt(); // for an integer input
System.out.printf("Hello %s, you are %d years old\n", name,
age);
}
}

19
Converting Textual data to numeric data

▪ The following are used to convert a value in typically the


String data type to numeric data types:
▪ Integer: Integer.parseInt()
▪ Double: Double.parseDouble()
▪ Float: Float.parseFloat()

20
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
System.out.print("Enter a numeric value: ");
double val = Double.parseDouble(in.next());
System.out.print("Enter another numeric value: ");
double val2 = Double.parseDouble(in.next());
System.out.printf("Their product is %.2f\n", val * val2);
}
}

Example of data conversion in Java 21


Classwork 1

▪ To be written down in your Note books


1. Write a program to Add, Subtract, Multiply and Divide two numbers
2. Modify solution to question 1 to receive the numbers from the user.
3. Write a program to find the area of a circle
4. Program to convert inches to centimetres
5. Program to average two double-precision numbers
22
Classwork 2

▪ To be written down in your exercise books


▪ Write a program that reads in a temperature in
degrees Fahrenheit and returns the corresponding
temperature in degrees Celsius. The conversion
formula is

23
Classwork 3
▪ Write a program that reads in two numbers: an account
balance and an annual interest rate expressed as a
percentage.
▪ Your program should then display the new balance after a year.
There are no deposits or withdrawals—just the interest payment.

24
Control Statements
Control Statement
▪ Control statements are used to control the flow of execution of
the program.
▪ There are different types of control statements:
▪ Decision Making statements
▪ if-then, if-then-else and switch
▪ Looping statements
▪ while, do-while and for
▪ Branching statements
▪ break, continue and return
If Statement

▪ This is a control statement to execute a


single statement or a block of code when
the given condition is true and if it is false
then it skips the if block and remaining
code in the program is executed.
Example 1

▪ If n%2 evaluates to 0
then the "if" block is
executed.
▪ Here it evaluates to 0 so
the if block is executed.
▪ Hence "This is even
number" is printed on the
screen.
If-else Statement

▪ The "if-else" statement is an


extension of the if statement
that provides another option
when “if” statement evaluates
to "false"
▪ i.e. else block is executed if "if"
statement is false.
Example 2

▪ If n%2 doesn't evaluate to 0


then else block is executed.
▪ Here n%2 evaluates to 1 that
is not equal to 0 so else block
is executed.
▪ So "This is not even number"
is printed on the screen.
Self-Test
What is Wrong with this code?

31
Classwork 4

▪ Write a program to find and print the greater out of two


numbers a and b.
Switch Statement

▪ The keyword "switch" is followed by an expression that should evaluate


to byte, short, char or int primitive data types, only.
▪ In a switch block there can be one or more labelled cases.
▪ The expression that creates labels for the case must be unique.
▪ The switch expression is matched with each case label.
▪ Only the matched case is executed, if no case matches then the default
statement (if present) is executed.
Syntax for Switch Statement
Example 3

▪ Here expression "day" in switch statement evaluates to 5


which matches with a case labelled "5" so code in case 5 is
executed that results to output "Friday" on the screen.
Example 3: Code Snippet
Classwork 5 – Use a switch statement

▪ Write a program to find out the Chinese Zodiac sign Z for a


given year Y. The Chinese Zodiac is based on a twelve-year
cycle (where Z=Y%12), with each year’s sign represented by
an animal;
▪ monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse,
or sheep; the cycle is shown in the figure on the next slide
Classwork 5 - Continuation

For example, if the user types in


2000 for the year,

Your program should display “It’s


the year of the Dragon” since
2000 % 12 = 8

38
while, do…while, and for loop

▪ A loop is used to tell a program to execute statements


repeatedly.
▪ A repetition structure is a control structure that repeats a
statement or sequence of statements in a controlled way.
The while Loop

▪ A while loop executes


statements repeatedly while
the condition is true.
▪ The syntax for the while loop
is:
while loop: Example

▪ To print a
statement 100
times.
Explanation

▪ The part of the loop that contains the statements to be repeated is


called the loop body.
▪ A one-time execution of a loop body is referred to as an iteration (or repetition)
of the loop.
▪ Each loop contains a loop-continuation-condition, a Boolean expression that
controls the execution of the body.
▪ It is evaluated each time to determine if the loop body is executed.
▪ If its evaluation is true, the loop body is executed;
▪ if its evaluation is false, the entire loop terminates and the program control turns to the
statement that follows the while loop.
The do-while Loop

▪ A do-while loop is the same as


a while loop except that it
executes the loop body first
and then checks the loop
continuation condition.
▪ The do-while loop is a variation
of the while loop. Its syntax is:
Explanation

▪ The loop body is executed first, and then the loop-continuation-


condition is evaluated.
▪ If the evaluation is true, the loop body is executed again; if it is false, the
do-while loop terminates.
▪ The difference between a while loop and a do-while loop is the
order in which the loop-continuation-condition is evaluated and
the loop body executed.
Classwork 6

▪ The Fibonacci sequence is a series of numbers such that a


number is generated when the two numbers before it is
added together.
▪ The sequence starts with 0 and 1 i.e. 0,1,1,2,3,5,8,13,21,34
and so on.
▪ Using a do…while statement, write a program to display
the Fibonacci sequence.
Classwork 6
▪ class FibonacciExample1{
▪ public static void main(String args[])
▪ {
▪ int n1=0,n2=1,n3,i,count=10;
▪ System.out.print(n1+" "+n2);//printing 0 and 1
▪ for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
▪ {
▪ n3=n1+n2;
▪ System.out.print(" "+n3);
▪ n1=n2;
▪ n2=n3;
▪ }

▪ }
▪ } 46
The for Loop

▪ A for loop has a


concise syntax for
writing loops.
▪ Often you write a loop
in the following
common form:
In general, the syntax of a for loop is
For loop cont.

▪ The for loop statement starts with the keyword for,


followed by a pair of parentheses enclosing the control
structure of the loop.
▪ This structure consists of initial-action, loop-continuation-
condition, and action-after-each-iteration.
▪ The control structure is followed by the loop body enclosed inside
braces.
For loop cont.

▪ The initial-action, loop continuation-condition, and action-after-each-


iteration are separated by semicolons.
▪ A for loop generally uses a variable to control how many times the loop
body is executed and when the loop terminates.
▪ This variable is referred to as a control variable.
▪ The initial action often initializes a control variable, the action-after-each-
iteration usually increments or decrements the control variable, and the
loop-continuation-condition tests whether the control variable has reached
a termination value.
Example (For loop)

▪ To print Welcome to
Java! a hundred
times:
Classwork 7

▪ Using a while loop and a for loop, write a program to


display numbers from 1 to 5.

▪ Using For/While Loop, write a program to sum the multiples


of three between a range supplied by the user.
Classwork 8

▪ Write a program in Java to find the sum of the first n


elements of the sequence: 1, 11, 111, 1111, 11111…
▪ Let the user supply the value of n

53
Classwork 9

▪ Write a Java program that ▪ Expected Output :


takes a number as input and ▪ 8x1=8
▪ 8 x 2 = 16
print its multiplication table
▪ 8 x 3 = 24
up to 10.
▪ ...
▪ The output should look as ▪ 8 x 10 = 80
follows:
▪ Input a number: 8
Exercise 1: Write a Program to print the
roots of a quadratic equation

▪ The two roots of a quadratic equation 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 can be


obtained using the following formula:
−𝑏 ± 𝑏 2 − 4𝑎𝑐
2𝑎
▪ 𝑏 2 − 4𝑎𝑐 is called the discriminant of the quadratic equation.
▪ If it is positive, the equation has two real roots.
▪ If it is zero, the equation has one root.
▪ If it is negative, the equation has no real roots.
55
Exercise 2: Predicting Tuition

▪ Suppose that the tuition for a university is $10,000 this year


and tuition increases 7% every year. In how many years will
the tuition be doubled?
▪ You are to write a program using loops

56
Methods &
Exception Handling
in Java
What is a Method?

▪ Methods can be used to define reusable code and organize


and simplify coding.
▪ A method is a collection of statements grouped together to
perform an operation.
▪ There are predefined methods in Java, such as
System.out.println and others.
What is a Method?
▪ A method definition consists of its method name,
parameters, return value type, and body
What is a Method?

▪ The Method header specifies the modifier, return value type, method
name and its parameters.
▪ The return value type is the data type the methods would return. Such
methods are called value-returning methods.
▪ Not all methods return values. For a method that doesn’t return any value,
the keyword void is used in place of a return value type
What is a Method? (Cont’d)

▪ The variables in the header are parameters that would receive values
when the method is invoked or called. The value received is also called
an argument.
▪ The method name and parameters consist the method signature.
▪ A method may or may not have a parameter, parameters are optional.
E.g. Math.random()
▪ The method body contains the collection of statements that implement
the method
Types of Methods

▪ Methods with a return value type


▪ E.g. public static int max (int i, int j);

▪ Methods without a return value type


▪ E.g. public static void printGrade(double score);
They are called in different ways in a program.
Calling Methods

▪ Methods with a return value type


▪ These methods are treated as a value when called
▪ E.g. int larger = max(3.5); //max returns a value

▪ Methods that return voids


▪ These methods are called as statements
▪ E.g. printGrade(65); //printGrade() does not return any value
Example of a Return value type Method
Example of a void Method
Classwork 1

▪ Write a method to compute the following series:


1 2 𝑖
▪ 𝑚 𝑖 = + + ⋯+
2 3 𝑖+1

▪ Write a test program that displays the following table


Methods Overloading

▪ Method overloading means multiple methods can have the


same name with different parameters.
▪ Instead of defining two methods that should do the same
thing, it is better to overload one.
▪ Multiple methods can have the same name as long as the
number, sequence and/or type of parameters are different.
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);
}

Method Overloading example


static void computeArea(double l, double b) {
double area = l * b;
System.out.println("Result is " + area);
}

static void computeArea(double l, double b, double h) {


double area = l * b * h;
System.out.println("Result is " + area);
}

public static void main(String[] args) {


computeArea(4, 3.5); // call the first version
computeArea(4, 9, 2.5); // call the second version
}

Overloading methods (2) – different number of arguments


Classwork 2

▪ Write a java program that overloads a method max with int


and double types to return the largest of any three integer
numbers or any three floating point numbers.
Exception Handling
What is Exception Handling?

▪ An exception is an object that represents an error or a condition that


prevents execution from proceeding normally.
▪ The root class for exceptions is java.lang.Throwable.
▪ If not handled, the program will terminate abnormally. Runtime errors
detected by the Java Virtual Machine (JVM) are thrown as exceptions.
▪ All three of these classes Error, Exception, and RuntimeException are
exceptions, and all of the errors occur at runtime.
Exception Types
Definition of some Exception Types

▪ ClassNotFoundException
▪ Attempt to use a class that does not exist.
▪ IOException
▪ Related to input/output operations, such as invalid input, reading past the end of a file, and
opening a non-existent file.
▪ Runtime exceptions
▪ Represented in the RuntimeException class, which describes programming errors, such as
bad casting, accessing an out-of-bounds array, and numeric errors.
Definition of some Exception Types (2)

▪ ArithmeticException
▪ Dividing an integer by zero. Note that floating-point arithmetic does not throw
exceptions
▪ NullPointerException
▪ Attempt to access an object through a null reference variable.
▪ IndexOutOfBoundsException
▪ Index to an array is out of range.
▪ IllegalArgumentException
▪ A method is passed an argument that is illegal or inappropriate.
Exception Handling

▪ Exceptions can be thrown from a method. The caller of the


method can catch and handle the exception.
▪ When an exception is thrown, the normal execution flow is
interrupted.
▪ The statement for invoking the method is contained in a try
block and a catch block.
Exception Handling

▪ The try block contains the code that is executed in normal


circumstances.

▪ The exception is caught by the catch block. The code in the


catch block is executed to handle the exception
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter two integers");
double number1 = scan.nextDouble();
double number2 = scan.nextDouble();

try {
double result = number1 / number2;
System.out.println(number1 + " divided by " + number2 + " is equal to: " + result);
}
catch (ArithmeticException ex) {
System.out.println("Exception:" + "An Integer cannot be divided by zero");
System.out.println("Execution continues...");
}
}
If number2 is 0, the method throws an exception and the
catch block is used to handle exception with the
appropriate message.

Possible division by zero example


Further notes on Exceptions

▪ When programming, it is possible that the exact type of exception that


could occur might not be anticipated

▪ In this case, it is safe to use the general exception class Exception rather
than a specific type in the catch block.

▪ For example
▪ catch (Exception ex) instead of catch (ArithmeticException ex)
Exercises (1)

▪ (Display patterns) Write a method to display a pattern as follows:


1
21
321
...
n n-1 ... 3 2 1
▪ The method header is
▪ public static void displayPattern(int n)
Exercises (2)

▪ (Display matrix of 0s and 1s) Write a method that displays an n-by-n matrix using
the following header:
▪ public static void printMatrix(int n)
▪ Each element is 0 or 1, which is generated randomly. Write a test program that
prompts the user to enter n and displays an n-by-n matrix. Here is a sample run:
Exercises (3)

▪ (Occurrences of a specified character) Write a method that finds the


number of occurrences of a specified character in a string using the
following header:
▪ public static int count(String str, char a)
▪ For example, count("Welcome", 'e') returns 2.

▪ Write a test program that prompts the user to enter a string followed by a
character and displays the number of occurrences of the character in the
string.
Exercises (4)

▪ In Exercise 3, the expression count("Welcome", ‘w’) returns 0.


▪ Enhance your program in Exercise 3 to count accurately
regardless of the letter case.
▪ Sample output shown below
Method Overloading in Java

1
Java Method overloading

▪ Method overloading means multiple methods can have


the same name with different parameters
▪ Instead of defining two methods that should do the same
thing, it is better to overload one.

2
Java Method overloading – Instead of
▪ 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); } 3
Java Method overloading – Better to
▪ 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); } 4
Java Method overloading

▪ Multiple methods can have the same name as long as the


number, sequence and/or type of parameters are
different

5
Method overloading by changing data type
of arguments
▪ class Calculate
▪ {
▪ void sum (int a, int b)
▪ {
▪ System.out.println("sum is"+(a+b)) ;
▪ }
▪ void sum (float a, float b)
▪ {
▪ System.out.println("sum is"+(a+b));
▪ }
▪ Public static void main (String[] args)
▪ {
▪ Calculate cal = new Calculate();
▪ cal.sum (8,5); //sum(int a, int b) is method is called.
▪ cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
▪ }
▪ }
6
Method overloading by changing number
of arguments
▪ class Demo
▪ {
▪ void multiply(int l, int b)
▪ {
▪ System.out.println("Result is"+(l*b)) ;
▪ }
▪ void multiply(int l, int b,int h)
▪ {
▪ System.out.println("Result is"+(l*b*h));
▪ }
▪ public static void main(String[] args)
▪ {
▪ Demo ar = new Demo();
▪ ar.multiply(8,5); //multiply(int l, int b) is method is called
▪ ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
▪ }
▪ }
7
Method overloading by changing sequence
of arguments
▪ class Demo{

▪ public void get(String name, int id)


▪ {
▪ System.out.println("Company Name :"+ name);
▪ System.out.println("Company Id :"+ id);
▪ }

▪ public void get(int id, String name)


▪ {
▪ System.out.println("Company Id :"+ id);
▪ System.out.println("Company Name :"+ name);
▪ }
▪ }

▪ class MethodDemo8{
▪ public static void main (String[] args) {
▪ Demo obj = new Demo();
▪ obj.get("Cherry", 1);
▪ obj.get("Jhon", 2);
▪ }
▪ }
8
Classwork 1

▪ Write a java program. A first class DislayOverloading has a


method add that returns the sum of two integers. Then call
the method in another class displayMax.
▪ Overload the add method to return the sum of 3 integers when
called.
Classwork 1
▪ class DisplayOverloading
▪ {
▪ }
▪ //adding two integer numbers
▪ class displayMax
▪ int add(int a, int b)
▪ {
▪ {
▪ public static void main(String args[])
▪ int sum = a+b;
▪ {
▪ return sum;
▪ DisplayOverloading obj = new
▪ } DisplayOverloading();
▪ //adding three integer numbers ▪ System.out.println(obj.add(10, 20));
▪ int add(int a, int b, int c) ▪ System.out.println(obj.add(10, 20, 30));
▪ { ▪ }
▪ int sum = a+b+c; ▪ }
▪ return sum;
▪ }
Classwork 2

▪ Write a java program. It has a first class


displayOverloading2 that overloads a method add with
integer and floating point types set for 2 inputs, to return
their sum, then call the method in another class
displayMax2.
Classwork 2
▪ class displayOverloading2 ▪ class displayMax2
▪ { ▪ {
▪ //two int parameters ▪ public static void main(String args[])
▪ public int add(int a, int b) ▪ {
▪ { ▪ displayOverloading2 obj = new displayOverloading2();
▪ int sum = a+b; ▪ //This will call the method add with two int params
▪ return sum; ▪ System.out.println(obj.add(5, 15));
▪ }
▪ //two float parameters ▪ //This will call the method add with two float params
▪ public float add(float a, float b) ▪ System.out.println(obj.add(5.5f, 2.5f));
▪ { ▪ }
▪ float sum = a+b; ▪ }
▪ return sum;
▪ }
▪ }
Classwork 3

▪ Write a java class Sum. It has a method sum to return the


sum of two integers. Then call the method.
▪ Overload the sum method to return the sum of 3 integers when
called.
▪ Overload the sum method to return the sum of 2 floating point
numbers when called
Classwork 3
▪ // Overloaded sum(). This sum takes two double
▪ // Java program to demonstrate working of method ▪ // parameters
▪ // overloading in Java ▪ public double sum(double x, double y)
▪ {
▪ public class Sum { ▪ return (x + y);
▪ }

▪ // Overloaded sum(). This sum takes two int parameters


▪ // Driver code
▪ public int sum(int x, int y) { return (x + y); }
▪ public static void main(String args[])
▪ {
▪ // Overloaded sum(). This sum takes three int ▪ Sum s = new Sum();
parameters ▪ System.out.println(s.sum(10, 20));
▪ public int sum(int x, int y, int z) ▪ System.out.println(s.sum(10, 20, 30));
▪ { ▪ System.out.println(s.sum(10.5, 20.5));

▪ return (x + y + z); ▪ }
▪ }
▪ }

14
Assignment

▪ Write a java class textMax that overloads a method max


with int and double types to return the largest of any three
integer numbers or any 3 floating point numbers.
For more examples

▪ See next slides

16
▪ // Java Program to Illustrate Method Overloading ▪ // Class 2

▪ // By Changing the Number of Parameters ▪ // Main class


▪ class GFG {

▪ // Importing required classes


▪ import java.io.*; ▪ // Main driver method
▪ public static void main(String[] args)

▪ // Class 1 ▪ {

▪ // Helper class
▪ class Product { ▪ // Creating object of above class inside main()
▪ // method

▪ // Method 1 ▪ Product ob = new Product();

▪ // Multiplying two integer values


▪ public int multiply(int a, int b) ▪ // Calling method to Multiply 2 numbers

▪ { ▪ int prod1 = ob.multiply(1, 2);

▪ int prod = a * b;
▪ return prod; ▪ // Printing Product of 2 numbers

▪ } ▪ System.out.println(
▪ "Product of the two integer value :" + prod1);

▪ // Method 2
▪ // Multiplying three integer values ▪ // Calling method to multiply 3 numbers

▪ public int multiply(int a, int b, int c) ▪ int prod2 = ob.multiply(1, 2, 3);

▪ {
▪ int prod = a * b * c; ▪ // Printing product of 3 numbers

▪ return prod; ▪ System.out.println(

▪ } ▪ "Product of the three integer value :" + prod2);

▪ } ▪ }
▪ }

17
▪ // Multiplying three double values.

▪ // Java Program to Illustrate Method Overloading ▪ public double Prod(double a, double b, double c)

▪ // By Changing Data Types of the Parameters ▪ {


▪ double prod2 = a * b * c;
▪ return prod2;
▪ // Importing required classes
▪ }
▪ import java.io.*;
▪ }

▪ // Class 1
▪ class GFG {
▪ // Helper class
▪ public static void main(String[] args)
▪ class Product { ▪ {
▪ Product obj = new Product();
▪ // Multiplying three integer values
▪ public int Prod(int a, int b, int c) ▪ int prod1 = obj.Prod(1, 2, 3);

▪ { ▪ System.out.println("Product of the three integer value :" +


prod1);
▪ double prod2 = obj.Prod(1.0, 2.0, 3.0);
▪ int prod1 = a * b * c;
▪ System.out.println("Product of the three double value :" +
▪ return prod1; prod2);
▪ } ▪ }
▪ } 18
▪ // Class 2
▪ // Java Program to Illustrate Method Overloading
▪ // Main class
▪ // By changing the Order of the Parameters
▪ class GFG {
▪ // Importing required classes
▪ import java.io.*; ▪ public static void main(String[] args)
▪ {
▪ // Class 1
▪ // Helper class
▪ class Student { ▪ // Creating object of
above class
▪ // Method 1 ▪ Student obj = new
▪ public void StudentId(String name, int roll_no) Student();
▪ {
▪ System.out.println("Name :" + name + " " +
"Roll-No :" + roll_no); ▪ // Passing name and id
▪ } ▪ // Note: Reversing order
▪ // Method 2 ▪ obj.StudentId("Spyd3r",
▪ public void StudentId(int roll_no, String name) 1);
▪ {
▪ obj.StudentId(2,
▪ // Again printing name and id of person "Kamlesh");
▪ System.out.println("Roll-No :" + roll_no + " " + "Name :" + name);
▪ }
▪ }
▪ }
▪ } 19
▪ int public add(float a, float b){
▪ int c;
▪ Below is the code that explains the Method Overloading in
Java: ▪ c=a+b;

▪ Class sum{ ▪ return c;


▪ }
▪ private int a;
▪ int public add(float a, int b, int c){
▪ private int b;
▪ int d;
▪ private int c;
▪ d=a+b+c;
▪ private int d;
▪ return d;
▪ int public add(int a, int b){
▪ }
▪ int c;

▪ c=a+b; ▪ }
▪ return c; ▪ Public static void main (String[]args)
▪ } ▪ {
▪ int public add(int a, float b){ ▪ // Creating object of the class in main method
▪ int c; ▪ sum obj1 = new sum();
▪ c=a+b; ▪ sum1=obj1.add(10,20);
▪ return c; ▪ sum2=obj1.add(10,55.5);
▪ } ▪ sum3=obj1.add(110.5,25.5);
▪ sum4=obj1.add(10,20,30);
20
Java Methods

1
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 or subroutines.
▪ Why methods? To be able reuse codes many times
How to 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

3
Example

▪ Methods are created inside Main class.


▪ public class Main {
▪ static void myMethod() {
▪ // code to be executed
▪ }
▪ }
4
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.
▪ void means that this method does not have a return value.

5
How to call a method

▪ To call a method in Java, write the method's name followed


by two parentheses () and a semicolon;

6
Example on how to call a method
▪ public class Main {
▪ static void myMethod() {
▪ System.out.println(“Ijust got executed”)
▪ }

▪ public static void main(String[] args) {


▪ myMethod();
▪ }
▪ }
7
A method can be called multiple times
▪ public class Main {
▪ static void myMethod() {
▪ System.out.println(“Ijust got executed”)
▪ }

▪ public static void main(String[] args) {


▪ myMethod();
▪ myMethod();
▪ myMethod();
▪ myMethod();
▪ }
▪ } 8
Java method parameters

▪ 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.

9
Java method parameters - Example
▪ public class Main {
▪ static void myMethod(String firstName) {
▪ System.out.println(firstName + “Oyedepo”)
▪ }

▪ public static void main(String[] args) {


▪ myMethod(“David”);
▪ myMethod(“Faith”);
▪ myMethod(“Isaac”);
▪ myMethod(“David-Jnr”);
▪ }
▪ } 10
Multiple parameters

▪ A java program can have as many parameters as possible


▪ When 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.

11
Multiple parameters - example
▪ public class Main {
▪ static void myMethod(String firstName, int age) {
▪ System.out.println(firstName + “Oyedepo” + “is” + age + “years old”)
▪ }

▪ public static void main(String[] args) {


▪ myMethod(“David”, 69);
▪ myMethod(“Faith”, 66);
▪ myMethod(“Isaac”, 38);
▪ myMethod(“David-Jnr”, 35);
▪ }
▪ } 12
Return values

▪ The void keyword used in above examples indicates that


the method should not return a value.
▪ To return a value, a primitive data type (e.g. int, char, double
etc.) replaces void in the method declaration.
▪ The return keyword is then used inside the method

13
Return value - example
▪ public class Main {
▪ static int myMethod(int age) {
▪ return age + 5
▪ }

▪ public static void main(String[] args) {


▪ System.out.println(myMethod(3));
▪ }
▪ }
14
Return value – example 2
▪ This example returns the sum of a method’s two parameters

▪ public class Main {


▪ static int myMethod(int x, int y) {
▪ return x + y
▪ }

▪ public static void main(String[] args) {


▪ int total = myMethod(5, 3)
▪ System.out.println(myMethod);
▪ }
▪ } 15
A method with If…Else
▪ It is common to use if…else inside methods

▪ public class Main {


▪ static int checkAge(int age) {
▪ if (age < 18) {
▪ System.out.println(“Access denied – you are not old enough”);
▪ } else {
▪ System.out.println(“Access granted – you are old enough”);
▪ }
▪ }

▪ public static void main(String[] args) {


▪ checkAge(20);
▪ }
▪ } 16
Method Overloading in Java

1
Java Method overloading

▪ Method overloading means multiple methods can have the


same name with different parameters.
▪ Instead of defining two methods that should do the same
thing, it is better to overload one.
▪ Multiple methods can have the same name as long as the
number, sequence and/or type of parameters are different.
2
Java Method overloading – Instead of
▪ 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); } 3
Java Method overloading – Better to
▪ 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); } 4
Method overloading by changing data type
of arguments

▪ class Calculate ▪ }
▪ { ▪ Public static void main (String[] args)
▪ void sum (int a, int b) ▪ {
▪ { ▪ Calculate cal = new Calculate();
▪ System.out.println("sum is"+(a+b)) ; ▪ cal.sum (8,5); //sum(int a, int b) is
method is called.
▪ } ▪ cal.sum (4.6f, 3.8f); //sum(float a, float b) is
▪ void sum (float a, float b) called.
▪ { ▪ }
▪ System.out.println("sum is"+(a+b)); ▪ }

5
Method overloading by changing number
of arguments

▪ class Demo
▪ System.out.println("Result is"+(l*b*h));
▪ {
▪ }
▪ void multiply(int l, int b) ▪ public static void main(String[] args)
▪ { ▪ {
▪ System.out.println("Result is"+(l*b)) ; ▪ Demo ar = new Demo();
▪ } ▪ ar.multiply(8,5); //multiply(int l, int b) is method is
called
▪ void multiply(int l, int b,int h)
▪ ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
▪ {
▪ }
▪ System.out.println("Result ▪ }
is"+(l*b*h));
6
Method overloading by changing sequence
of arguments
▪ System.out.println("Company Name :"+
▪ class Demo{ name);
▪ }
▪ public void get(String name, int id) ▪ }
▪ {
▪ System.out.println("Company Name :"+ name); ▪ class MethodDemo8{
▪ System.out.println("Company Id :"+ id);
▪ public static void main (String[] args) {
▪ }
▪ Demo obj = new Demo();
▪ public void get(int id, String name) ▪ obj.get("Cherry", 1);
▪ { ▪ obj.get("Jhon", 2);
▪ System.out.println("Company Id :"+ id); ▪ }
▪ }
7
Classwork

1) Write a java program. A first class DislayOverloading has a method add


that returns the sum of two integers. Then call the method in another
class displayMax. Overload the add method to return the sum of 3
integers when called.
2) Write a java program. It has a first class displayOverloading2 that
overloads a method add with integer and floating point types set for 2
inputs, to return their sum, then call the method in another class
displayMax2.
Classwork 1
▪ class DisplayOverloading
▪ {
▪ }
▪ //adding two integer numbers
▪ class displayMax
▪ int add(int a, int b)
▪ {
▪ {
▪ public static void main(String args[])
▪ int sum = a+b;
▪ {
▪ return sum;
▪ DisplayOverloading obj = new
▪ } DisplayOverloading();
▪ //adding three integer numbers ▪ System.out.println(obj.add(10, 20));
▪ int add(int a, int b, int c) ▪ System.out.println(obj.add(10, 20, 30));
▪ { ▪ }
▪ int sum = a+b+c; ▪ }
▪ return sum;
▪ }
Classwork 2
▪ class displayOverloading2 ▪ class displayMax2
▪ { ▪ {
▪ //two int parameters ▪ public static void main(String args[])
▪ public int add(int a, int b) ▪ {
▪ { ▪ displayOverloading2 obj = new displayOverloading2();
▪ int sum = a+b; ▪ //This will call the method add with two int params
▪ return sum; ▪ System.out.println(obj.add(5, 15));
▪ }
▪ //two float parameters ▪ //This will call the method add with two float params
▪ public float add(float a, float b) ▪ System.out.println(obj.add(5.5f, 2.5f));
▪ { ▪ }
▪ float sum = a+b; ▪ }
▪ return sum;
▪ }
▪ }
Assignment

1) Write a java class textMax that overloads a method max with int
and double types to return the largest of any three integer
numbers or any 3 floating point numbers.
2) Write a java class Sum. It has a method sum to return the sum
of two integers. Then call the method. Overload the sum method
to return the sum of 3 integers when called. Overload the sum
method to return the sum of 2 floating point numbers when
called
Assignment 1
▪ // Overloaded sum(). This sum takes two double
▪ // Java program to demonstrate working of method ▪ // parameters
▪ // overloading in Java ▪ public double sum(double x, double y)
▪ {
▪ public class Sum { ▪ return (x + y);
▪ }

▪ // Overloaded sum(). This sum takes two int parameters


▪ // Driver code
▪ public int sum(int x, int y) { return (x + y); }
▪ public static void main(String args[])
▪ {
▪ // Overloaded sum(). This sum takes three int ▪ Sum s = new Sum();
parameters ▪ System.out.println(s.sum(10, 20));
▪ public int sum(int x, int y, int z) ▪ System.out.println(s.sum(10, 20, 30));
▪ { ▪ System.out.println(s.sum(10.5, 20.5));

▪ return (x + y + z); ▪ }
▪ }
▪ }

12
Array and Strings

1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)

Author
Liang, Y. Daniel

Download for your progressive learning


LECTURE OUTLINE

▪ Arrays
▪ One dimensional arrays
▪ Multi-dimensional arrays
▪ Strings processing
▪ ArrayLists
Arrays

▪ Array stores variables of the same data type


▪ To declare an array (named sampleArray) that is of type integer.

// declares an array of integers


int[] sampleArray;

▪ There are two components of an array declaration:


Components of array declaration (1)

▪ Array type: This is written as type[] where type is the data


type of the elements contained.
▪ The brackets are special symbols indicating that the variable holds
an array. The size of the array is not part of the type (which is why
the brackets are empty).
Components of array declaration (2)

▪ Array name: This can be anything you want as long as it follows


the rules and conventions of naming variables.
▪ As with variables of other types, the declaration does not actually
create an array; it simply tells the compiler that this variable will hold an
array of specified type.
Furthermore,
You can declare arrays of other types
byte[] sampleArrayOfBytes;
short[] sampleArrayOfShorts;
long[] sampleArrayOfLongs;
float[] sampleArrayOfFloats;
double[] sampleArrayyOfDoubles;
boolean[] sampleArrayOfBooleans;
char[] sampleArrayOfChars;
string[] sampleArrayfStrings;
More on arrays

▪ You can also place the brackets after the array name;
//this form is discouraged
float sampleArrayOfFloats[];
▪ However, it is not advisable due to the fact that brackets
identify the array type and should appear with the type
designation.
Creating and initializing an array

▪ An example of how to create an array is filling the elements


of the array at the point of creation.
▪ //Create an array of integer
▪ int[] sampleArray = {4, 8, 6, 1, -4};
▪ By doing this, the array length is determined
implicitly
Dynamically initializing an array

▪ Another example of how to create an array is using the new


operator. This is used when the array elements are not
known before hand.
▪ //Create an array of integers with a size of 10
▪ int[] sampleArray = new int[10];
▪ If the RHS of this statement is missing, then the compiler
points an error and compilation fails.
More on Arrays – Accessing array
elements

sampleArray[0] =100; // stores value in the first element


sampleArray[1] =200; // stores value in the second element
sampleArray[2] =300; // and so on

Each array element is accessed by its numerical index.


System.out.println("Element 1 at index 0:" + sampleArray[0]);
System.out.println("Element 2 at index 1:" + sampleArray[1]);
System.out.println("Element 3 at index 2:" + sampleArray[2]);
More on Arrays

▪ The built-in length property can be used to determine the


size of any array. The following code will print the array’s
size to standard output.
System.out.println(sampleArray.length);
Example 1

public class arrays {


public static void main(String[] args) {
int[] sample = {3, 5, 5, 1, 0, -6};
for(int i = 0; i < sample.length; i++) //line 4
System.out.print(sample[i] + " "); //line 5
}
}
Explanation

▪ The program listing in Example 1 displays the contents of a one


dimensional array, lines 4-5 select the items in the array one after
the other for display.
▪ You would notice we can automatically know the length of an array
using the length property provided by Java
▪ In Example 1, the expression sample.length returns 6 since we
have six elements enclosed within the curly braces
Example 2

▪ The code on the next slide demonstrates a sample code that


works with an array whose size and elements were not known
before the program run

▪ In the code, we have to get various inputs:


▪ The size of the array
▪ The array elements
15
public static void main(String[] args) {
int[] sample;
int n;
Scanner in = new Scanner(System.in);
System.out.print("How many elements do you have in the array: ");
n = in.nextInt(); //get the size of the array via the keyboard
sample = new int[n]; //use the size to initialise the array dynamically
for(int i = 0; i < n; i++){ //go through each index of the array
System.out.printf("Input element[%d]: ", i); //ask for the ith element
sample[i] = in.nextInt(); //store the element at position i
}

System.out.println("Your array elements include: ");


for(int i = 0; i < n; i++)
System.out.print(sample[i] + " "); //print array element at position i
}

Example 2 - Code 16
Classwork 1

▪ Write a program to read, store and print the score of 20


students in an array
▪ Hint: It is similar to Example 2
Classwork 2

▪ Write a program to read six integers and determine both the


largest and smallest
Multi-dimensional Arrays

▪ You can declare array of arrays (multidimensional array) by


using two or more sets of brackets such as string[][] names.

▪ In Java, a multidimensional array is an array whose


components are themselves arrays.
Example 3 – Java code that initialises a 2D
array and prints out its elements
int[][] sample = {{1, 3, 4, 5, 6}, {4, 9, 0, 2, 11}};
System.out.println("Your array elements include: ");
for(int i = 0; i < sample.length; i++){
for(int j = 0; j < sample[i].length; j++) { //we can do
this because element i is an array itself
System.out.print(sample[i][j] + " "); //print array
element at position i, j
}
System.out.println();
}
20
Example 3 – Alternative code

//Alternatively
int[][] sample = {{1, 3, 4, 5, 6}, {4, 9, 0, 2, 11}};
System.out.println("Your array elements include: ");
for(int i = 0; i < 2; i++){ //2 rows in the 2D array
for(int j = 0; j < 5; j++) { //5 columns in the 2D array
System.out.print(sample[i][j] + " ");
}
System.out.println();
}
21
Copying Arrays

▪ The System class has an arraycopy method that can be used to


efficiently copy data from one array into another.
▪ public static void main arraycopy(Object src, intsrcpos, Object dest,
intdestpos, int length)
▪ The first object argument specifies the array to copy from.
▪ The second object argument specifies the array to copy to.
▪ The three int arguments specifies the starting position of the source array, the
starting position of the destination array and the number of array elements to
copy respectively.
public static void main(String[] args) {
int[] sample = {1, 3, 4, 5, 6};
int[] sample2 = new int[sample.length];
//copying operation
System.arraycopy(sample, 0, sample2, 0, sample.length);
System.out.println("Elements in sample2 array are: ");
for(int i = 0; i < sample2.length; i++)
System.out.print(sample2[i] + " ");
} Output:

Notice the expression:


System.arraycopy(sample, 0, sample2, 0, sample.length);
You can clearly identify the five arguments of the arraycopy() method of the Java System
class

Example 4 – Copying array elements 23


STRING PROCESSING

▪ A string is a sequence of characters. The most direct way


to create a string is to write −
String greeting = "Hello world!";
▪ Whenever it encounters a string literal in your code, the
compiler creates a String object with its value in this case,
"Hello world!'.
String cont.

▪ As with any other object, you can create String objects by


using the new keyword and a constructor.
▪ The String class has many constructors that allow you to
provide the initial value of the string using different sources,
such as an array of characters.
Immutability of the string object

▪ The String class is immutable, so that once it is created a


character within the String object cannot be changed.
▪ If there is a necessity to make a lot of modifications to
Strings of characters, then you should use String Buffer &
String Builder Classes.
String Length

▪ Strings are made up of different numbers of characters.

▪ To get information about the length of the string, the


accessor method length() is used.
public static void main(String[] args) {
//create a character array
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
//use it to initialise a new string
String myString = new String(charArray);
//concatenate the string with a name
String concat_string = myString.concat(" Zara");
//see the output of concatenation
System.out.println(concat_string);
//print the string's length
System.out.println(concat_string.length());
}

Example 5
Concatenating Strings

The String class includes a method for concatenating two strings.


string1.concat(string2);
▪ This returns a new string that is string1 with string2 added to it at the end.
▪ You can also use the concat() method with string literals, as in −
"My name is ".concat("Zara");
Concatenating Strings (2)

▪ Strings are more commonly concatenated with the +


operator, as in −
"Hello," + " world" + "!"
which results in
"Hello, world!"
String cont.

▪ To get more than one consecutive characters from a string, you can use
the substring method.

▪ The substring method has two versions as shown in Table 1.


Method Description
String substring (intbeginIndex, Returns a new string that is a substring of
intendIndex) this string. The substring begins at the
specified beginIndex and extends to the
character at index endIndex - 1
String substring (intbeginIndex) Returns a new string that is a substring of
this string. The integer argument specifies
the index of the first character. Here, the
returned substring extends to the end of
the original string
Table 1 – String class methods
Example 6

▪ The following codes gets from “Testing the usefulness of Java!”, the
substring that extends from index 12 up to index 22, which is the word
“usefulness”.

String anotherExample = " Testing the usefulness of Java!";


String usefulness = anotherExample(12,22);
Method Description
String[] split(String regex) Searches for a method as specified by the
String[] split(String regex, int limit) string argument which contains a regular
expression and splits this string into an
array of string accordingly. The optional
integer argument specifies the maximum
size of the returned array.
charSequence subsequence(intbeginIndex, Returns a new character sequence
intendIndex) constructed from beginIndex index up
until endIndex – 1
String trim() Return a copy of this string with leading
and trailing white space removed
String toLowerCase() Returns a copy of the string converted to
String toUpperCase lowercase or uppercase. If no conversions
are necessary, these methods return the
original string
Table 2: Other methods in the String class for manipulating strings
Methods Description
intindexOf( intch) Returns the index of the first (last)
intlastIndexOf(intch) occurrence of the specified character
intindexOf( intch, intfromIndex) Returns the index of the first (last)
intlastIndexOf(intch, intfromIndex) occurrence of the specified character,
searching forward (backward) from the
specified index
intindexOf(String str) Returns the index of the first (last)
intlastIndexOf(String str) occurrence of the specified substring
intindexOf(String str, intfromIndex) Returns the index of the first (last)
intlastIndexOf(String str, intfromIndex) occurrence of the specified substring,
searching forward (backward) from the
specified index
boolean contains (char sequence S) Returns true if the string contains the
specified character sequence
Table 3: The search method in the String class
Method Description
String replace(char oldChar, char Returns a new string resulting from
newChar) replacing all occurrence of oldChar in this
string with newChar
String replace(CharSequence target, Returns each substring of this string that
CharSequence replacement) matches the literal target sequence with
the specifier literal replacement sequence
String replaceAll (string regex, string Replaces each substring of this string that
replacement) matches the given regular expression with
the given replacement
String replaceFirst (string regex, string Replaces the first substring of this string
replacement) that matches the given regular expression
with the given replacement

Table 4 : Replacing characters and substrings into a string


Classwork 3

▪ Given String theme = “My future is bright”; what will be the value
returned from the following:
▪ theme.substring(10, 15);
▪ theme.indexOf(“o”);

▪ theme.lastIndexOf(“e”, 6);
▪ theme.contains(‘!’);
Classwork 4

▪ (Convert letter grade to number) Write a program that


prompts the user to enter a letter grade A, B, C, D, or F
▪ The program should then display its corresponding numeric
value 4, 3, 2, 1, or 0. Here is a sample run:
Classwork 5

▪ Write a program to compute the sum and product of two 3x3


Matrices A and B using the following methods:
▪ readInput to read the elements of the matrices
▪ findSum to compute the sum of the two matrices
▪ findProduct to compute the product of the two matrices
▪ WriteResult to print the sum and product of the matrices.
Classwork 6

▪ (Student major and status) Write a program that prompts the user to enter
two characters and displays the major and status represented in the
characters.

▪ The first character indicates the major and the second is number
character 1, 2, 3, 4, which indicates whether a student is a freshman,
sophomore, junior, or senior.
40
Classwork 6 cont’d

▪ Suppose the following


characters are used to denote
the majors:
▪ M: Mathematics
▪ C: Computer Science
▪ I: Information Technology

41
More Exercises – Main Text

▪ Exercise 7.8
▪ Exercise 7.10
▪ Exercise 8.10
▪ Exercise 8.11
▪ Exercise 8.17
42
Objects & Classes

1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)

Author
Liang, Y. Daniel

Download for your progressive learning


LECTURE OUTLINE
▪ Introduction to Objects
▪ Classes
▪ Constructors
▪ Reference Variables/Types
▪ The ArrayList class
▪ Array of Objects
▪ The This Reference
What is Object-Oriented Programming
(OOP)?

▪ Places emphasis on the objects- which are a representation of


the domain of interest.
▪ Computer programs are designed by making them out of objects
that interact with one another.
▪ For example, a student, a desk, a circle, a button, and even a loan
can all be viewed as objects. An object has a unique identity,
state, and behaviour.
4
What is OOP?

▪ For example, a student, a desk, a circle, a button, and even a loan


can all be viewed as objects. An object has a unique identity, state,
and behaviour.
▪ The state of an object represents its properties/attributes, represented by
data fields with their current values.
▪ The behaviour of an object represents the actions that can be performed
by/on the object, achieved via methods.

5
Class as a concept in OOP

▪ The objects we are talking about can be created via classes.


▪ A class is a template or blueprint that defines what an object’s
data fields and methods will be.
▪ An object is an instance of a class.
▪ You can create many instances of a class.
▪ Creating an instance is referred to as instantiation.

6
A simple example – Circle class

A constructor is primarily a method but


has the same name as that of the class

Let’s define the class Circle based on the


given UML description of the class

7
Steps

▪ Create a new project in IntelliJ


▪ Make sure you check “Create project from template” option
▪ Name the project “ClassDemo”
▪ After creating the project, right-click on the “src” folder on the project view
window on the LHS of the IDE.
▪ Select New -> Java class to create a new class. Name the new class Circle
▪ Now, you should have two java files in the source folder
8
public class Circle {
double radius;
public Circle(){ radius = 1; }
public Circle(double newRadius){ radius = newRadius; }
double getArea() {
return radius * radius * Math.PI; //𝜋𝑟 2
}
double getPerimeter() {
return 2 * Math.PI * radius; //2𝜋r
}
void setRadius(double newRadius) { radius = newRadius; }
}

Inside Circle.java 9
Creating Objects of a class

▪ Just like naming variables. For example, an integer variable b can


be created as follows:
▪ int b;
▪ Objects are also “variables”, but they are associated with reference
types, e.g. a class.
▪ To create an object of a circle, we would have the following, where
objC is the name of the object:
▪ Circle objC; 10
Object Instantiation

▪ Before you can use an object of a class, it needs to be


instantiated using the new keyword.
▪ For objC, we would have:
▪ objC = new Circle();
▪ The expression above calls the constructor of the Circle class
and initialises the data fields of the objC object.
11
Object Instantiation (2)

▪ Although, the initialisation of data fields is based on what was


defined in the constructor.
▪ For the Circle class, we can instantiate an object in two different ways due
to the fact that it has two constructors.
▪ Next, we can now use the object freely by calling the appropriate
methods.
▪ The next slide demonstrates the usage of the Circle class.
12
public class Main {
public static void main(String[] args) {
Circle c1 = new Circle(); //calling the non-parameterised constructor
Circle c2 = new Circle(10); //another instance
System.out.println("Perimeter of c1: " + c1.getPerimeter());
System.out.println("Perimeter of c2: " + c2.getPerimeter());
c2.setRadius(7.0); //change the radius of circle c2
System.out.println("Area of c1: " + c1.getArea());
//print the area of circle c2
System.out.println("Area of c2: " + c2.getArea());
}
}

Inside the main class 13


Primitive Types and Reference Types

▪ If for example, you have the following:


▪ int i = 0; int j = i;
▪ The value of i is copied to j.
▪ For a variable of a reference type, the value is a reference to where
an object is located. For example, for the two objects of Circle:
▪ c2 = c1
▪ This means that c2 and c1 will be pointing to the same reference.
This has implications!
14
Reference Type Assignment
Circle c1 = new Circle(); //value of radius should be 1.0
Circle c2 = c1;
c2.setRadius(7.0); //change the radius of circle c2; it
changes the radius of c1 too
System.out.println("Area of c1: " + c1.getArea());
System.out.println("Area of c2: " + c2.getArea());

When the area of both objects are printed, the same value is
outputted since c1 and c2 both reference the same memory location 15
The ArrayList Class
(Automatic shrinking and expansion of arrays)

▪ The ArrayList class adds more flexibility to managing a set of


homogenous values.
▪ It is provided via the java.util package, and employed when the
array length needed to solve a problem is dynamic.

▪ The format for declaring an ArrayList object is as follows:


▪ ArrayList<datatype> varName = new ArrayList()<>;

16
More on the ArrayList class

▪ The documentation of the ArrayList class and a list of its


methods can be found via the link below:
▪ https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
▪ Common methods include the following: add(), remove(),
contains(), indexOf(), isEmpty()

17
Example 1

▪ Write a program that randomly generates 20 integers in the


range [1,50] and stores the even numbers generated in an
array.
▪ The question is: Do you know the exact number of even
numbers that would be generated?
▪ Let’s solve the problem using an ArrayList.
▪ You need to include java.util.Random and java.util.ArrayList
18
public static void main(String[] args) {
Random rng = new Random();
ArrayList<Integer> bucket = new ArrayList<>();
for(int i=0; i<20; i++){
//for the code below, generate a number btw. 0 and 49, then add 1
int randNum = rng.nextInt(50) + 1;
if(randNum % 2 == 0)
bucket.add(randNum);
}

for(int num : bucket)


System.out.print(num + " ");

System.out.println();
System.out.println(bucket.isEmpty());
System.out.println(bucket.contains(18));
}
19
Explanation of Example 1 code

▪ The line:
▪ ArrayList<Integer> bucket = new ArrayList<>();
▪ simply creates a new ArrayList object (bucket) whose elements are
Integers. Notice that “Integer” is used rather than “int”
▪ The expression bucket.add(randNum); adds a new member
(the value of the variable randNum) to the arraylist

20
Explanation of Example 1 code (Cont’d)

▪ Notice the special kind of for loop used in the code


▪ for(int num : bucket)
▪ This is the for each loop, it is a more efficient way of looping through
elements of an array-like object
▪ The last two lines check the following in this order:
▪ If the ArrayList is empty
▪ If the ArrayList contains the value 18.
21
Protecting Data Members

▪ Our very first example, the Circle class has a data member
called radius.
▪ While using the object of a class, a user may inadvertently
change the value of radius.
▪ One way to protect the radius instance variable from such is
to declare it private.
22
Protecting Data Members (2)

▪ Our first version of the Circle class, one could directly refer to
the member variable radius by doing the following:
▪ c1.radius() or
▪ c2.radius()
▪ This is an undesirable property as the essence of creating a
class in the first place is to facilitate Data Encapsulation
23
public class Circle {
private double radius; //now a private member
public Circle(){ radius = 1; }
public Circle(double newRadius){ radius = newRadius; }
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * Math.PI * radius;
}
void setRadius(double newRadius) { radius = newRadius; }
}

public static void main(String[] args) {


Circle c = new Circle(9.0);
c.radius = 7.0; //Not allowed, ‘radius’ has private access
System.out.println(c.getArea());
}

24
Array of Objects

▪ Just like creating an array of primitive types, you can also


create arrays of objects.

▪ For example, the following statement declares and creates an


array of five Circle objects:
▪ Circle[] circleArray = new Circle[5];
25
Array of Objects (2)

▪ Mind you, the expression above just creates five spaces large
enough to store five Circle objects, it has not instantiated them.

▪ To instantiate the Circle object arrays, it has to be done via a loop


as follows:
▪ for(int i=0; i<5; i++)
circleArray[i] = new Circle(); //instantiate CircleArray[i]

26
Example 2

▪ Given the same Circle class in example 1, do the following


tasks:
▪ Create five members of the object using an array,
▪ Instantiate the object arrays by allowing the user to supply the radius
value of each array element,
▪ Print the perimeter and the area of each Circle object, a line for each
object.
27
public static void main(String[] args) {
Circle[] circleArray = new Circle[5];
for(int i=0; i<5; i++){
Scanner in = new Scanner(System.in);
System.out.printf("Enter the radius of circle %d: ", i + 1);
double rad = in.nextDouble();
circleArray[i] = new Circle(rad);
}

//printing the information of the Circle objects


System.out.println(".................");
System.out.printf("Perimeter\tArea");
System.out.println();
for(int i=0; i<5; i++){
System.out.printf("%.2f\t %.2f\n", circleArray[i].getPerimeter(),
circleArray[i].getArea());
}
System.out.println(".................");
}
28
Class Activity 1

▪ If we are to print the radius alongside the area of the circle


instead of the perimeter:
▪ Modify the class definition to allow this possibility without changing
the access modifier of the radius instance variable.
▪ Modify the Main program to reflect your changes

29
The This Reference

▪ The keyword this refers to the object itself. It can also be


used inside a constructor to invoke another constructor of the
same class.
▪ You can use the this keyword to reference the object’s
instance members.
▪ Although, it may be omitted, it can sometimes be useful when
a variable name conflicts with the data field of a class.
30
public class Circle {
private double radius;
public Circle(){
this(1); //calling the other version of the constructor below with radius parameter value of 1.0
}
public Circle(double radius){
this.radius = radius; //this.radius is not the same as the parameter radius
}
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * Math.PI * radius;
}
void setRadius(double newRadius) { radius = newRadius; }
}
Redefinition of the Circle class utilising the this keyword 31
Class Activity 2 / Exercise

▪ Implement a class called NBATeam that has the following


member variables:
▪ team_name, win_record (an integer), loss_record (an integer),
best_player_name and made_playoffs (a Boolean variable).
▪ Implement the following member functions:

32
Class Activity 2 (Cont’d)

1. A non-default constructor that initialises all the member variables.


The constructor should be able to check for violation of anyone of the
two possible errors:
a) if both the win and loss records are zero and
b) if the value of one of the records (win or loss) is negative.
▪ Print an error message if a violation is made, otherwise, initialise the
member variables.
33
Class Activity 2 (Cont’d)

2. Private member function that returns the win percentage of the team.
This can be calculated by the following formula:
𝑤𝑖𝑛_𝑟𝑒𝑐𝑜𝑟𝑑
𝑤𝑖𝑛_𝑝𝑐𝑡 =
𝑤𝑖𝑛_𝑟𝑒𝑐𝑜𝑟𝑑 + 𝑙𝑜𝑠𝑠_𝑟𝑒𝑐𝑜𝑟𝑑

34
Class Activity 2 (Cont’d)

3. A method that prints a message about the best player (it does not
return any value) based on the following rules, where player_name
represents the name of the team’s best player:
a) Print “Trade player_name” if the team did not make the playoffs and the
win percentage is less than 0.5
b) Print “Keep player_name” if the team made the playoffs and had at least a
win percentage of 0.60

35
Class Activity 2 (Cont’d)

c) Print “Find a co-star for player_name” if the team made the playoffs but
had a win percentage of at least 0.45 but below 0.5.
d) Otherwise print “Let’s run with player_name next season”.
▪ Do the following in the main program:
▪ Instantiate an object of the NBATeam class with the non-default
constructor
▪ Print an information about the best player
36
Extra Study

▪ Static Variables
▪ Study more examples
▪ Solve more exercises
▪ Inheritance and Polymorphism

37

You might also like