king fahd university of petroleum & minerals college of computer science & engineering...

339
King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction ICS102 - Introduction to computing

Post on 21-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Lecture 1 : Introduction

ICS102 - Introduction to computing

Page 2: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Components of a Personal Computer

Questions :

- what are the input devices ?

- what are the output devices ?

Page 3: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

A motherboard, provides the electrical connections by which the other components of the system communicate and hosts the central processing unit as well as other subsystems and devices.

Motherboard

Page 5: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

CPU (Central Processing Unit)

The Central Processing Unit (CPU) or processor is the portion of a computer system that carries out the instructions of a computer program and is the primary element carrying out the computer's functions.

In an addition operation, the arithmetic logic unit (ALU) will be connected to a set of inputs and a set of outputs. The inputs provide the numbers to be added, and the outputs will contain the final sum.

Example: (3 + 2) = 5

3

2

5

Page 6: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

CPU memory

Registers

Cache

Main memory (RAM):

Data has to be in main memory so that CPU can access it

Volatile: lost when program exits; computer shuts off

Hard Disk, CD, etc.

Persistent

This is where you keep the data for long-term storage

Memory

Memory refers to computer components, devices, and recording media that hold digital data used for computing for some interval of time.

There are mainly three types of memory :

Page 7: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Main Memory …

10021003

1004

1005

CellAddress

Memory is divided intoMany memory locations (cells)

Each memory cell has a numeric address, which uniquely identifies it

Each cell contains a datavalue, e.g. 22

Page 8: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Main Memory …

Page 9: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The word “Hello.” stored in 6 memory cells

Main Memory …

Page 10: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Memory units : Bits and Bytes

Bit -- most basic unit of memory

1 or 0, on or off

1 Byte = 8 bits

In a computer, data values are stored as a sequence of bits

2

7

1004

1005

00000010

00000111

1004

1005

Page 11: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Program / CPU / Memory Interaction

Example: Input read a number from keyboard Add 1 to it Output it on screen

KeyboardRAM

11 CPU

RAM

2 Monitor1 2 2

Page 12: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

What is programming?

Page 13: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

What is a program?

A (software) program is a list of instructions intended to a computer

The list must be ordered correctly

A program has inputs and outputs

Each instruction tells the computer to do something (an action, a calculation, a comparison)

Page 14: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Program Execution

A program tells the CPU how to manipulate and/or move information

Programming is about processing information

Take some input, manipulate it in some way, and produce a particular output

ManipulationInputs Outputs

Program

Page 15: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example 1 : Recipe for Scrambled Eggs

Ingredients (Inputs) : two eggs, tablespoon of oil, salt

Instructions (program):

Add oil to pan

Heat pan on stove

Crack eggs into pan

Add salt

Mix until light and flakey

Output: scrambled eggs

Page 16: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example 2 : Currency Exchange

Input: Amount Source Currency Desired Currency

Instructions Look up in table current exchange rate for the selected

currencies Calculate result as amount * exchange rate

• Output: result

Task : convert an amount of money in some currency (e.g. US Dollars) to another one (e.g. Saudi Riyals).

Page 17: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Programming language

A programming language is the language used to write programs

A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements

A programming language has a syntax and semantics

There are several types of languages (functional, Object-Oriented, etc.)

In this course we focus on Java programming language.

Page 18: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Java

• Java is a programming language originally developed by James Gosling at Sun Microsystems

• It was first released in 1995.

• The language derives much of its syntax from C and C++.

• But has a simpler object model and fewer low-level facilities than C and C++.

Page 19: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Why Java ?

Currently, Java is the most popular language in the world !

Page 20: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Why Java ?

1. Simple

• Get started quickly

2. Concise

• Write less code

3. Object-oriented

• Better quality code

4. Portable

• Architecture neutral (write once run anywhere)

5. Secure

• More appropriate for Internet

Page 21: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Portability of Java

Classical model:

Java model:

Page 22: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Portability of Java

Write once, run anywhere: Because applications written in the Java programming language are compiled into machine-independent bytecodes, they run consistently on any Java platform.

Page 23: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

A Java Program

A Java program consists of one or more classes

A Java class consists of one or more methods

A Java method consists of one or more statements

A Java Program

Javaclasses

JavaMethods

Page 24: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

A Java Program

A Java program resides in one or more files.

The file name of a Java program has extension .java.

One of the classes of a Java program is called the driver class.

The name of the driver class must be the same as the name of its Java file. (Java is case sensitive. So EX1 is different from ex1.)

The diver class must contain a method called main. The execution of Java program starts from the main method of the driver class.

Page 25: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Page 26: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Class nameMain method

Instruction

Class body

Page 27: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Also notice:

Curly braces } {

Page 28: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Also notice:

Parentheses ( )

Curly braces } {

Page 29: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Also notice:

Parentheses ( )

Curly braces } { Square brackets] [

Page 30: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Also notice:

A pair of braces } { define a block

Page 31: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Compiling and running a program

Type in your program Save the program

Store all your files in one directory for now Give the program the same name as the class

Compile the program this produces a .class file Translates the program into something the computer can

understand and execute (Java bytecode) Run the program Observe the result and adjust the program if necessary

Page 32: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Edit

Text Editor

Public class/*

Adventure.java

Public class Adven/* This program is an Arit*/

public static void main /* Program statements g System.out.print(“Wel }}

Page 33: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Compile - With Errors

Adventure.java

Public class Adven/* This program is an Arit*/

public static void main /* Program statements g System.print(“Welcome }}

Compiler

Errors and Warnings-------------------Error : The method print(String) is undefined forType System

Page 34: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Compile - Success

Adventure.java

Public class Adven/* This program is an Arit*/

public static void main /* Program statements g System.out.print(“Wel }}

Compiler

Adventure.class

00101101000101110110110100010111011101010001011101110101101000101110111010110100010111011101011010001011101110101101000101110111000101110111010110100010111011100101110111010110100010111011100101110111010110100010111011100101110111010110100010111011100101110111010110100010111011100101110

Page 35: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Run Program

Welcome to the ArithmThe date is Monday SepWhat is your name?FredWell Fred, after a dayThe cube appears to beYou find a Green door,The door closes behindThere is a feel of mat

Adventure

Fred

1

Page 36: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

End

Page 37: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 1 : Expressions and Assignment

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 38: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 38

Outline

Declaration Statements Primitive Data Types Identifiers Assignment Statements Arithmetic Operators and Expressions Precedence Rules Round-Off Errors in Floating-Point Numbers Integer and Floating-Point Division The % Operator Type Casting Increment and Decrement Operators

Page 39: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 39

Variable

In mathematics:

x + y = 17

In Computer Science: a variable is an identifier (usually a letter, word, or phrase) that is linked to a value stored in the computer's memory

x = 5;

variable

variable

variable

Page 40: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Variable Declaration

Every variable in a Java program must be declared before it is used

int numberOfBeans;numberOfBeans = 10;

A variable declaration tells the compiler what kind of data (type) will be stored in the variable

Basic types in Java are called primitive types

Page 41: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 41

- Primitive Data Types

Page 42: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 42

Names of variables (Identifiers)

int variable = 3;

The name of a variable must not start with a digit, and all the characters must be letters, digits, or the underscore symbol

Java is a case-sensitive language: Rate, rate, and RATE are the names of three different variables

It is not allowed to use reserved words as variable names:

public class void static

Page 43: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 44

Assignment Statements

In Java, the assignment statement is used to change the value of a variable

An assignment statement consists of a variable on the left side of the operator, and an expression on the right side of the operator

Variable = Expression;

Example

temperature = 98.6; count = numberOfBeans;

Page 44: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 45

Assignment Statements With Primitive Types

When an assignment statement is executed, the expression is first evaluated, and then the variable on the left-hand side of the equal sign is set equal to the value of the expression

distance = rate * time;

Note that a variable can occur on both sides of the assignment operator

count = count + 2;

The assignment operator is automatically executed from right-to-left, so assignment statements can be chained

number2 = number1 = 3;

Page 45: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 46

Initialize Variables …

A variable that has been declared but that has not yet been given a value by some means is said to be uninitialized

In certain cases an uninitialized variable is given a default value

It is best not to rely on this and always initialize your variables

int initialCount = 50; int finalCount;

What is the value of initialCount?

What is the value of finalCount?

Page 46: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 47

Shorthand Assignment Statements …

e.g. variable += 3;

Shorthand assignment notation combines the assignment operator (=) and an arithmetic operator

The general form is

Variable Op = Expression

Example: Equivalent To:

count += 2; count = count + 2;

sum -= discount; sum = sum – discount;

bonus *= 2; bonus = bonus * 2;

time /= rushFactor; time = time / rushFactor;

change %= 100; change = change % 100;

amount *= count1 + count2; amount = amount * (count1 + count2);

Page 47: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 48

Arithmetic Operators and Expressions

These are : + (addition), - (subtraction), * (multiplication), / (division), and % (modulo, remainder)

If an arithmetic operator is combined with int operands, then the resulting type is int

If an arithmetic operator is combined with one or two double operands, then the resulting type is double

If different types are combined in an expression, then the resulting type is the right-most type on the following list that is found within the expression

byteshortintlongfloatdoubleChar

Page 48: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 49

Assignment Compatibility

Is this legal ?

int x = 2.99;

And this ?

double variable = 2;

Page 49: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 50

More generally, a value of any type in the following list can be assigned to a variable of any type that appears to the right of itbyteshortintlongfloatdouble

Note that as your move down the list from left to right, the range of allowed values for the types becomes larger

int x = 5.8; errordouble y = 6; okshort i = 14.3; errorfloat s = 9.2; ok

Assignment Compatibility

For these, you need type cast. next

slide

Page 50: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 51

Type Casting

A type cast takes a value of one type and produces a value of another type with an "equivalent" value

int x = (int) 2.9;

When type casting from a floating-point to an integer type, the number is truncated, not rounded:

(int) 2.9 evaluates to 2, not 3

Page 51: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 52

Integer and Floating-Point Division

When one or both operands are a floating-point type, division results in a floating-point type

15.0/2 evaluates to 7.5

When both operands are integer types, division results in an integer type

Any fractional part is discarded

The number is not rounded

15/2 evaluates to 7

Be careful to make at least one of the operands a floating-point type if the fractional portion is needed

Page 52: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023

Precedence Rules

e.g. int x = y = -2 + 5 * 7 – 7 / 2 % 5;

Low precedence

High precedence

First: The unray operators: +, -, ++, --, and !

Second: The binary arithmetic operators: *, /. And %

Third: The binary arithmetic operators: + and -

If some or all of the parentheses in an expression are omitted, Java will follow precedence rules to determine, in effect, where to place them.

Page 53: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 54

Precedence Rules

e.g. int x = y = -2 + 5 * 7 – 7 / 2 % 5;This will be evaluated as..

int x = (y = ((-2 + (5 * 7)) – ((7 / 2) % 5)));

Low precedence

High precedence

First: The unray operators: +, -, ++, --, and !

Second: The binary arithmetic operators: *, /. And %

Third: The binary arithmetic operators: + and -

35 3

33 3

30

If some or all of the parentheses in an expression are omitted, Java will follow precedence rules to determine, in effect, where to place them.

Page 54: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 55

The % (modulo) Operator

The % operator is used with operands of type int to recover the information lost after performing integer division

15/2 evaluates to the quotient 7

15%2 evaluates to the remainder 1

The % operator can be used to count by 2's, 3's, or any other number

To count by twos, perform the operation number % 2, and when the result is 0, number is even

Page 55: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 56

Increment and Decrement Operators

The increment operator (++) adds one to the value of a variable

If n is equal to 2, then n++ or ++n will change the value of n to 3

The decrement operator (--) subtracts one from the value of a variable

If n is equal to 4, then n-- or --n will change the value of n to 3

Page 56: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Expressions & Assignment 57

Increment and Decrement Operators

When either operator precedes its variable, and is part of an expression, then the expression is evaluated using the changed value of the variable

If n is equal to 2, then 2*(++n) evaluates to 6

When either operator follows its variable, and is part of an expression, then the expression is evaluated using the original value of the variable, and only then is the variable value changed

If n is equal to 2, then 2*(n++) evaluates to 4

Page 57: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 1.2 of the textbook

Page 58: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 3 : Math

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 59: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

What is a library?

Most programming languages come with a library.

A library is a collection of classes for common system services such as : math operations, input/output routines, etc.

The Java library is called : API (Application Programming Interface).

Java API is organized into packages.

Today we will see a class of this library : Math.

Page 60: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The Math Class

The Math class provides a number of standard mathematical methods

The Math class has two predefined constants, E (e, the base of the natural logarithm system) and PI (, 3.1415 . . .)

area = Math.PI * radius * radius;

Page 61: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Some Methods in the Class Math …

Page 62: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Some Methods in the Class Math …

Page 63: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Some Methods in the Class Math …

Page 64: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Some Methods in the Class Math …

Page 65: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Some Methods in the Class Math

Page 66: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Page 67: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Page 68: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 4 : String Class

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 69: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String 70

Outline

The String Class

Explicit String Objects

String variables are References

String Methods

Escape Sequences

Page 70: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String

71

The String Class

There is no primitive type for strings in Java

The class (type) String is a predefined class in Java that is used to store and process strings

A String object is a sequence of characters that is treated as a single value.

When any “ ” (quote) appears, a String object is created automatically.

A variable of type String can be given the value of a String object

Page 71: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Explicit String Objects

A declaration and object creation are needed for instances of the String class. For example,

We normally use shorthand notation(only for Strings):

String name1;

name1 = new String("Salam");

String name1;

name1 = "Salam";

These two statements are equivalent.

These two statements are equivalent.

April 19, 2023 72ICS102: The class String

Page 72: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

String variables are References…

Code

State of Memory

String word1, word2;

word1 = new String("Java");

word2 = word1;

AABoth word1 and word2 are allocated memory (to store references), but the objects themselves are not yet created, so they both contain null.

Both word1 and word2 are allocated memory (to store references), but the objects themselves are not yet created, so they both contain null.

word1

word2

After is executedAA

Page 73: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

word1

word2

String variables are References…

April 19, 2023 ICS102: The class String 74

Code String word1, word2;

word1 = new String("Java");

word2 = word1;

BBOne String object is created and assigned to word1, so word1 contains the address of this object.

One String object is created and assigned to word1, so word1 contains the address of this object.

word1

word2

After is executedBB

String

Java

State of Memory

Page 74: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

word1

word2

String

Java

String variables are References.

April 19, 2023 ICS102: The class String 75

Code String word1, word2;

word1 = new String("Java");

word2 = word1; CC

Content of word1, which is an address, is assigned to word2, making word2 refer to the same object.

Content of word1, which is an address, is assigned to word2, making word2 refer to the same object.

word1

word2

String

Java

After is executedCC

State of Memory

Page 75: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String 76

String Methods

String Concatenation

String Length

String Starting Position

Other Useful String Operators

Page 76: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String 77

String Concatenation

Concatenation: Using the + operator on two (or more) strings in order to connect them to form one longer string

A new String object is created operands are not affected. When a string is combined with almost any other type of

item, the result is a string

String greeting = "Hello ";String course = "ICS102";System.out.println(greeting + course); Hello ICS102

int x = 6, y = 10; String s = ".Hi.";System.out.println(s + x);System.out.println(x + y + s); System.out.println(s + (x + y));System.out.println(s + x + y);

.Hi.616.Hi. .Hi.16.Hi.610

Page 77: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

String Length

We determine the number of characters in a String with the length method.

String name = "Espresso!";String str2 = "";String str3;

Error because no object is created for str3, so it is a null.

Error because no object is created for str3, so it is a null.

str2.length();

str3.length();

9

0

Error!

Page 78: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Individual characters in a String can be accessed with the charAt method.

Position of a character or String can be found with indexOf method.

String Starting Position

text

This variable refers to the whole string.

This variable refers to the whole string.

text.charAt(8)

The method returns the character at position # 8.

The method returns the character at position # 8.

String text = "Java is fun.";

text.indexOf("is")

The method returns the position of the string “is”.

The method returns the position of the string “is”.

Page 79: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Other Useful String Operators

Method Meaning

equals Checks if two strings are equal. (Use equalsIgnoreCase for case insensitive) str1.equals( str2 )

compareTo Compares the two strings. str1.compareTo( str2 )

substringExtracts the a substring from a string.

str1.substring( 1, 4 ) str1.substring( 5 )

trim Removes the leading and trailing spaces. str1.trim( )

toUpperCaseConverts a string to all caps string. (Use toLowerCase for all small)

str1.toUpperCase( )

Page 80: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String 81

Escape Sequences …

A backslash (\) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character

The character following the backslash does not have its usual meaning

Although it is formed using two symbols, it is regarded as a single character

Page 81: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The class String 82

Escape Sequences

Page 82: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 1.3 (pages 65-77)

Page 83: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

For each of these expressions determine its result

String text = "Java Programming";

text.substring(0, 4) text.length( ) text.substring(8, 12) text.substring(0, 1) + text.substring(7, 9) text.substring(5, 6) + text.substring(text.length() – 3,

text.length())

Page 84: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a program that initializes a String object to “Hello the World”, prints its length, then erases the word “the” from that String.

Page 85: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 5 : Screen Output and Console Input

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 86: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

System.out.println

To write of the screen:

System.out.println(“Hello World");

It is possible to print more than one item:

A plus sign is used to connect more than one item

System.out.println("The answer is " + 42);

Every invocation of println generates a new line after it finishes

System.out.println(“Hello World”);System.out.println(“Hello World”);

Package name

Class name

Method name

The item to be printed on the screen

Hello World

Hello World

Page 87: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

println Versus print

To stay on the same line, use print

System.out.print(“Hello World ”);System.out.print(“Hello World ”);

The print method is like println, except that it does not generate a new line

With println, the next output goes on a new line

With print, the next output goes on the same line

Hello World Hello World

Page 88: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Console Input

What if we want to let the user choose the values he wants to use ?

We can prompt the user by console (keyboard) input

Page 89: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Console Input

Import instruction

Create Scanner object

Read a first integer and assign it to variable a

Read a second integer and assign it to variable

b

Page 90: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Console Input

Page 91: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Details ..

Java includes a class for doing simple keyboard input named the Scanner class

In order to use the Scanner class, a program must include the following line near the start of the file:

import java.util.Scanner

This statement tells Java to

Make the Scanner class available to the program

Find the Scanner class in a library of classes (i.e., Java package) named java.util

Page 92: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The following line creates an object of the class Scanner and names the object keyboard :

Scanner keyboard = new Scanner(System.in); Although a name like keyboard is often used, a Scanner

object can be given any name For example, in the following code the Scanner object is

named scannerObject

Scanner scannerObject = new Scanner(System.in); Once a Scanner object has been created, a program can

then use that object to perform keyboard input using methods of the Scanner class

Details ..

Page 93: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The method nextInt reads one int value typed in at the keyboard and assigns it to a variable:

int numberOfPods = keyboard.nextInt();

The method nextDouble reads one double value typed in at the keyboard and assigns it to a variable:

double d1 = keyboard.nextDouble();

Multiple inputs must be separated by whitespace and read by multiple invocations of the appropriate method

Whitespace is any string of characters, such as blank spaces, tabs, and line breaks that print out as white space on paper

Details ..

Page 94: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The method next reads one string of non-whitespace characters delimited by whitespace characters such as blanks or the beginning or end of a line

Given the code

String word1 = keyboard.next();String word2 = keyboard.next();

and the input line

jelly beans

The value of word1 would be jelly, and the value of word2 would be beans

Details ..

Page 95: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The method nextLine reads an entire line of keyboard input The code,

String line = keyboard.nextLine();

reads in an entire line and places the string that is read into the variable line

The end of an input line is indicated by the escape sequence '\n‘

This is the character input when the Enter key is pressed

On the screen it is indicated by the ending of one line and the beginning of the next line

When nextLine reads a line of text, it reads the '\n' character, so the next reading of input begins on the next line

However, the '\n' does not become part of the string value returned (e.g., the string named by the variable line above does not end with the '\n' character)

Details ..

Page 96: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Dealing with the Line Terminator, '\n‘ …

The method nextLine of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off

This can cause problems when combining it with different methods for reading from the keyboard such as nextInt

Given the code,

Scanner keyboard = new Scanner(System.in);int n = keyboard.nextInt();String s1 = keyboard.nextLine();String s2 = keyboard.nextLine();

and the input,

2Heads are better than1 head.

what are the values of n, s1, and s2?

Page 97: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Dealing with the Line Terminator, '\n'

Given the code and input on the previous slide

n will be equal to 2,s1 will be equal to "", ands2 will be equal to "heads are better than“

If the following results were desired instead

n equal to 2, s1 equal to "heads are better than", ands2 equal to "1 head“

then an extra invocation of nextLine would be needed to get rid of the end of line character ('\n')

Page 98: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Dealing with the Line Terminator, '\n'

Given the codeScanner keyboard = new Scanner(System.in);int n = keyboard.nextInt();keyboard.nextLine();String s1 = keyboard.nextLine();String s2 = keyboard.nextLine();

and the input,

2Heads are better than1 head.

We get the desired result:

n equal to 2, s1 equal to "heads are better than", ands2 equal to "1 head“

Page 99: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Programming Tip …

Prompt for Input

A program should always prompt the user when he or she needs to input some data:

System.out.println( "Enter the number of pods followed by");

System.out.println("the number of peas in a pod:");

Page 100: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read chapter 2 (pages 90-118)

Page 101: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Methods in the Class Scanner …

Page 102: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Methods in the Class Scanner ….

Page 103: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Methods in the Class Scanner

Page 104: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 6 : File Input Output

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 105: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Outline

Text Files

Stream

Reading from a Text File using Scanner

Writing to a File

IOException

Pitfalls

Page 106: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Text Files

Files that are designed to be read by human beings, and that can be read or written with an editor are called text files

Text files can also be called ASCII files because the data they contain uses an ASCII encoding scheme

An advantage of text files is that they are usually the same on all computers, so that they can move from one computer to another

Page 107: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ASCII Encoding

Page 108: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Streams

A stream is an object that enables the flow of data between a program and some I/O device or file

If the data flows into a program, then the stream is called an input stream

If the data flows out of a program, then the stream is called an output stream

file

program

Output stream

Input stream

Page 109: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Streams

Input streams can flow from the keyboard or from a file

System.in is an input stream that connects to the keyboard

Scanner keyboard = new Scanner(System.in);

Output streams can flow to a screen or to a file

System.out is an output stream that connects to the screen

System.out.println("Output stream");

Page 110: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Reading From a Text File Using Scanner

The class Scanner can be used for reading from the keyboard as well as reading from a text file

Simply replace the argument System.in (to the Scanner constructor) with a suitable stream that is connected to the text file

Scanner StreamObject =new Scanner(new FileInputStream(FileName));

Methods of the Scanner class for reading input behave the same whether reading from the keyboard or reading from a text file

For example, the nextInt and nextLine methods

Page 111: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Reading Input from a Text File Using Scanner

Page 112: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Reading Input from a Text File Using Scanner

Page 113: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Reading Input from a Text File Using Scanner

Page 114: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Reading Input from a Text File Using Scanner

Page 115: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Writing to a Text File

The class PrintWriter is a stream class that can be used to write to a text file

An object of the class PrintWriter has the methods print and println

These are similar to the System.out methods of the same names, but are used for text file output, not screen output

Page 116: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Writing to a Text File

All the file I/O classes that follow are in the package java.io, so a program that uses PrintWriter will start with a set of import statements:

import java.io.PrintWriter;import java.io.FileOutputStream;import java.io.FileNotFoundException;

The class PrintWriter has no constructor that takes a file name as its argument

It uses another class, FileOutputStream, to convert a file name to an object that can be used as the argument to its (the PrintWriter) constructor

Page 117: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Writing to a Text File

A stream of the class PrintWriter is created and connected to a text file for writing as follows:

PrintWriter outputStreamName;

outputStreamName = new PrintWriter(new

FileOutputStream(FileName));

The class FileOutputStream takes a string representing the file name as its argument

The class PrintWriter takes the anonymous FileOutputStream object as its argument

Page 118: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Writing to a Text File

This produces an object of the class PrintWriter that is connected to the file FileName

The process of connecting a stream to a file is called opening the file

If the file already exists, then doing this causes the old contents to be lost

If the file does not exist, then a new, empty file named FileName is created

After doing this, the methods print and println can be used to write to the file

Page 119: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Writing to a Text File

Page 120: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Path Names

When a file name is not in the same directory, the path name must be given

First way:

Scanner in = new Scanner(new FileInputStream(“c:/user/data.txt"));

Second way:

Scanner in = new Scanner(new FileInputStream(“c:\\user\\data.txt"));

Page 121: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read chapter 10 from 602 to 615

Page 122: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 7 : Selection Structures

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 123: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 124

Outline

Block statement

Branching Statements

Simple if statement

if-else statement

if-else-elseif statement

switch statement

Nested if statements

Page 124: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Introduction to selection structures

Write a program that accepts an integer value from the user and then:

prints “positive” if the integer is larger or equal to zero

Prints “negative” if the integer is less than zero

Page 125: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 126

Block Statement

A block statement consists of one or more Java statements enclosed in braces.

Example of a block statement:

{statement 1;statement 2; …statement n;

}

Blocks can be nested.

A block statement can be used anywhere that a single statement can be used.

Page 126: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 127

Branching Statement

A branching statement consists of one or more block statements

The execution of a block statement in a branching statement is controlled by a boolean expression which we call a condition.

There are mainly the following four types of branching statement.

Simple if

If-else

If-elseif-else

switch

Page 127: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 128

Simple if Statement …

Simple if statement has the following structure:

if ( <boolean_expression> ) {

<then_block>}

The boolean_expression must be enclosed in parentheses If the boolean_expression is true, then the then_block is

executed. Otherwise it will NOT execute.

if ( testScore >= 95 ) {

System.out.println("You are a good student");

}Then BlockThen Block

Boolean ExpressionBoolean Expression

Page 128: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 129

-- Simple if Statement …

testScore >= 95?

testScore >= 95?

falseSystem.out.println("You are a good student");

System.out.println("You are a good student");

trueControl Flow of if:

Page 129: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 130

… -- Simple if Statement

Example: Design and write a Java program prints the absolute value of a number.

import java.util.Scanner;class absolute {

public static void main(String [] args) { Scanner kb = new Scanner(System.in); System.out.print(“Enter a number: “); double x = kb.nextDouble(); double y = x; if( y < 0)

{ y = -y; } System.out.print(“The absolute value of “ + x + “ is “ +

y); }}

Page 130: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 131

-- if-else Statement …

An if-else statement chooses between two alternative statements based on the value of a Boolean expression

If the boolean_expression is true, then the then_block is executed, otherwise the else_block is executed.

if (<boolean_expression>) { <then_block>} else { <else_block>}

if (testScore < 50) {

System.out.println("You did not pass");

} else {

System.out.println("You did pass");

}

Then BlockThen Block

Else BlockElse Block

Boolean ExpressionBoolean Expression

Page 131: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 132

System.out.println("You did pass");

System.out.println("You did pass");

falsetestScore < 50 ?testScore < 50 ?

System.out.println("You did not pass");

System.out.println("You did not pass");

true

-- if-else Statement …

Page 132: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 133

Compound Statements

You have to use braces if the <then> or <else> block has multiple statements.

if only one statement is there braces are optional but it is advisable to always use them to enhance readability

if (testScore < 70)

{

System.out.println("You did not pass");

System.out.println("Try harder next time");

}

else

{

System.out.println("You did pass");

System.out.println("Keep up the good work");

}

Then BlockThen Block

Else BlockElse Block

Page 133: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 134

… -- if-else Statement

Design and write a Java program which prints the difference of two numbers.

Scanner kb = new Scanner(System.in); System.out.println(“Enter the value of the first number: “); double first = kb.nextDouble(); System.out.println(“Enter the value of the second number: “); double second = kb.nextDouble(); if ( first > second) { double diff = first – second; System.out.println(diff); } else { double diff = second – first; System.out.println(diff); }

Page 134: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 135

-- if-elseif-else Statement …

The multiway if-else statement is simply a normal if-else statement that nests another if-else statement at every else branch

It is indented differently from other nested statements

All of the Boolean_Expressions are aligned with one another, and their corresponding actions are also aligned with one another

The Boolean_Expressions are evaluated in order until one that evaluates to true is found

The final else is optional

Page 135: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 137

if - else- if

if (score >= 85) {

System.out.println(”Grade is A");

} else if (score >= 75) {

System.out.println(”Grade is B");

} else if (score >= 65) {

System.out.println(”Grade is C");

} else if (score >= 50) {

System.out.println(”Grade is D");

} else {

System.out.println(”Grade is N");

}

Test Score Grade85 score A75 score 85 B65 score 75 C50 score 65 D score 50 N

Page 136: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 138

- The switch Statement …

The switch statement is the only other kind of Java statement that implements multiway branching

When a switch statement is evaluated, one of a number of different branches is executed

The choice of which branch to execute is determined by a controlling expression enclosed in parentheses after the keyword switch

The controlling expression must evaluate to a char, int, short, or byte

Page 137: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 139

Syntax for the switch Statement

switch ( fanSpeed ) {

case 1:

System.out.println("That's low");

break;

case 2:

System.out.println("That's medium");

break;

case 3:

System.out.println("That's high");

break;

}

switch ( <arithmetic expression> ) {

<case label 1> : <case body 1>

<case label n> : <case body n>

}

Case Body

Case Body

Arithmetic ExpressionArithmetic Expression

Case Label

Case Label

Page 138: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 140

switch With break Statements

switch ( N ) {

case 1: x = 10;

break;

case 2: x = 20;

break;

case 3: x = 30;

break;

}

x = 10;x = 10;

false

trueN == 1 ?

N == 1 ?

x = 20;x = 20;

x = 30;x = 30;

N == 2 ?

N == 2 ?

N == 3 ?

N == 3 ?

false

false

true

true

break;break;

break;break;

break;break;

Page 139: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 141

The switch Statement with default

switch ( binaryDigit ) {

case 0:

System.out.println("zero"); break;

case 1:

System.out.println("one"); break;

default:

System.out.println("That's not a binary digit"); break;

}

switch ( <arithmetic expression> ) {<case label 1> : <case body 1>…<case label n> : <case body n>default: <default body>

}

Page 140: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 142

switch With No break Statements

switch ( N ) {

case 1: x = 10;

case 2: x = 20;

case 3: x = 30;

}

x = 10;x = 10;

false

trueN == 1 ?

N == 1 ?

x = 20;x = 20;

x = 30;x = 30;

N == 2 ?

N == 2 ?

N == 3 ?

N == 3 ?

false

false

true

true

Page 141: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 143

… -- The switch Statement

double y = 30;double z = 20;Scanner kb = new Scanner(System.in);System.out.println("1. add ");System.out.println("2. Subtract ");System.out.println("3. Multiply ");System.out.println("Enter a value: between 1 and 3 ");int x = kb.nextInt();switch (x) {

case 1: System.out.println(z + y);break;

case 2: System.out.println(z - y); break;

case 3: System.out.println(z * y);break;

default: System.out.println("Wrong Choice.");break;

}

Page 142: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 144

- Nested if Statements …

One of the block statements of a branching statement can be another if statement.

The inner if statement is executed when the enclosing block statement is executed

If statements can be nested to many levels

If(<boolean_expresion_1>){ Statement_1; <block_statement_2>; Statement_3;}

if(<boolean_expression_2>) { Statement_2A; Statement_2B: }

Statement_2A and 2B are only executed if boolean_expresions 1 and2 are true.

Page 143: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 145

- Nested if Statements …

if (testScore >= 50) {

if (studentAge < 10) {

System.out.println("You did a great job");

} else {

System.out.println("You did pass");

}

} else { //test score < 50

System.out.println("You did not pass");

}

Nested ifNested if

Page 144: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 146

- Nested if Statements …

System.out.println("You did not pass");

System.out.println("You did not pass");

falseinner if

System.out.println("You did pass");

System.out.println("You did pass");

false

testScore >= 50 ?testScore >= 50 ?true

studentAge < 10 ?

studentAge < 10 ?

System.out.println("You did a great

job");

System.out.println("You did a great

job");

true

Page 145: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 147

Nested simple-if

if (x < y) {

if (x < z)

System.out.println("Hello");

} else {

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

}

if (x < y) {

if (x < z) {

System.out.println("Hello");

}

} else {

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

}

means

Page 146: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course Chapter 6 - 148

Nested if-else

if (x < y)

if (x < z)

System.out.println("Hello");

else

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

if (x < y) {

if (x < z) {

System.out.println("Hello");

} else {

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

}

}

really means

Page 147: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 3.1 (pages 128-140)

Page 148: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a Java program that reads an integer using Scanner then tests if it is odd or even. The format of the input and output should be as follows: Please enter a number: 1010 is even.

Write a program that reads three integers and prints them in increasing order. Example:Please enter three integers: 9, 5, 21The integers in increasing order are: 5 9 21

Page 149: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a program that reads an integer between 0 and 10 and then prints the word corresponding to the number. Example:Please enter a number between 0 and 10: 7You entered: seven

Page 150: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 8 : Boolean Expressions

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 151: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 153

Outline

Introduction Java Comparison Operators Evaluating Boolean Expressions Pitfall: Using == with Strings Lexicographic and Alphabetical Order Building Boolean Expressions Truth Tables Short-Circuit and Complete Evaluation Precedence and Associativity Rules Evaluating Expressions Rules for Evaluating Expressions

Page 152: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 154

- Introduction

A Boolean expression is an expression that is either true or false

The simplest Boolean expressions compare the value of two expressions

time < limityourScore == myScore

Note that Java uses two equal signs (==) to perform equality testing: A single equal sign (=) is used only for assignment

Page 153: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 155

- Java Comparison Operators

Page 154: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 156

- Evaluating Boolean Expressions

Even though Boolean expressions are used to control branch and loop statements, Boolean expressions can exist independently as well

A Boolean variable can be given the value of a Boolean expression by using an assignment statement

A Boolean expression can be evaluated in the same way that an arithmetic expression is evaluated

The only difference is that arithmetic expressions produce a number as a result, while Boolean expressions produce either true or false as their result

boolean madeIt = (time < limit) && (limit < max);

Page 155: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 157

- Pitfall: Using == with Strings

The equality comparison operator (==) can correctly test two values of a primitive type

However, when applied to two objects such as objects of the String class, == tests to see if they are stored in the same memory location, not whether or not they have the same value

In order to test two strings to see if they have equal values, use the method equals, or equalsIgnoreCase

string1.equals(string2)string1.equalsIgnoreCase(string2) Confusion between =, ==, and

equals method is one of the

most frequent programming

errors

Page 156: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 158

- Lexicographic and Alphabetical Order

Lexicographic ordering is the same as ASCII ordering, and includes letters, numbers, and other characters

All uppercase letters are in alphabetic order, and all lowercase letters are in alphabetic order, but all uppercase letters come before lowercase letters

If s1 and s2 are two variables of type String that have been given String values, then s1.compareTo(s2) returns:

A negative number if s1 is before s2 in lexicographic ordering zero if the two strings are equal. A positive number if s2 comes before s1

When performing an alphabetic comparison of strings (rather than a lexicographic comparison) that consist of a mix of lowercase and uppercase letters, use the compareToIgnoreCase method instead

Page 157: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 159

- Building Boolean Expressions

When two Boolean expressions are combined using the "and" (&&) operator, the entire expression is true provided both expressions are true

Otherwise the expression is false

When two Boolean expressions are combined using the "or" (||) operator, the entire expression is true as long as one of the expressions is true

The expression is false only if both expressions are false

Any Boolean expression can be negated using the ! Operator

Place the expression in parentheses and place the ! operator in front of it

Unlike mathematical notation, strings of inequalities must be joined by &&

Use (min < result) && (result < max) rather than min < result < max

Page 158: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 160

- Truth Tables

Page 159: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 161

- Short-Circuit and Complete Evaluation

Consider x > y || x > z

The expression is evaluated left to right. If x > y is true, then there’s no need to evaluate x > z because the whole expression will be true whether x > z is true or not.

This also happens when we use && operator and the first expression is false.

To stop the evaluation once the result of the whole expression is known is called short-circuit evaluation or lazy evaluation

Page 160: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 162

- Short-Circuit and Complete Evaluation

What would happen if the short-circuit evaluation is not done for the following expression?

kids != 0 && toys/kids >= 2

There are times when using short-circuit evaluation can prevent a runtime error

Sometimes it is preferable to always evaluate both expressions, i.e., request complete evaluation

In this case, use the & and | operators instead of && and ||

Page 161: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 163

- Precedence and Associativity Rules …

Boolean and arithmetic expressions need not be fully parenthesized

If some or all of the parentheses are omitted, Java will follow precedence and associativity rules (summarized in the following table) to determine the order of operations

If one operator occurs higher in the table than another, it has higher precedence, and is grouped with its operands before the operator of lower precedence

If two operators have the same precedence, then associativity rules determine which is grouped first

Page 162: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: The course 164

Precedence and Associativity Rules

Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious

Page 163: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

165

The end

Important to do at home :

- read chapter 3 from 141 to 153

Page 164: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 9 : While and Do-While loops

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 165: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 167

Outline

Introduction

while Loop

do-while Loop

Page 166: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 168

- Introduction

Loops in Java are similar to those in other high-level languages

Java has three types of loop statements: The while The do-while The for

The code that is repeated in a loop is called the body of the loop

Each repetition of the loop body is called an iteration of the loop

Page 167: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 169

- while loop

A while statement is used to repeat a portion of code (i.e., the loop body) based on the evaluation of a Boolean expression

The Boolean expression is checked before the loop body is executed

When false, the loop body is not executed at all

Before the execution of each following iteration of the loop body, the Boolean expression is checked again

If true, the loop body is executed again

If false, the loop statement ends

The loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ })

Page 168: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 170

-- while Loop Syntax

while ( <boolean expression> )

<statement> //only one statement

OR

while ( <boolean expression> ) {

<statement> //many

}

while ( number <= 100 ) {

sum = sum + number;

number = number + 1;

}

Boolean ExpressionBoolean Expression

Statement(loop body)

Statement(loop body)

These statements are executed as long as number is less than or equal to 100.

These statements are executed as long as number is less than or equal to 100.

Page 169: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 171

-- while Loop Control flow

int sum = 0, number = 1int sum = 0, number = 1

number <= 100 ?number <= 100 ?

falsesum = sum + number;

number = number + 1;

sum = sum + number;

number = number + 1;

true

Page 170: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 172

-do-while Loop

A do-while statement is used to execute a portion of code (i.e., the loop body), and then repeat it based on the evaluation of a Boolean expression

The loop body is executed at least once The Boolean expression is checked after the loop body is executed

The Boolean expression is checked after each iteration of the loop body

If true, the loop body is executed again If false, the loop statement ends Don't forget to put a semicolon after the Boolean expression

Like the while statement, the loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ })

Page 171: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 173

-- do-while Loop Syntax

do {

sum += number;

number++;

} while (sum <= 1000000) ;

do {

<statement>

} while (<boolean expression>);

Boolean ExpressionBoolean Expression

Statement(loop body)

Statement(loop body)

These statements are executed as long as sum is less than or equal to 1,000,000.

These statements are executed as long as sum is less than or equal to 1,000,000.

Page 172: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 174

-- do-while Loop Control Flow

int sum = 0, number = 1int sum = 0, number = 1

sum += number;

number++;

sum += number;

number++;

sum <= 1000000 ?sum <= 1000000 ?true

false

Page 173: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 175

Examples

Page 174: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 176

Questions

1. Write a Java program which computes the sum of all the odd numbers between 0 and 100.

2. Write a Java program which reads 20 numbers using a scanner and computes their average.

3. Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the number of even numbers. Assume the input integers are all positive. Use a negative number as a sentinel.

Page 175: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 177

Solution using while loop

Page 176: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 178

Q1 Solution

int n =1;int sum = 0;while (n < 100) { sum += n; n = n + 2;}System.out.println(“The sum is “

+ sum);

Write a Java program which computes the sum of all the odd numbers between 0 and 100.

Page 177: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 179

Q2 Solution

Scanner kb = new Scanner(System.in);int cnt = 0;double x;double sum = 0;While (cnt < 20) { x = kb.nextDouble(); sum += x; cnt++;}System.out.println(“The Average is “ +

sum/cnt);

Write a Java program which reads 20 numbers using a scanner and computes their average.

Page 178: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 180

Q3 Solution

Scanner kb = new Scanner(System.in);int even_cnt = 0;int odd_cnt = 0;double x = kb.nextInt();while (x > 0) { if ( mod(x,2) == 0) even_cnt++; else odd_cnt++; x = kb.nextInt();}System.out.println(“Even numbers are = “ +

even_count);System.out.println(“Odd numbers are = “ +

odd_count);

Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel.

Page 179: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 181

Solution using do-while loop

Page 180: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 182

Q1 Solution

int n = 1;int sum = 0;do {

sum += n;n = n + 2;

} While ( n < 100)System.out.println(“The sum is “

+ sum);

Write a Java program which computes the sum of all the odd numbers between 0 and 100.

Page 181: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 183

Q2 Solution

Scanner kb = new Scanner(System.in);int cnt = 0;double x;double sum = 0;do { System.out.println(“Enter a number”); x = kb.nextDouble(); sum += x; cnt++;} while (cnt < 20);System.out.println(“The Average is “ +

sum/cnt);

Write a Java program which reads 20 numbers using a scanner and computes their average.

Page 182: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 184

Q3 Solution

Scanner kb = new Scanner(System.in);int even_cnt = 0;int odd_cnt = 0;double x = kb.nextInt();if (x > 0) { do { if ( mod(x,2) == 0) even_cnt++; else odd_cnt++; x = kb.nextInt();

} while ( x > 0)}System.out.println(“Even numbers are = “ +

even_count);System.out.println(“Odd numbers are = “ +

odd_count);

Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel.

Page 183: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 185

Additional Slides

Page 184: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while Chapter 7 - 186

while Loop Pitfall - 1

Infinite Loops Both loops will not terminate because the boolean expressions will never become false.

Infinite Loops Both loops will not terminate because the boolean expressions will never become false.int count = 1;

while ( count != 10 ) {

count = count + 2;

}

22

int product = 0;

while ( product < 500000 ) {

product = product * 5;

}

11

Page 185: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while Chapter 7 - 187

while Loop Pitfall - 2

Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory.

Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory.double count = 0.0;

while ( count <= 1.0 ) {

count = count + 1.0/3.0;

}

22

double count = 0.0;

while ( count != 1.0 ) {

count = count + 1.0/3.0;

}

11

Page 186: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while Chapter 7 - 188

while Loop Pitfall - 3

Goal: Execute the loop body 10 times.

count = 1;

while (count < 10) {

. . .

count++;

}

11

count = 0;

while (count <= 10) {

. . .

count++;

}

33

count = 1;

while (count <= 10) {

. . .

count++;

}

22

count = 0;

while (count < 10) {

. . .

count++;

}

44

11 33and exhibit off-by-one error.

Page 187: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while Chapter 7 - 189

Checklist for Repetition Control

1. Watch out for the off-by-one error (OBOE).

2. Make sure the loop body contains a statement that will eventually cause the loop to terminate.

3. Make sure the loop repeats exactly the correct number of times.

Page 188: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 3.3 (pages 160-166)

Page 189: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 10 : The for-loop and nested loops

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 190: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Outline

The for Statement Syntax Semantics of the for Statement Nested Loops continue, break, and exit Statements

Page 191: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- The for Statement Syntax

for (Initializing; Boolean_Expression; Update) Block

Note that the three control expressions are separated by two, not three, semicolons

Note that there is no semicolon after the closing parenthesis at the beginning of the loop

Page 192: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- The for Statement

The for statement is most commonly used to step through an integer variable in equal increments

It begins with the keyword for, followed by three expressions in parentheses that describe what to do with one or more controlling variables

The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration

The second expression determines when the loop should end, based on the evaluation of a Boolean expression before each iteration

The third expression tells how the control variable or variables are updated after each iteration of the loop body

Page 193: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example

Page 194: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Nested Loops

Loops can be nested, just like other Java structures When nested, the inner loop iterates from beginning to

end for each single iteration of the outer loop

for (Initializing; Boolean_Expression; Update) Block 1

Block 1 can contain other loop statements as follows

Block 1 for (Initializing; Boolean_Expression; Update)

Block 2

Page 195: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Nested Loops

Loops can be nested, just like other Java structures When nested, the inner loop iterates from beginning to

end for each single iteration of the outer loop

int rowNum, columnNum;for (rowNum = 1; rowNum <=3; rowNum++){ for (columnNum = 1; columnNum <=2; columnNum++) System.out.print(" row " + rowNum + " column " +

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

Page 196: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Continue, break, and exit Statements

Class test { public static void main( String [] args) { for (int i = 0; i < 10; i++) { statement 1;

statement 2;if( cond) continue;statement 3;statement 4;

} statement 5; statement 6; }}

Page 197: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Continue, break, and exit Statements

Class test { public static void main( String [] args) { for (int I = 0; I < 10; i++) { statement 1;

statement 2;if( cond) break;statement 3;statement 4;

} statement 5; statement 6; }}

Page 198: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Continue, break, and exit Statements

Class test { public static void main( String [] args) { for (int I = 0; I < 10; i++) { statement 1;

statement 2;if( cond) System.exit(0);statement 3;statement 4;

} statement 5; statement 6; }}

Page 199: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

For-loop examples

Page 200: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 202

Questions

1. Write a Java program which computes the sum of all the odd numbers between 0 and 100.

2. Write a Java program which reads 20 numbers using a scanner and computes their average.

3. Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the number of even numbers. Assume the input integers are all positive. Use a negative number as a sentinel.

Page 201: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 203

Q1 Solution

int sum = 0;for( int n = 1; n <= 100; n = n + 2) { sum += n;}System.out.println(“The sum is “ +

sum);

Write a Java program which computes the sum of all the odd numbers between 0 and 100.

Page 202: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 204

Q2 Solution

Scanner kb = new Scanner(System.in);double x;double sum = 0;While (int cnt = 0; cnt < 20; cnt++) { System.out.println(“Enter a number”);

x = kb.nextDouble(); sum += x;}System.out.println(“The Average is “ +

sum/cnt);

Write a Java program which reads 20 numbers using a scanner and computes their average.

Page 203: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: while & do-while 205

Q3 Solution

Scanner kb = new Scanner(System.in);int even_cnt = 0;int odd_cnt = 0;int n;For(;;) { n = kb.nextInt(); if (n < 0) break; else if ( mod(n,2) == 0) even_cnt++; else odd_cnt++; }System.out.println(“Even = “ + even_count + “ odd = “

odd_cnt);

Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel.

Page 204: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Nested-loop examples

Page 205: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Questions

1. Write a java program which gives the following output122333444455555

2. Write a java program which prints all the prime numbers less than 1000.

Page 206: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Q1 Solution

Write a java program which gives the following output122333444455555

for(int k = 1; k <= 5; k++) {For ( int j = 1; j <=k; j++)

System.out.print(k);System.out.println();

}

Page 207: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Q2 solution

Write a java program which prints all the prime numbers less than 1000.

int n, j;

for(int k = 2; k < 100; k++) {

n = 0;

j = 2;

while(n == 0 && j < k/2) {

if (mod(k,j) == 0) n++;

j++;

}

if( n ==0) System.out.println(k);

}

Page 208: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 3.3 (pages 166-177)

Page 209: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 11 : Arrays

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 210: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Arrays

An array is an ordered list of values

An array of size N is indexed from zero to N-1

This array holds 4 values that are indexed from 0 to 3

Entire array hasA single name

Each value hasA numeric index

scores [0] [1] [2] [3]

79 62 98 57

Page 211: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Processing Array Elements

Access individual elements of an array using: the name of the array a number (index or subscript) that tells which of the

element of the array

What value is stored in scores[2]?

scores [0] [1] [2] [3]

79 62 98 57

Page 212: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Arrays

For example, an array element can be assigned a value, printed, or used in a calculation:

scores[2] = 87;

scores[first] = scores[first] + 2;

Avg = (scores[0] + scores[1])/2;

System.out.println (“Max = " + scores[3]);

Page 213: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Arrays

The values held in an array are called array elements

Array elements are of the same type

The element type can be a primitive type or an object reference.

Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc.

In Java, the array itself is an object

Therefore the name of the array is a object reference variable, and the array itself must be instantiated

Page 214: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Declaring an Array

Defining an array

Type [] name

Where: Type specifies the kind of values the array stores the brackets [ ] indicate this is an array name is the handle to access the array

•This declares the handle only

•Initialized to null

•Stores an address when arrays are created

•This declares the handle only

•Initialized to null

•Stores an address when arrays are created

Page 215: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Declaring an Array

The scores array could be declared as follows:

double [] scores = new double [4];

The above statement will: allocate block of memory to hold 4 doubles initialize block with zeros create a handle or a pointer or a reference called scores

store address of the block in scores scores [0] [1] [2] [3]

0.0 0.0 0.00.0

BlockHandle

Page 216: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Syntax

Forms

ElementType [] arrayName;

ElementType [] arrayName = new ElementType [size];

ElementType [] arrayName = array-literal;

Where: ElementType is any type arrayName is the handle for the array array-literal is a list of literals enclosed in curly braces { }

Page 217: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Declaring Arrays

Some examples of array declarations:

float[] prices = new float[500];

boolean[] flags;

flags = new boolean[20];

char[] codes = new char[1750];

Page 218: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Bounds Checking

Once an array is created, it has a fixed size

An index used in an array reference must specify a valid element

That is, the index value must be in bounds (0 to N-1)

The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds

This is called automatic bounds checking

Page 219: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Bounds Checking

For example, if the array scores can hold 100 values, it can be indexed using only the numbers 0 to 99

If scores has the value 100, then the following reference will cause an exception to be thrown:

System.out.println (scores[count]);

Often for loop is used to process array. It’s common to introduce off-by-one errors when using arrays

for (int index=0; index <= 100; index++)

scores[index] = index*50 + epsilon;

problem

Page 220: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Bounds Checking

Each array object has a public constant called length that stores the size of the array

It is referenced using the array name:

scores.length

Note that length holds the number of elements, not the largest index

Page 221: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Initializer Lists

An initializer list can be used to instantiate and initialize an array in one step

The values are delimited by braces and separated by commas

Examples:

int[] scores = {98, 76, 54, 83, 87, 65, 99, 66};

char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

Page 222: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Initializer Lists: Example 1

Used when exact size and initial values of an array are known in advance

int [] scores = {98, 76, 54, 83}

Visualize the results of the above command

scores [0] [1] [2] [3]

98 76 54 83

Page 223: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Initializer Lists: Example 2

Consider the following 4 student names

Note results:

String [] STUDENTS = { “Aref", “Ali“, “Emad”, "Sami"};

STUDENTS [0] [1] [2] [3]

Aref Ali Emad Sami

Array elements are handles for String values

Page 224: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Initializer Lists

Note that when an initializer list is used:

the new operator is not used

no size value is specified

The size of the array is determined by the number of items in the initializer list

An initializer list can only be used only in the array declaration

Page 225: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The Assignment Operation

Java provides a few operations to use with arrays, including assignment

Consider:

int [] alist = { 1, 12, 15, 7};int [] blist;blist = alist;

Recall that alist and blist are handles

alist contains an address of where the numbers are blist now contains that same address blist does not have a copy of alist

Page 226: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array Cloning

To actually create another array with its own values, Java provides the .clone() method

int [] alist = {1, 12, 15, 7};

int [] blist;

blist = alist.clone();

Now there are two separate lists of numbers, one with handle alist, the other with handle blist

Page 227: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array Cloning with Reference Types

Recall previous declaration:

Consider:

String[] s_list = STUDENTS.clone():

This will create another list of handles, also pointing to the names

Sometimes called a "shallow copy"

operation

Sometimes called a "shallow copy"

operation

STUDENTS [0] [1] [2] [3]

Aref Ali Emad Sami

Page 228: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array Cloning with Reference Types

We can write our own "deep copy"

String [] original = {“Aref”,“Ali”, “Emad”, “Sami”};

String [] result = new String(original.length);

for (i = 0; i < original.length; i++)

result[i] = original[i].clone();

Page 229: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array Equality

Java has an equals() method for classes

if (a1.equals(a2)) …

If a1 and a2 are arrays, the equals() method just looks at the addresses the handles point to

They could be pointing to different addresses but the contents of the array still be equal

It is the contents that we really wish to compare

Page 230: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array Equality

We must write our own method to compare the arrays they both must have the same length then use a for( ) loop to compare element by element

for equality

Boolean areEqual = true;if (list1.length != list2.length) areEqual = false;

else { for (int i = 0; i < list1.length; i++) if (list1[i] != list2[i]) areEqual = false;

}if(areEqual) System.out.println(“They are equal”);else System.out.println(“They are NOT equal”);

As soon as one pair of elements is found not equal, the arrays are not equalAs soon as one pair of elements is found not equal, the arrays are not equal

Page 231: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array exercises

Write an application that inputs 10 numbers, each between 10 and 100. As each number is read, display it only if it is not a duplicate of a number already read.

Given an array of integers, write a java code that allows to check if the array is “palindromic”. A palindromic array is a symmetric one:

For example the arrays 1 6 4 6 1 and 258852 are both palindromic, but the array 3753 is not.

Page 232: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Array exercises

Write a program that reads a sequence of 10 integers into an array and then computes the alternating sum of all elements in the array.

For example if the array is : 1 4 9 16 9 7 4 9 11 then it computes : 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11

= -2

Page 233: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 6.1 (pages 372-379)

Page 234: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 12 : 2-D Arrays

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 235: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Two-Dimensional Arrays

Two-dimensional (2-D) Arrays.

2-D Array Declaration.

Initializer Lists.

Differing Numbers of Elements in each Row.

Implementation of a 2-D Array

Printing a 2-D Array.

Page 236: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

2-D Arrays: Why?

Often data come in a 2-D form. For example: The layout of a printed page is 2-D Computer screen is 2-D The spread sheet (table) is 2-D

For these situations we need a 2-D array.

A 2-D array can be thought of as a collection of "slots" laid out in a 2-D grid.

each slot can hold a value two indexes are needed to specify a slot.

Page 237: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example: Table of Student Grades

Imagine a class of 7 students that have a quiz grades for 5 weeks. These grades can be stored in a table form.

A particular cell of the table is identified by student number and week number. For example:

The grade for student 0 in week 1 is 42

The grade for student 3 in week 4 is 93

The grade for student 6 in week 2 is 78

StudentWeek

0 1 2 3 4

0 99 42 74 83 100

1 90 91 72 88 95

2 88 61 74 89 96

3 61 89 82 98 93

4 93 73 75 78 99

5 50 65 92 87 94

6 43 98 78 56 99

Page 238: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

2-D Arrays in Java

In Java, a table may be implemented as a 2-D array.

As with 1-D arrays, every slot in a 2-D array is of the same type which can be a primitive type or an object reference type.

Each slot of the array is specified with a row and column number.

Suppose that gradeTable is a 2-D array then the syntax to specify a particular slot should be gradeTable[row][col]

For example

gradeTable[0][1] is 42

gradeTable[3][4] is 93

gradeTable[6][2] is 78

StudentWeek

0 1 2 3 4

0 99 42 74 83 100

1 90 91 72 88 95

2 88 61 74 89 96

3 61 89 82 98 93

4 93 73 75 78 99

5 50 65 92 87 94

6 43 98 78 56 99

Page 239: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

2-D Arrays in Java

The subscripted variables of a 2-D array can be used in assignment statements and arithmetic expressions just like any variable:

gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1.

gradeTable[ 3 ][ 4 ]++; //increments the value at row 3 column 4.

int value = (gradeTable[ 6 ][ 2 ] + 2)/2;//puts 40 into value

Write a Java statement that puts a zero into row 5 column 3.

StudentWeek

0 1 2 3 4

0 99 33 74 83 100

1 90 91 72 88 95

2 88 61 74 89 96

3 61 89 82 98 944 93 73 75 78 99

5 50 65 92 87 94

6 43 98 78 56 99

gradeTable[ 5 ][ 3 ] = 0

Page 240: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

2-D Array Declaration

In Java, a 2-D array is an object.

To declare a reference variable myArray to a 2-D array of int: int[][] myArray;

To create an array object of 3 rows and 5 columns, and put the reference in myArray, we write

int[][] myArray = new int[3][5];

All the elements of myArray are initialized to zero. We can create the above array by using the initializer list: int[][] myArray = {{0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}};

Page 241: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Different Numbers of Elements per Row

In Java, each row of a 2-D array may have a different number of elements. In the following example, the array A has

3 elements in its first row, 2 in its second row, and 5 in its last row.

int[][] A = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }};

Page 242: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Length of a 2-D Array

The length of a 2-D array is the number of rows it has.

So the row index (number) is from 0 to length-1.

As each row in a 2-D array is like a 1-D array, we can refer to an entire row by specifying just the row index, e.g., A[0] means row # 0

The length of a row is the number of columns in the row.

As each row of a 2-D array can have a different number of columns, so each row has its own length.

int[][] A = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };

System.out.println("Length of array is: " + A.length );

System.out.println("Length of row[0] is: " +

A[0].length );

System.out.println("Length of row[1] is: " +

A[1].length );

System.out.println("Length of row[2] is: " +

A[2].length );

Page 243: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Implementation of 2-D Array

A 2-D array is implemented as an array of 1-D arrays.

To understand the idea, we construct the 2-D array step-by-step.

int[][] myArray; // 1

declares a variable myArray

myArray = new int[3][] ; // 2

Creates an array object. The array object has 3 slots. Each slot may refer (in the future) to an array of int (i.e., a row)

myArray[0] = new int[3] ; // 3

Creates a 1-D array object and puts its reference in slot 0 of myArray.

Page 244: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Implementation of 2-D Array

A previously constructed 1-D array can be assigned to a row:

int[] x = {0, 2}; int[] y = {0, 1, 2, 3, 4}; myArray[1] = x ;myArray[2] = y ; //4

The rows do not need to have the same number of elements

Page 245: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Printing a 2-D Array

Suppose we want to print every element of a 2-D array A

It can be done by using nested loops.

The expression A[row].length gives a different number for each row of the array.

int[][] A = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }}; for ( int row=0; row < A.length; row++ ) {

System.out.print("Row " + row + ": ");

for ( int col=0; col < A[row].length; col++ )

System.out.print( A[row][col] + " ");

System.out.println();

}

Page 246: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 6.4 (pages 425-436)

Page 247: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a program that creates a two dimensional array, fills it using Scanner, and then prints the sum of every column.

Given a two-dimensional array, dataTable, of type double such that the rows can have different lengths. Write a code fragment that computes the average of each row and saves it in a single-dimension array of size corresponding to the rows of dataTable.

Page 248: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 13 : Methods

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 249: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

A Java Program

A Java program consists of one or more classes

A Java class consists of one or more methods

A Java method consists of one or more statements

A Java Program

Javaclasses

JavaMethods

Page 250: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- What is a method …

A Java application program consists of one or more classes.

Each class has one or more methods

Each method consists of one or more statements

Each method has a name.

One of the methods must be called main

When a Java application program is run, the run-time system automatically invokes the method named main

All Java application programs start with the main method

Page 251: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - What is a method …

public class class-name {

method1

method 2

method 3

method n

}

Page 252: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Page 253: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example of a Java Program

Class nameMain method

Instruction

Class body

Page 254: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercise

Write a program that computes the factorial (n!) of 6 then the factorial of 3, then the factorial of 10.

Page 255: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercise

Write a program that computes the factorial (n!) of 6 then the factorial of 3, then the factorial of 10. Method

invocation

Method definition

Return instruction

Method parameter

Return type

Page 256: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

-- Method Structure

public or private<static> <void or typeReturned>myMethod(<parameters>)

{statementstatementstatement……

statement }

Method body

If method doesn’t return value

Variable list

Method name

Type of the return value

Page 257: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Invoking a Methods

The statements inside a method body are executed when the corresponding method is called from another method.

Calling a method is also called invoking a method Each time the method is invoked, its corresponding

body is executed

Page 258: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- return Statements …

The body of a method that returns a value must also contain one or more return statements

A return statement specifies the value returned and ends the method invocation.

Page 259: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - return Statements

A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed

Example : write a method that prints all the numbers between 10 and 30

Page 260: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Local Variables

A variable declared within a method definition is called a local variable

All variables declared inside the method are local variables

All method parameters are local variables

Page 261: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Local Variables

If two methods each have a local variable of the same name, they are still two entirely different variables. Example:

Local variable in main method

Local variable in factorial method

Local variable in addition method

Page 262: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Method Parameters …

A parameter list provides a description of the data required by a method

It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in the method

public double myMethod(int p1, int p2, double p3)

Example: What is the parameter list of a method division that divides two integers and returns the result (double)?

Parameters list

Page 263: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - Method Parameters …

When a method is invoked, the appropriate values must be passed to the method in the form of arguments

The number, order, and types of the arguments must exactly match that of the parameter list

Error: type mismatch

Page 264: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Is this program correct?

… - Method Parameters …

Yes it is! .. Details in the next slide..

Page 265: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - Method Parameters …

If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion

In the preceding example, the int value of argument a would be cast to a double

A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right:

byteshortintlongfloatdouble char

Page 266: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - Method Parameters …

A parameters is often thought of as a blank or placeholder that is filled in by the value of its corresponding argument

However, a parameter is more than that: it is actually a local variable

When a method is invoked, the value of its argument is computed, and the corresponding parameter (i.e., local variable) is initialized to this value

Even if the value of a formal parameter is changed within a method (i.e., it is used as a local variable) the value of the argument cannot be changed

Page 267: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Call-by-Value Example

Prints 10

Prints 10

Page 268: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Method Parameters: Array Parameters

Methods can have array parameters.

Example: Write a program that prints the values of an array of integers, then increments each value of the array by two and then prints the new values of the same array.

A parameter of type array

Page 269: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Details

Array arguments are always passed by reference. This means any changes done to an array element by the invoked method, will also change the corresponding array element in the caller method.

Example:

Public static void m1() { int [] A = { 1, 2, 3}; m2(A); }

public static void m2(int [] A){ A[1] = 5};

Method m2 changes the value of a[1] to 5; as a result the value of a[1] in m1 will also change to 5.

Page 270: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Method Overloading …

In java the same class can have methods with the same name. Such methods are called overloaded methods.

Overloaded methods must differ in the number or type of their arguments.

The name of a method together with the number, order, and types of its arguments are called the method signature. No two methods of the same class must have the same signature.

The compiler treats overloaded methods as completely different methods. It knows which one to call by using method signatures.

Page 271: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Method Overloading …

These 3 methods have the same

name but different

signatures

Page 272: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read pages 206-212

Page 273: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a method that takes as input an integer value and returns the sum of all integers less than that value. For example, if the input is 6, the output is 5+4+3+2+1 = 15. If the input is negative, the output should be -1.

Write a method that takes as input an array of integers and returns the average of the values in the array.

Page 274: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercises

Write a method public void printTriangleNumbers(int n) such that:

The call: printTriangleNumbers(5) prints the following on the screen: 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 The call: printTriangleNumbers(6) prints the following on the screen: 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 The call: printTriangleNumbers(3) prints the following on the screen: 1 2 3 1 2 1

Page 275: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 14 : Classes

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 276: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Outline

Introduction

Class Definitions

A Class Is a Type

The new Operator

Instance Variables and Methods

Information Hiding

public and private Modifiers

Accessor and Mutator Methods

Encapsulation

Page 277: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Introduction

Classes are the most important language feature that make object-oriented programming (OOP) possible

Programming in Java consists of defining a number of classes

Every program is a class All helping software consists of classes All programmer-defined types are classes

Classes are central to Java

Page 278: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example

Suppose you are asked to write a program for a commercial company:

The company has several: Employees Clients Products Stores

If you use an object-oriented language such as Java, you will have to define:

Class Employee : public class Employee{ ..}

Class Client: public class Client{..} Class Product: public class Product{..} Class Store: public class Store{..}

Page 279: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Class Definitions

You already know how to use classes and the objects created from them, and how to invoke their methods

For example, you have already been using the predefined String and Scanner classes

Now you will learn how to define your own classes and their methods, and how to create your own objects from them …

next slide

Page 280: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Class Definition

A class definition is composed of two parts: Data members (Data part) Methods (Operations part)

Example: define a class Employee

Page 281: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Details

A class definition specifies the data items and methods that all of its objects will have

These data items and methods are sometimes called members of the object

Data items are called fields or instance variables

Instance variable declarations and method definitions can be placed in any order within the class definition

Page 282: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Object Declaration

It is possible to declare several objects from a class:

Class Employeee2

e1

e3

e4

Note: classes Employee and TestClass should be saved in the same directory

Strings2

s1

s3

s4

The same principle as:

Page 283: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- A Class Is a Type

A class is a special kind of programmer-defined type, and variables can be declared of a class type

A value of a class type is called an object or an instance of the class

The following phrases are equivalent: “e1 is of type Employee," “e1 is an object of the class Employee," and “e1 is an instance of the class Employee"

Employeee2

e1

e3

e4

Page 284: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Object Creation

The instruction:Employee e1;

only declares e1. But the object is still not created.

To create the object the operator new must be used:

e1 = new Employee();

These can be combined as follows:

Employee e1 = new Employee();

Page 285: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Object Creation

Declaration Creation

Question: What is the name of Employee e1?

How to change the name of Employee e1? … next slide ..

Page 286: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Instance Variables and Methods …

In order to refer to a particular instance variable, preface it with its object name as follows:

objectName.instanceVar1objectName.instanceVar2

Example: e1.name e1.age e1.salary

To change the name of e1: e1.name = “Mohamed”;

Page 287: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Instance Variables and Methods …

In order to invoke a method of a class, you need an object of that class:

objectName.method1()objectName.method2(argument1)

Example: e1.outputDetails(); e1.outputDetails();

Page 288: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Instance Variables and Methods …

Modifying the name Accessing the name

Invoking a method

Calling object

Page 289: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Information Hiding and Encapsulation

Information hiding is the practice of separating how to use a class from the details of its implementation

Abstraction is another term used to express the concept of discarding details in order to avoid information overload

Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object), which hides the implementation details

Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface

In Java, hiding details is done by marking them private

Page 290: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- public and private Modifiers …

Instance variables and methods of a class can be declared public, or private

Example: public String name; private int age; public void outputDetails{..}

The modifier public means that there are no restrictions on where an instance variable or method can be used

The modifier private means that an instance variable or method cannot be accessed by name outside of the class

It is considered good programming practice to make all instance variables private

Page 291: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- public and private Modifiers …

Illegal because we try to access a private member (age) from outside the class Employee

Page 292: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

… - public and private Modifiers

Within the definition of a class, private members of any object of the class can be accessed, not just public members of the calling object

Page 293: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Problem ..

It is considered good programming practice to make all instance variables private

Question: how to access and modify the instance variables of Employee objects e1, e2, e3 and e4? .. answer .. Use accessor and mutaor methods ….

next slide..

Page 294: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Accessor and Mutator Methods …

Accessor methods allow the programmer to obtain the value of an object's instance variables

The data can be accessed but not changed The name of an accessor method typically starts with the

word get Example: public String getName()

{ return name;}

Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner

Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word

set Example: public void setName(String n)

{ name = n;}

Page 295: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- Accessor and Mutator Methods (Example)

Accessor method for instance variable name

Mutator method for instance variable name

Modifying the name of e1 using a mutator method

Page 296: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read sections 4.1 and 4.2 (pages 200-243)

Page 297: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercise

Define a class Date with three instance variable:

month of type String day of type integer year of type integer

Provide a method WriteOutput to print the details of the Date

Provide accessor and mutator methods for all instance variables.

Page 298: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Solution

Page 299: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Solution

Page 300: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Solution

Page 301: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 15 : Classes II

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 302: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Constructors

A constructor is a special kind of method that is designed to initialize the instance variables for an object:

public ClassName(ParametersList){…}

A constructor must have the same name as the class

A constructor has no type returned, not even void

Constructors are typically overloaded

Page 303: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Constructor Example

Constructor

Page 304: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

How Constructors are called

A constructor is called when an object of the class is created using new

ClassName objectName = new ClassName(anyArgs);

The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator

A constructor cannot be invoked like an ordinary method

Example:

Employee e1 = new Employee(“Mohamed”, 20, 5000);

Page 305: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Constructors

Constructor

Calling the constructor

Page 306: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Constructors

In the previous lecture we saw this example:

We did not define any constructor,

but

we created objects using new!!

Explanation .. Next slide ..

Page 307: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Include a No-Argument Constructor

If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created

If you include even one constructor in your class, Java will not provide this default constructor

If you include any constructors in your class, be sure to provide your own no-argument constructor as well

Page 308: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

No-argument constructor

No-argument constructor

Page 309: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Copy Constructor

A copy constructor is a constructor with a single argument of the same type as the class.

It creates an object which is an exact copy of the argument object

Example:

How to invoke a copy constructor:

Page 310: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

- The methods equals and toString

Java expects certain methods, such as equals and toString, to be in all, or almost all, classes

The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal“

Note: You cannot use == to compare objects

public boolean equals(ClassName objectName)

The purpose of the toString method is to return a String value that represents the data in the object

public String toString()

Page 311: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

equals example

Page 312: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

equals example

Invoking equals method:

equals invocation

Page 313: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

toString example

toString invocation

Page 314: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read sections 4.3 and 4.4 (pages 244-273)

Page 315: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Exercise: Temperature Class (1/2)

Write a Temperature class that has two instance variables: a temperature value (a floating-point number) and a character for the scale, either 'C' for Celsius or 'F' for Fahrenheit.

The class should have four constructor methods: one for each instance variable (assume zero degrees if no

value is specified and Celsius if no scale is specified), one with two parameters for the two instance variables, and a no-argument constructor (set to zero degrees Celsius).

Include two accessor methods to return the temperature: getTempCelsius: to return the degrees Celsius, getTempFahrenheit: to return the degrees Fahrenheit

IMPORTANT: use the following formulas : degreesC = 5(degreesF - 32)/9 degreesF = (9(degreesC)/5) + 32

Page 316: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Include three mutator methods, setValue to set the value, setScale to set the scale ('F' or 'C'), and setValueAndScale to set both;

Include a suitable toString method. Include a equals method

Then write a test class called TestTemperature that tests all the methods. Be sure to use each of the constructors.

Exercise: Temperature Class (2/2)

Page 317: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 16 : Classes III

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 318: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 320

Class variables Vs Primitive type variables

int i = 15;

Employee e1 = new Employee(“Mohamed”, 20, 5000);

i is a variable of type integer that contain the value 15.

e1 is a variable of type Employee that contains the address where the object is located.

The object named by the variable is stored in some other location in memory

i 15

e1

“Mohamed”20

5000

Page 319: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 321

References

What happens if we do:

Employee e1 = new Employee(“Mohamed”, 20, 5000);

Employee e2 = e1;

e1 and e2 will refer to the same object! The assignment operator sets the reference (memory

address) of one class type variable equal to that of another

Any change to the object named by one of theses variables will produce a change to the object named by the other variable, since they are the same object !!

Page 320: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example

What will be printed here?

Page 321: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 323

- Class Parameters …

All parameters in Java are call-by-value parameters

A parameter is a local variable that is set equal to the value of its argument

Therefore, any change to the value of the parameter cannot change the value of its argument

Class type parameters appear to behave differently from primitive type parameters

They appear to behave in a way similar to parameters in languages that have the call-by-reference parameter passing mechanism

Page 322: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Call-by-Value

Page 323: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Call-by-Reference

What salary will printed here?

Page 324: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 326

… - Class Parameters

The value plugged into a class type parameter is a reference (memory address)

Therefore, the parameter becomes another name for the argument

Any change made to the object named by the parameter (i.e., changes made to the values of its instance variables) will be made to the object named by the argument, because they are the same object

Page 325: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 327

- Differences Between Primitive and Class-Type Parameters

A method cannot change the value of a variable of a primitive type that is an argument to the method

In contrast, a method can change the values of the instance variables of a class type that is an argument to the method

Page 326: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 328

Pitfall: Use of == with Class type variables

The test for equality (==) also behaves differently for class type variables

The == operator only checks that two class type variables have the same memory address

Unlike the equals method, it does not check that their instance variables have the same values

Two objects in two different locations whose instance variables have exactly the same values would still test as being "not equal“

Use equals method instead:

Page 327: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

April 19, 2023 ICS102: Classes 3/5 329

- The Constant null

null is a special constant that may be assigned to a variable of any class type

YourClass yourObject = null;

It is used to indicate that the variable has no "real value“

Page 328: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

The end

Important to do at home :

- read section 5.2

(pages 310-324)

Page 329: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Advanced Example

An advanced example of classes is the Class Person defined in Display 5.19 of Chapter 5 of the textbook

(Pages 296-304 of the 4th edition)

Page 330: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

ICS102

Lecture 18 : Static Members

King Fahd University of Petroleum & MineralsCollege of Computer Science & Engineering

Information & Computer Science Department

Page 331: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Static Methods

A static method is one that can be used without a calling object.

A static method still belongs to a class, and its definition is given inside the class definition.

When a static method is defined, the keyword static is placed in the method headerpublic static returnedType myMethod(parameters) { . . . }

Static methods are invoked using the class name in place of a calling objectreturnedValue = MyClass.myMethod(arguments);

Page 332: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Static Variables

Static variables can be declared and initialized at the same time

private static int myStaticVariable = 0;

If not explicitly initialized, a static variable will be automatically initialized to a default value

boolean static variables are initialized to false Other primitive types static variables are initialized to the

zero of their type Class type static variables are initialized to null

It is always preferable to explicitly initialize static variables rather than rely on the default initialization

Page 333: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Static Variables

A static variable should always be defined private, unless it is also a defined constant

The value of a static defined constant cannot be altered, therefore it is safe to make it public

In addition to static, the declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed

public static final int BIRTH_YEAR = 1954;

When referring to such a defined constant outside its class, use the name of its class in place of a calling object

int year = MyClass.BIRTH_YEAR;

Page 334: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Pitfall: Invoking a Nonstatic Method Within a Static Method

A static method cannot refer to an instance variable of the class, and it cannot invoke a nonstatic method of the class

A static method has no this, so it cannot use an instance variable or method that has an implicit or explicit this for a calling object

A static method can invoke another static method, however

Page 335: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Simple Example

static field

static method

Page 336: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example (Part 1 of 4)

Page 337: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example (Part 2 of 4)

Page 338: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example (Part 3 of 4)

Page 339: King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department Lecture 1 : Introduction

Example (Part 4 of 4)