0% found this document useful (0 votes)
4 views

Java Lecture Notes

These Java Lecture Notes provide a summary of key concepts in Java programming, including its history, structure, data types, and programming conventions. The notes emphasize that they are not a replacement for textbooks or personal notes and cover various topics such as conditionals, loops, methods, and object-oriented design. The document serves as a guide for understanding the fundamentals of Java and its application in software development.

Uploaded by

Halil Özmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Lecture Notes

These Java Lecture Notes provide a summary of key concepts in Java programming, including its history, structure, data types, and programming conventions. The notes emphasize that they are not a replacement for textbooks or personal notes and cover various topics such as conditionals, loops, methods, and object-oriented design. The document serves as a guide for understanding the fundamentals of Java and its application in software development.

Uploaded by

Halil Özmen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

JAVA Lecture Notes

These Java notes do not intend to replace the textbook or the notes taken by the student.
These are summary notes, and may not cover all the details explained during the lectures.

Table of Contents
1. Introduction to Java......................................................................................................................2
1.1. Introduction to Computers and Computer Programming ...................................................................... 2
1.2. History and Structure of Java .............................................................................................................. 4
1.3. Basics of Java..................................................................................................................................... 5
1.4. Identifiers and Reserved Words .......................................................................................................... 5
1.5. Java Naming Conventions................................................................................................................... 5
1.6. White Space and Indentation............................................................................................................... 6
2. Data and Expressions ..................................................................................................................6
2.1. Primitive Data Types ........................................................................................................................... 6
2.2. Character Strings ................................................................................................................................ 7
2.3. Variables and Assignments ................................................................................................................. 7
2.4. Operators and Expressions ................................................................................................................. 8
2.5. Data Conversion ................................................................................................................................. 9
2.6. Simple Input ........................................................................................................................................ 9
3. Conditionals and Loops .............................................................................................................10
3.1. Boolean Expressions......................................................................................................................... 10
3.2. The if Statement................................................................................................................................ 11
3.3. Comparing Strings ............................................................................................................................ 12
3.4. The switch Statement ........................................................................................................................ 12
3.5. The for Statement ............................................................................................................................. 13
3.6. The while Statement ......................................................................................................................... 14
3.7. The do Statement (do-while) ............................................................................................................. 15
3.8. break and continue Statements ......................................................................................................... 16
4. Methods .....................................................................................................................................17
5. Using Classes and Objects ........................................................................................................19
5.1. Packages .......................................................................................................................................... 19
5.2. Creating Objects ............................................................................................................................... 19
5.3. The String Class ............................................................................................................................... 21
5.4. Character Methods............................................................................................................................ 22
5.5. The Math Class ................................................................................................................................. 22
5.6. The Random Class ........................................................................................................................... 23
5.7. Formatting Output ............................................................................................................................. 24
5.8. File Input and Output ......................................................................................................................... 25
6. Arrays and ArrayList ..................................................................................................................27
6.1. Arrays ............................................................................................................................................... 27
6.1.1. Declaring and Using Arrays....................................................................................................... 27
6.1.2. Arrays of Objects ...................................................................................................................... 28
6.2. Two-Dimensional Arrays ................................................................................................................... 29
6.3. Variable Length Parameter Lists........................................................................................................ 30
6.4. The ArrayList Class ........................................................................................................................... 31
7. Writing Object Classes...............................................................................................................33
7.1. Classes and Objects ......................................................................................................................... 33
7.2. Anatomy of a Class ........................................................................................................................... 33
7.3. Constructors, Mutators, Accessors .................................................................................................... 36
7.4. Encapsulation ................................................................................................................................... 36
7.5. Inheritance ........................................................................................................................................ 37
8. Object-Oriented Design .............................................................................................................38
8.1. Software Developments Activities...................................................................................................... 38
8.2. Identifying Classes and Objects ........................................................................................................ 38
8.3. Static Class Members ....................................................................................................................... 39
8.4. Class Relationships........................................................................................................................... 40
8.5. Method Design .................................................................................................................................. 41
9. Sorting and Searching ...............................................................................................................42
9.1. Sorting Algorithms............................................................................................................................. 42
9.2. Searching Algorithms ........................................................................................................................ 43
10. Recursion ..................................................................................................................................45

Java Lecture Notes 1 Halil Özmen


1. Introduction to Java
1.1. Introduction to Computers and Computer Programming
Computer Program:
A computer program is a sequence or set of instructions in a programming language for a
computer to execute.

Computer Programming Process:


Computer programming is the process of performing a particular computation, usually by
designing and building an executable computer program. Programming involves tasks such as
analysis, generating algorithms (design and implementation), profiling algorithms' accuracy and
resource consumption, and the implementation of algorithms.

Programming Languages:
A programming language is a system of notation for writing computer programs.
Assembly Language is any low-level programming language with a very strong correspondence
between the instructions in the language and the architecture's machine code instructions.
A high-level language is any programming language that enables development of a program in a
much more user-friendly programming context and is generally independent of the computer's
hardware architecture.

Machine Language: 01101011 01010100 10111011 11101010 00100111 ....


Assembly Language:
LBL4: MOV AX,8
ADD R3, #32
CMP AL, BL
JE LBL4
High Level Language:
a = int(input("Enter an integer number: "))
if a % 2 == 0:
a = a / 2
print(a)

History of Programming Languages: (only major languages are listed)


1951 - Assembly Language 1978 - SQL (query language)
1954 - FORTRAN 1980 - C++
1958 - LISP 1984 - MATLAB
1958 - ALGOL 1990 - Python
1959 - COBOL 1993 - R
1964 - BASIC 1995 - Java
1964 - PL/I 1995 - PHP
1970 - Pascal 2002 - Scratch
1972 - C ....

Assembler, Compiler, Linker, Loader, Interpreter:


• Assembler translates a program in an assembly language to machine instructions.
• Compiler translates a program in a high-level language to machine instructions.
• Linker is a program which helps to link object modules of a program into a single object file. It
performs the process of linking. Linking is a process of collecting and maintaining piece of code
and data into a single file.
• Loader is a component of an operating system that is accountable for loading programs and
libraries to computer memory.
• Interpreter is a computer program that directly executes instructions written in a programming or
scripting language, without requiring them previously to have been compiled into a machine
language program.

Java Lecture Notes 2 Halil Özmen


Computer Components:

A computer consists of central processing unit (CPU), memory and input/output (IO) modules.

CPU controls the computer and instructions are run by the CPU.

CPU consists of control unit, arithmetic logic unit (ALU), registers and interconnections among
these units. The control unit controls the CPU.

COMPUTER Central Processing Unit (CPU)

Central Arithmetic
Processing Memory Control Unit Logic Unit
Unit (ALU)
System Intercon-
(CPU)
Intercon- nection in
nection CPU

Input/
Output Registers
Modules

Input/Output (IO) System Interconnection (Busses)


Devices (Data Bus, Address Bus, Control Bus)

Input Devices: keyboard, mouse, harddisk, flash disk, microphone, modem, etc.
Output Devices: monitor, harddisk, flash disk, sound speaker, modem, printer, etc.

Running Programs in Computer:

While running programs, both the program (computer instructions) and data are stored in the
memory.
Memory
0 OS
Program statements and CPU Instructions:
Program Statements CPU Instructions
prg
z=x+y Read location x prg
Read location y prg
Add x 10
Write to location z y 20
print(z) Read location z z 30
Send to output
8GB

Java Lecture Notes 3 Halil Özmen


1.2. History and Structure of Java

Java is an object-oriented programming language. Java was developed by James Gosling and
colleagues at Sun Microsystems in the early 1990s. It was developed to provide a platform-
independent programming language. The first public implementation was Java 1.0 in 1995. It made
the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms.

Structure of Java:
Java programs consists of pieces called classes.
Objects are instances of classes. From the same class, many objects can be created. An object-
oriented program may contain many objects from various classes.
Classes contain attributes and methods.
Attributes contain data of object. Methods perform actions related with objects.

Java has rich collections of existing classes in the Java Class Libraries which are also known as the
Java API's (Application Programming Interfaces).

To write Java programs, one has to learn:


a) the Java language itself (the syntax, the constructs),
b) the classes in the Java Class Libraries,
c) to write new classes.

Java programs go through five phases:


1. Edit: create Java program using an editor and store on disk in a file ending with .java.
2. Compile: bytecodes are created and stored on disk in a file ending with .class.
3. Load: bytecodes are taken from the disk and stored in the memory.
4. Verify: check that all bytecodes are valid, and ensure that the bytecode does not violate Java's
security restrictions.
5. Execute: JRE (Java Runtime Engine) reads bytecodes, translates them into instructions that the
computer can understand and runs these machine instructions.

.java .class

Edit Source program Compile Bytecode Run

Oracle who now owns Sun Micrsystems, the creator of the Java programming language, provides the
Java Software Development Kit (Java SDK), which is usually referred to as the Java Development Kit
(JDK).
The Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader
(java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools
needed in Java development.
JDK can be downloaded from https://www.oracle.com/technetwork/java/javase/downloads/index.html.

Integrated Development Environment (IDE) softwares makes the software development tasks easier.
They provide tools to edit, compile and run Java programs.
Eclipse is one of the powerful IDE programs to develop Java programs.

Java Lecture Notes 4 Halil Özmen


1.3. Basics of Java
The source file must be in the form: classname.java. The following Java program outputs "Welcome
to Java!". The following program is in WelcomeJavaApp.java file.
// The WelcomeJavaApp class implements an application that
// simply prints "Welcome to Java!" to standard output.

public class WelcomeJavaApp


{
public static void main(String[] args)
{
System.out.println("Welcome to Java!"); // Display the string.
} // end of main
} // end of WelcomeJavaApp class
Here, the "WelcomeJavaApp" class is an application class. Application classes have a "main" method.

Comments:
The Java programming language supports three kinds of comments:
// text The compiler ignores everything from // to the end of the line.
/* text */ The compiler ignores everything from /* to */.
/** documentation */ This indicates a documentation comment (doc comment, for short). The
compiler ignores this kind of comment, just like it ignores comments that
use /* and */. The JDK javadoc tool uses doc comments when preparing
automatically generated documentation.

1.4. Identifiers and Reserved Words


The various words used when writing programs are called identifiers.
In Java, the identifiers can be composed of any combination of letters, digits, the underscore character
( _ ) and the dollar sign ($), but it cannot begin with a digit. (It cannot contain any character not listed
above. E.g.: space character and punctuation characters.)
Some valid identifier examples: c3po, a77_4E, _4aT, $a70b, $, _0, _a, _$, $1, _1_, $X$, _x$, a, A
Some invalid identifier examples: a7+e44, _4-aT, 7aa, an.ne, ba ba

Java identifiers are case sensitive. Therefore, total, Total, ToTal, TOTAL are all different identifiers.

Reserved words in Java:


abstract const final int public throw
assert continue finally interface return throws
boolean default float long short transient
break do for native static true
byte double goto new strictfp try
case else if null super void
catch enum implements package switch volatile
char extends import private synchronized while
class false instanceof protected this

1.5. Java Naming Conventions


Using standard Java naming conventions make the Java code easier to read for the author and for
other programmers. Readability of Java code is important because it means less time is spent trying to
figure out what the code does, leaving more time to fix or modify it.
The following Java naming conventions will be followed in our course:
1. Class names are written in CamelCase, i.e. first character of each word is in upper case.
E.g.: class Student, class Car, class ClassRoom, etc.
2. If the identifier consists on a single word, or part of a word, all letters are lower case.
E.g.: count, sum, cnt, city, name, student, num1, number, etc.

Java Lecture Notes 5 Halil Özmen


3. If the identifier consists on two or more words, the first letter of 2nd and subsequent words are
upper case, all other letters are lower case.
E.g.: aveCityPopulation, cityCount, sumTrucks, cntStu, cityName, studentId, etc.
4. If the identifier is a constant identifier, then all letter are in upper case.
final int MAXSTUDENT = 50;
final double PI = 3.141592653589793; // use Math.PI

1.6. White Space and Indentation


The following two Java programs that are identical to the above Java program have poor utilization of
white spaces and indentation.
It becomes quite difficult to "read" and "understand" a program if the white spaces and indentation are
poor.
// File: WelcomeJavaApp.java
// This application simply prints "Welcome to Java!" to standard output.

class WelcomeJavaApp Very bad


{
public static void main(String[] args){
white space and
System.out.println("Welcome to Java!"); indentation style
}
}

SUMMARY:
1. Java source files have the same name as the class name with the extension .java.
2. Every running Java program is placed in a class called "application class".
3. The Java codes of an application class are written in:
public static void main(String[] args) method.
4. Class names start with capital letter, variable and object names start with lower case letter.
5. Identifiers are case sensitive. For example abc, Abc and ABC are all different identifiers.
6. Comments are written after //, or between /* ... */.

2. Data and Expressions


2.1. Primitive Data Types
Java is a strongly typed language. Each data value is associated with a particular data type.
There are 8 primitive data types. These 8 primitive data types are numeric types. The names of the
eight primitive data types are:
byte short int long float double char boolean

There are both integer and floating point primitive types. Integer types have no fractional part; floating
point types have a fractional part. On paper, integers have no decimal point, and floating point types
do. But in main memory, there are no decimal points: even floating point values are represented with
bit patterns. There is a fundamental difference between the method used to represent integers and the
method used to represent floating point numbers.
Integer Primitive Data Types:
Type Size Range
byte 8 bits (1 byte) -128 to +127
short 16 bits (2 bytes) -32,768 to +32,767
int 32 bits (4 bytes) (about)-2 billion to +2 billion
long 64 bits (8 bytes) (about)-10E18 to +10E18

Floating Point Primitive Data Types:


Type Size Range
float 32 bits (4 bytes) -3.4E+38 to +3.4E+38
double 64 bits (8 bytes) -1.7E+308 to 1.7E+308

Java Lecture Notes 6 Halil Özmen


Examples:
int year = 2020;
double cats, pi = 3.141592653589793;
char topgrade, separator = ' ', newline = '\n', tab = '\t';
boolean flag = true, done = false;

2.2. Character Strings


A character string is an object in Java, defined by the class String.
A string literal can contain any valid characters and it is delimited by double-quotation characters.
Examples: "", "x", "C3PO", "-248", "Menekse cad. Lale sok. No: 14/22, Sevgi Mah., Antalya"
A string literal cannot be devided through program lines. The following string is not valid:
"Menekse cad. Lale sok. No: 14/22, Invalid
Sevgi Mah., Antalya"

String Concatenation:
Strings can be concatenated by using the plus sign (+). Strings are concatenated
String name = lastname + ", " + firstname; with + sign.
String address = "Menekse cad. Lale sok. No: 14/22, \n" +
"Sevgi Mah., Antalya";
When a string is too long to fit in one line in a program, it can be divided into smaller parts that
can be concatenated by "+" string concatenation operator.

Mind the difference between the following two Java statements. What are their outputs?
System.out.println("Total is " + 24 + 41); // concatenation
System.out.println("Total is " + (24 + 41)); // addition, then concatenation

2.3. Variables and Assignments


Identifiers:
The various words used when writing programs are called identifiers.
In Java, the identifiers can be composed of any combination of letters, digits, the underscore
character (_) and the dollar sign ($), but it cannot begin with a digit. (It cannot contain any
character not listed above. E.g.: space character and punctuation characters.)
Valid identifier examples: c3po, a77_4E, _4aT, $a70B, $, _0, _a, _$, $1, _1_, $X$, _x$
Invalid identifier examples: a7+e44, _4-aT, 7aa, beat.les, ab ba

Variables:
A variable is a name for a location in memory used to hold a data value.
A variable declaration instructs the compiler to reserve a portion of main memory space large
enough to hold a particular type of value and indicates the name used to refer to that location.
A variable can store only one value of its declared type. A new value overrides the old one.

Declaration:
The following "variable declaration" statement reserves space for an integer:
int keys;
The following "variable declaration" statement reserves space for an integer and stores 88 in it:
int keys = 88;
A variable declaration can have multiple variables of the same type declared in one statement:
int result, count = 0, limit = 80, number;

Assignment:
Assignment statements are used to assign values to variables.
Basic assignment statement format:
Identifier = Expression;

Java Lecture Notes 7 Halil Özmen


Examples:
sides = 4; // This is an assignment statement.
count = count + 1;
nextvalue = (max * 1.4) - (min / nextvalue);
// Use of assignment statements to change the value stored in a variable.
public class Geometry
{
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println("A heptagon has " + sides + " sides.");

sides = 10; // assignment statement


System.out.println("A decagon has " + sides + " sides.");

sides = 12; // another assignment statement


System.out.println("A dodecagon has " + sides + " sides.");
} // end of main
} // end of class Geometry

Constants:
Constants are identifiers and are similar to variables except that they hold a particular value for the
whole duration of their existence. Constants do not change value. Constants have a data type.
The reserved word final is used to declare constants. Constants are written all in capital letters.
final int MAX_OCCUPANCY = 487;

2.4. Operators and Expressions


An expression is a combination of one or more operators and operands that usually perform a
calculation.
The operands used in the operations might be variables, literals, constants, or other sources of data.

Arithmetic Operators: + - * / % (Remainder / modulus operator)


Increment / Decrement Operators: ++ --
count++; // equivalent to: count = count + 1;
Relational Operators: > >= < <= == !=
Logical Operators: && (and) || (or) ! (not)
Assignment Operators: = += -= *= /= %=
total += value; // equivalent to: total = total + value;
val %= temp + 8; // equivalent to: val = val % (temp + 8);

Operator Precedence: Precedence of some of the Java operators are:


Precedence Level Operator Operation Associates
1 [] () . L-R
2 ++ -- ! + - Increment, Decrement, Logical NOT,
R-L
Unary plus, Unary minus
3 * / % Multiplication, Division, Remainder L-R
4 + - + Addition, Subtraction, String Concatenation L-R
5 < <= > >= Relational Operators
6 == != Equality Operators
7 && Logical AND L-R
8 || Logical OR L-R
9 = += -= *= /= %= Assignment Operators R-L

Java Lecture Notes 8 Halil Özmen


2.5. Data Conversion
It is sometimes necessary to convert a data value of one type to another type. But we must be careful
that we don't lose information in the process. For example, suppose a short variable that holds the
number 1000 is converted to a byte value.
short value = 2400;
int result, sum = 40000, count = 24;
result = value; // Conversion through assignment
result = (int) value * 2; // Type Casting!
result = sum / value; // Conversion through promotion
double average = (double) sum / count; // TYPE CASTING!!

2.6. Simple Input


Scanner class:
The Scanner class, which is part of the standard Java class library, provides convenient methods for
reading input values of various types.
First a scanner object must be created. In Java, objects are created using the new operator, that
invokes a call to a special method called a constructor to set up the object.
Scanner kb = new Scanner(System.in);
After this statement, we have an object named kb which is of the Scanner class.
Unless specified otherwise, a Scanner object assumes that white space characters (spaces, tabs, new
lines) are used to separate the elements of the input, called tokens, from each other.
Some methods of the Scanner class:
Method Description
String next () Returns the next input token as a character string.
String nextLine () Returns all input remaining on the current line as a character string.
boolean nextBoolean () Returns the next input token as the indicated type.
byte nextByte ()
short nextShort () Throws InputMismatchException if the next token is
int nextInt () inconsistent with the type.
long nextLong ()
double nextDouble ()
float nextFloat ()
boolean hasNext () Returns true if the scanner has another token in its input.
boolean hasNextLine()
boolean hasNextInt()
boolean hasNextDouble()

// Echo.java Author: Lewis/Loftus


// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
import java.util.Scanner;

public class Echo


{
// Reads a character string from the user and prints it.
public static void main (String[] args)
{
Scanner kb = new Scanner (System.in);

System.out.print ("Enter a line of text: ");


String message = kb.nextLine();

System.out.println("You entered: \"" + message + "\"");


} // end of main
} // end of Echo

Java Lecture Notes 9 Halil Özmen


Exercises:
• Write a Java program that inputs a degree value in Fahrenheit, converts it to Celcius and outputs. Celcius =
(Fahrenheit - 32) / 1.8
• Write a Java program that inputs the radius of a circle, computes and outputs its perimeter and its area.
• Write a Java program that inputs the lengths of two consecutive sides of a rectangle, computes and outputs
its perimeter and its area.

SUMMARY:
1. There are 8 primitive (basic) data types: byte, short, int, long, float, double, char, boolean.
2. A character string is an object in Java, defined by the class String.
3. All variables and objects must be declared.
4. Basic assignment statement format is: identifier = expression;
5. For simple input, a Scanner object is used. Scanner kb = new Scanner(System.in);

3. Conditionals and Loops

3.1. Boolean Expressions


A Boolean expression is an expression used in programming languages that produces a Boolean
value when evaluated. A Boolean value is either true or false.

Equality and Relational Operators: used to compare two values of the same data type.
== equal to
!= not equal to
< less than Precedence of Operators
<= less than or equal to 1 [] () . L-R
> greater than 2 ++ -- Increment, Decrement,
>= greater than or equal to ! Logical NOT, R-L
+ - Unary plus, Unary minus
3 * / % Multiplication, Division,
Logical Operators: L-R
Remainder
! Logical NOT !a 4 + - + Addition, Subtraction, String
&& Logical AND a && b L-R
Concatenation
|| Logical OR a || b 5 < <= Relational Operators
> >=
Truth table of AND and OR operators: 6 == != Equality Operators
a b a && b a || b 7 && Logical AND L-R
false false false false 8 || Logical OR L-R
false true false true 9 = += -= *= Assignment Operators
R-L
true false false true /= %=
true true true true

Examples:
if (total == sum)
....
if (total != sum)
....
if (count > 20)
{
System.out.println("Count exceeded.");
}
if ((count < MAX) && !done)
{
System.out.println("Not completed yet.");
}

Java Lecture Notes 10 Halil Özmen


3.2. The if Statement
An if statement consists of the reserved word if, followed by a boolean expression (enclosed inside
parentheses), followed by a statement or a block statement.

if (count > MAX)


System.out.println("Limit exceeded."); condition
if (count > MAX) evaluated false
{
System.out.println("Limit exceeded."); true
}
if (count > MAX) statement(s)
{
System.out.println("Limit exceeded.");
}
Flowchart of an if statement

if (numBooks < stackCount + inventoryCount + duplicateCount)


{
........
}

if-else statement:
if (height <= MAX)
adjustment = 0;
else condition
evaluated false
adjustment = MAX - height;
if (firstCh != 'a')
{ true
count++; // increment count.
} statement(s) statement(s)
else
{
count /= 2; // count = count / 2;
} Flowchart of an if-else statement
if (count > MAXCOUNT)
{
System.out.println("Limit exceeded.");
}
else // (count <= MAXCOUNT)
{
count++; // increment count.
}

Nested if statement:
A nested if statement is an if-else statement that contains another if statement inside the if-block
or inside the else-block or inside both.
// Find minimum of three numbers:
if (num1 <= num2)
{
if (num1 <= num3)
min = num1;
else
min = num3;
}
else // (num1 > num2) thus num1 cannot be minimum
{
if (num2 <= num3)
min = num2;
else
min = num3;
}
Java Lecture Notes 11 Halil Özmen
// An alternative:
if (num1 <= num2 && num1 <= num3) //can't be: (num1<= num2 && <= num3)
{ min = num1; }
else if (num2 <= num3) // or else if (num2 <= num1 && num2 <= num3)
{ min = num2; }
else
{ min = num3; }

Exercise:
• Write a Java program to input a grade value and assigns letter grade according to predefined lower
limits. (Lower limits: 50 for D, 70 for C; 80 for B, 90 for A, F if below 50.)

3.3. Comparing Strings


Comparing strings: use equals() or compareTo() methods of string objects to compare strings.
Equality and Relational Operators (==, !=, >, >=, <, <=) can not be used to compare strings.
To check if two strings s1 and s2 are lexically equal, the method call "s1.equals(s2)" is used.
To compare two strings for being lexically greater or less than, "s1.compareTo(s2)" is used.
If s1 is lexically greater than s2, then the compareTo() method call returns a positive number (> 0).
If s1 is lexically less than s2, then this method call returns a negative number (< 0).
If s1 >= s2, then s1.compareTo(s2) >= 0 is true, if s1 <= s2, then s1.compareTo(s2) <= 0 is true.

Examine the examples below to see how it can be used.


String str1 = "software", str2 = "software";
if(str1.equals(str2))
{ System.out.println("Characters are same in strings."); }

String name1, name2;


// name1 and name2 have been assigned some strings...
int result = name1.compareTo(name2);
if (result < 0)
{ System.out.println(name1 + " comes before " + name2); }
else if (result == 0)
{ System.out.println("The names are equal."); }
else
{ System.out.println(name1 + " comes after " + name2); }

3.4. The switch Statement


The switch statement causes the executing program to follow one of several paths based on a single
value. The expression evaluated at the beginning of a switch statement must be of type int, byte,
short, char or String. It cannot be boolean, long or floating point value. The value of each case must
be a constant, it cannot be a variable or other expression.

switch (idChar)
{
case 'A':
aCount++; // same as: aCount = aCount + 1;
break;
case 'B':
bCount = bCount + 1; // same as: bCount++;
break;
case 'C':
cCount++;
break;
default:
System.out.println("Error in Identification Character.");
}

Java Lecture Notes 12 Halil Özmen


3.5. The for Statement
The for statement is a repetition statement that is particularly well initialization
suited for executing the body of a loop a specific number of times that
can be determined before the loop is executed, or when the start and
end values are defined.
condition
evaluated false
The structure of for statement:
for (initialization; condition; next_value) true
{ statement(s)
.... // for block
}
next value

Example:
// Prints the values from 1 to 7.
for(int count = 1; count <= 7; count++) Flowchart of a for statement
{
System.out.println(count);
}
// Computes sum of all positive two digit integer numbers:
int sum = 0;
for(int n = 10; n <= 99; n++)
{
sum += n;
}
// Counts three digit numbers that are divisible by 7:
int count = 0;
for(int n = 100; n < 1000; n++) // all 3-digit numbers
{
if (n % 7 == 0) // if n is divisible by 7,
count++; // then increment count.
}

Exercises:
• Write a Java program that inputs two integers, computes and outputs the sum of all integer
numbers between these two integers (including these two numbers).
• Write a Java program that inputs two integers, prints all integer numbers that ends with 72.
• Write a Java program that inputs an integer number, checks if the input number is a prime number
or not, and outputs the result as "... is a prime number." or "... is NOT a prime number.". Write a
function that checks if a given integer is prime number or not.
• Write a Java program that inputs an integer number, outputs its prime factors.
Eg: 184 = 2x2x2x23.
• Assume that an int variable holds a positive integer. Write a for loop that prints all positive divisors
of each number from 1 to this value. For example, if value is 4, it prints:
Divisors of 1: 1
Divisors of 2: 1 2
Divisors of 3: 1 3
Divisors of 4: 1 2 4
• Write a Java program that computes and outputs (by using for loop) the sum of the series

until a term that is smaller than 0.00001 is found.

Java Lecture Notes 13 Halil Özmen


3.6. The while Statement
A while statement is a repetition statement that is used to execute
condition
statements as long as a condition is true.
evaluated false
The structure of while statement:
true
while (condition)
{ statement(s)
.... // while block
}

Example: Flowchart of a while statement


// Prints the values from 1 to 7.
int count = 1;
while (count <= 7)
{
System.out.println("Counter: " + count);
count++;
}
// Input numbers until 0 (zero) is entered, print their sum:
int sum = 0;
Scanner kb = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = kb.nextInt(); // Read first number.
while(n != 0) // While input number is not zero,
{
sum += n; // Add number to sum
System.out.print("Enter a number: ");
n = kb.nextInt(); // Read next number.
}
System.out.print("Sum = " + sum);

Exercises:
• Input two integer numbers (first one is smaller than the second one), compute the sum of numbers starting
from the first till the second, output the sum. Use a while loop, not a for loop.
• Input an integer number, output the sum of its digits.
• Assume that an int variable holds a positive integer. Write a while loop that prints all of the positive divisors of
the value. For example if the value is 12, it prints:
Divisors of 12: 1 2 3 4 6 12
*
• Write a nested loop that outputs n lines so that the first line contains one asterix, the second line **
contains two asterixes, and so on (the n'th line will have n asterixes). ***
• Write a Java program that computes and outputs (by using while loop) the sum of the ****

series until a term that is smaller than 0.00001

is found.

Java Lecture Notes 14 Halil Özmen


3.7. The do Statement (do-while)
The do statement is similar to the while statement except that its statement(s)
condition is at the end of the loop body.

The structure of do statement: true condition


do evaluated
{
.... // do-while block
false
} while (condition);
Flowchart of a do statement
Example:
// Prints the values from 1 to 7.
int count = 0;
do
{
count++;
System.out.println(count);
} while (count < 7); // Attention: not (count <= 7)

Exercises:
• Write a do loop to get a sequence of positive integers from the user, using zero as sentinel value.
The program should output the sum of the numbers.

Nested Loops:
The body of a loop can contain another loop. This situation is called a nested loop. Keep in mind that
for each iteration of the outer loop, the inner loop executes completely.
Example: Triangle of asterisks
for (int r = 1; r <= 4; r++)
{
for (int c = 1; c <= r; c++)
System.out.print ("*");
System.out.println();
}
Example: How many times the string "Here again" get printed?
int count1, count2;
count1 = 1;
while (count1 <= 4)
{
count2 = 1;
while (count2 <= 8)
{
System.out.println("Here again");
count2++;
}
count1++;
}

Infinite Loops:
The programmer must be carefull not to make infinite loops.
int count = 1;
while (count != 50) // infinite loop
{
System.out.println(count);
count += 2;
} // This loop will never exit.

Java Lecture Notes 15 Halil Özmen


3.8. break and continue Statements

break statement:
The break statement causes immediately to terminate a loop.
The execution continues after the loop.
Java program segment Output
for(int j = 1; j < 11; j++) 1
{ 2
if(j >= 5) // if n is 5 or more, 3
break; // then quit the loop 4
System.out.println(j);
}
int k = 827419; 8274
while(k > 0)
{
if(k % 2 == 0) // If k is even,
break; // then break
k /= 10; // k = k / 10;
}
System.out.println(k);

continue statement:
The continue statement causes Java to skip the rest of the current iteration (stop the current iteration),
and continue with the next iteration.
for(int j = 1; j < 11; j++) // 1 2 3 ... 9 10 1
{ 2
if(j >= 3 && j <= 6) // if j is 3 to 6 7
continue; // then skip the rest of loop 8
System.out.println(j); 9
} 10

Java Lecture Notes 16 Halil Özmen


4. Methods
The methods in Java language are like the functions in Python, C and many other languages.
A method is a group of programming language statements that is given a name.
A method declaration specifies the code that is executed when the method is invoked.
Every method in a Java program is part of a particular class: either an application class or object class.

When a method is called, the flow of


control transfers to that method. Then, the main doThis helpMe
statements of that method are executed. ....
.... ....
When that method is done, control returns ....
.... ....
to the location where the call was made ....
.... ....
and execution continues. .... helpMe(); ....
obj.doThis();
The called method (the one that is .... ....
.... .... ....
invoked) might be part of the same class as ....
the calling method that invoked it. If the .... ....
....
called method is part of the same class,
only the method name is needed to invoke
it. If it is part of a different class, it is
invoked through the name of an object of The flow of control following method invocations
that other class.

The return statement


Methods may return a value (basic data) or an object (a reference to an object), or may not return
anything.
If a method does not return anything (it does not have return statement), then its type is "void".
If a method returns something, then its type is exactly the type of the thing it returns.
The return type specified in the method header can be a primitive type, class name, or the reserved
word void. A method that returns a value must have a return statement.
When a return statement is executed, control is immediately returned to the statement in the calling
method, and processing continues there.
A method that does not return a value does not usually contain a return statement.
It is usually not a good practice to use more than one return statement in a method, even though it is
possible to do so. In general, a method should have one return statement as the last line of the
method body.
Example method headers:
private static void printDivisors(int n)
private static int countDivisors(int n)
private static String repeatStr(String a, int n)

Parameters
The methods may get zero or more parameters.
A parameter is a value that is passed into a method when it is invoked. The parameter list in the
header of a method specifies the types of the values that are passed and the names by which the
called method will refer to those values.
The names of the parameters in the header of the method declaration are called formal parameters.
In an invocation, the values passed into a method are called actual parameters. The actual
parameters are also called the arguments to the method. The actual parameters can be literals,
variables, or expressions. If an expression is used as an actual parameter, it is fully evaluated before
the method call and the result is passed as the parameter.
When a method is called, the value in each actual parameter (argument) is copied and stored in
the corresponding formal parameter.
The types and the number of the actual parameters must be consistent with the specified types and
numbers of the formal parameters.
A method invocation and definition always give the parameter list in parentheses after the method
name. If there are no arguments, an empty set of parentheses is used.
Java Lecture Notes 17 Halil Özmen
Invocation
Method ch = myMethod (count, 12, "Hello the nice people of Earth");

public static char myMethod(int num1, int num2, String message)


Declaration

{
Method

int sum = num1 + num2;


char result = message.charAt (sum);
return result;
}
Passing arguments from the method invocation (call) to the declaration.

Local Data
The scope of a variable or constant is the part of a program in which a valid reference to that variable
can be made.
A variable can be declared inside a method, making it local data as opposed to instance data. Local
data has scope limited to only the method in which it is declared. A local variable simply does not exist
outside the method in which it is declared.
The formal parameter names in a method header serve as local data for that method. They don't exist
until the method is called, and they cease to exist when the method is exited.

Methods that does not return anything Methods that return value or object
private static void abc (...) private static String abc (...)
{ {
.... String str;
} .... // make str
return str;
}
Examples:
// Method call: // Method call:
abc(a, b); // a and b are integers int total = abc(a, b);
.... ....

// Print numbers from n1 to n2 // Returns sum of numbers from n1 to n2


private static void abc(int n1, int n2) private static int abc(int n1, int n2)
{ {
for (int j = n1; j <= n2; j++) int sum = 0;
{ System.out.print(j + " "); } for (int j = n1; j <= n2; j++)
System.out.println(); { sum += j; }
} return sum;
}
// Method call: // Method call:
char a = '*'; if (isPrime(k)) // k is positive int
int b = 7; ....
tri(a, b);
.... // Returns true if parameter is prime.
private static boolean isPrime(int n)
// Print triangle of c {
private static void tri(char c, int n) boolean prime = true;
{ for (int j = 2; j <= n/2; j++)
for (int r = 1; r <= n; r++) {
{ if (n % j == 0) // divisible by j
for (int k = 1; k <= r; k++) {
{ prime = false;
System.out.print(c); break;
} }
System.out.println(); }
} return prime;
} }

Java Lecture Notes 18 Halil Özmen


5. Using Classes and Objects

5.1. Packages
The Java language is supported by a standard class library.
A class library is a set of classes that supports the development of programs. A compiler or
development environment often comes with a class library. Class libraries can also be obtained
separately from internet or through third-party vendors. The classes in a class library contain methods
contain methods that are often valuable to a programmer because of the special functionality they
offer.
The String class, for instance, is not an inherent part of the Java language. It is part of the Java
standard class library (java.lang) that can be found in any Java development environment.
The class library is made up of several clusters of related classes, which are sometimes called Java
API's, or application programming interfaces.
The classes of the Java standard class library are grouped into packages. Each class is part of a
particular package. The String class, for example, is part of the java.lang package. The Scanner class
is part of the java.util package.
Package Description
java.lang General support; it is automatically imported into all Java programs.
java.util General utilities. Includes Scanner class and more.
java.applet Create programs (applets) that are easily transported across the Web.
java.awt Draw graphics and create graphical user interfaces;
AWT stands for Abstract Windowing Toolkit.
java.beans Define software components that can be easily combined into applications.
java.io Perform a wide variety of input and output functions.
java.math Perform calculations with arbitrarily high precision.
java.net Communicate accross a network.
java.rmi Create programs that can be distributed across multiple computers;
RMI stands for Remote Method Invocation
java.security Enforce security restrictions.
java.sql Interact with databases; SQL stands for Structured Query Language.
java.text Format text for output.
javax.swing Create graphical user interfaces with components that extend the AWT capabilities
javax.xml.parsers Process XML documents; XML stands for eXtensible Markup Language.

The import Declaration:


The classes of the java.lang package are automatically available for use when writing a Java program.
To use classes from any other package, however, we must either fully qualify the reference or use an
import declaration.
import java.util.Scanner;
import java.util.*;

5.2. Creating Objects


Objects are created by specifying their class and by using a constructor:
Class objectName = new Constructor(arguments);
creates an object
reference to object gives address of the created object

Consider the following two declarations:


int num; // variable of a basic data type
String name; // object from a class

Java Lecture Notes 19 Halil Özmen


The first declaration creates a variable that holds an integer value. The second declaration creates a
String variable that holds a reference to a String object. An object variable does not hold an object
itself, it holds the address of an object.
Initially, the two variables declared above don't contain any data, they are uninitialized.
num - (Integer variable exists, but it is uninitialized.)

name - (No String object actually exists yet!)

The following two assignment statements give values to the two variables declared above:
num = 24;
name = "Kaan Ekermen"; // name = new String("Kaan Ekermen");
After the new operator creates the object, a constructor is invoked to help set it up initially.
The new operator returns a reference to a newly created object.
A constructor is a special method that has the same name as the class.
num 24

name "Kaan Ekermen"

After an object has been instantiated, the dot operator is used to access (run) its methods.
count = name.length();
The length method does not take any parameters, but the parantheses are still necessary to indicate
that a method is being invoked. Some methods produce a value that is returned when the method
completes. The purpose of the length method of the String class is to determine and return the length
of the string (the number of characters it contains). For the string "Kaan Ekermen", the length method
returns 12.
The act of declaring the object reference variable and creating the object itself can be combined into
one step:
String title = new String("Java Software Solutions");
String title = "Java Software Solutions";
Character strings are so fundamental, there is a shortcut notation. We will frequently use this simplified
syntax.
String city = "Ankara";

Aliases
Suppose we have two integer variables, num1, initialized to 7, and num2, initialized to 12.
num1 7 num2 12

In the following statement, a copy of the value that is stored in num1 is stored in num2:
num2 = num1;
num1 7 num2 7

Now, consider the following object declarations:


String name1 = "Ingrid Bergman";
String name2 = "Dr. Alexander Fleming";
name 1
"Ingrid Bergman"
name 2
"Dr. Alexander Fleming"
Now suppose the following assignment statement is executed, copying the value name1 into name2.
name2 = name1;
name 1
"Ingrid Bergman"
name 2

The name1 and name2 reference variables are now aliases of each other, because they are two
names that refer to the same object.
Multiple reference variables can refer to the same object.

Java Lecture Notes 20 Halil Özmen


5.3. The String Class
Some of the useful methods of the String class are:
String (String str) Constructor: creates a new string object with the same characters as str.
int length () Returns the number of characters in this string.
char charAt (int index) Returns the character at the specified index. (Index starts with 0.)
boolean equals (String str) Returns true if this string contains the same characters as str (including case) and
false otherwise.Case sensitive equality check.
boolean equalsIgnoreCase Returns true if this string contains the same characters as str (without regard to
(String str) case) and false otherwise. Case insensitive equality check.
int compareTo (String str) Returns an integer indicating if this string is lexically before (a negative return
value), equal to (a zero return value), or lexically after (a positive return value) the
string str case sensitively.
int compareToIgnoreCase Returns an integer indicating if this string is lexically before (a negative return
(String str) value), equal to (a zero return value), or lexically after (a positive return value) the
string str case insensitively.
String concat (String str) Returns a new string consisting of this string concatenated with str.
String replace (char Returns a new string that is identical with this string except that every occurence
oldChar, char newChar) of oldChar is replaced by newChar.
String replace (String Returns a new string that is identical with this string except that every occurence
oldStr, String newStr) of oldStr is replaced by newStr.
String substring (int offset) Returns a new string that is a subset of this string starting at index offset.
String substring (int offset, Returns a new string that is a subset of this string starting at index offset and
int endIndex) extending through endIndex-1.
String toLowerCase() Returns a new string identical to this string except all uppercase letters are
converted to their lowercase equivalent.
String toUpperCase() Returns a new string identical to this string except all lowercase letters are
converted to their uppercase equivalent.
int indexOf (char ch) Returns the index of the first occurence of ch in this string.
Returns -1 if ch is not found.
int indexOf (String str) Returns the index of the first occurence of str in this string.
Returns -1 if str is not found.
int indexOf (char ch, int Returns the index of the first occurence of ch in this string starting from index
startIndex) position "startIndex". Returns -1 if ch is not found.
int indexOf (String str, int Returns the index of the first occurence of str in this string starting from index
startIndex) position "startIndex". Returns -1 if str is not found.
int lastIndexOf (char ch) Returns the index of the last occurence of ch in this string. Returns -1 if ch is not
found.
int lastIndexOf (String str) Returns the index of the last occurence of str in this string. Returns -1 if str is not
found.
int lastIndexOf (char ch, int Returns the index of the last occurence of ch in this string starting from index
fromIndex) position "fromIndex". Returns -1 if ch is not found.
int lastIndexOf (String str, Returns the index of the last occurence of str in this string starting from index
int fromIndex) position "fromIndex". Returns -1 if str is not found.
boolean contains(String str) Returns true if sequence of chars in str are found in this string, otherwise returns
false.
String[] split (String sep) Returns an array of strings that is made by splitting the string by string sep.
Example: String s = "Abc;1234;Klmnopq";
String[] parts = s.split(";"); // yields: "Abc" "1234" "Klmnopq"

Examples:
String name1 = "Yunus Emre", name2 = "Bertrand Russell", name3;
int len = name1.length(); // length of string
char c1 = name2.charAt(4); // Char at index position 4
int k = name1.compareTo (name2);
if (k < 0)
System.out.println(name1 + " comes before (smaller than) "+name2);
else if (k == 0)
System.out.println(name1 + " equals " + name2);
else
System.out.println(name1 + " comes after (greater than) "+ name2);
System.out.println("name1 in uppercase: " + name1.toUpperCase());
Java Lecture Notes 21 Halil Özmen
if (name1.equalsIgnoreCase("YUNUS EMRE")) // --> true
System.out.println(name1 + " is case insensitively equal to " +
"YUNUS EMRE");
name1 = name1.concat (", Mevlana"); // "Yunus Emre, Mevlana"
name3 = name2.replace('r', '='); // --> "Be=t=and Russell"
System.out.println("<" + name3.substring(3, 7) + ">"); // t=an

Exercises:
• Write a Java program that inputs a string and a character, counts and outputs the number of occurences of
the input character in the input string. (a) Case sensitive; (b) Case insensitive.
• Write a Java program that inputs a string and two characters, replaces all occurences of the first input
character with the second one, then outputs new string.
• Write a static method that takes two strings (str1, str2) as parameters, finds and returns the number of
occurences of str2 inside str1 case insensitively. Hint: use uppercase versions of both strings.

5.4. Character Methods


The character methods are static class methods, they are called as "Character.methodName(char)".

Method Description
boolean isLetter() Returns true if the specified char value is a letter.
boolean isDigit() Returns true if the specified char value is a digit.
boolean isLetterOrDigit() Returns true if the specified char value is a letter or a digit.
boolean isUpperCase() Returns true if the specified char value is uppercase.
boolean isLowerCase() Returns true if the specified char value is lowercase.
boolean isWhitespace() Returns true if the specified char value is white space.
char toUpperCase() Returns the uppercase form of the specified char value.
char toLowerCase() Returns the lowercase form of the specified char value.

Examples: Count number of upper case letters, lower case letters and digits.
String s = "Some of perfect numbers are 6, 28, 496, 8128.";
int digits = 0, upcase = 0, lowcase = 0; // Counts.
for (int j = 0; j < s.length(); j++) // Loop for indexes.
{
if (Character.isUpperCase(s.charAt(j))) // if uppercase letter
{ upcase++; } // then increment its count
if (Character.isLowerCase(s.charAt(j))) // if lowercase letter
{ lowcase++; } // then increment its count
if (Character.isDigit(s.charAt(j))) // if numeric character
{ digits++; } // then increment its count
}

5.5. The Math Class


The Math class provides a large number of basic mathematical functions that are often helpful in
making calculations. The Math class is defined in java.lang package of Java standard class library.
An example is below:
value = Math.abs(total) + Math.pow(max, 4);
Math.PI is the pi number: 3.141592653589793
Math.E is the e number: 2.718281828459045
Several of Math class methods are listed below.
int abs (int num) Returns the absolute value of num.
double abs (double num)
double pow (double num, double Returns the value num raised to the specified power.
power) numpower
double sqrt (double num) Returns the square root of num, which must be positive.
int round(double or float) Returns the closest integer value. 6.499 => 6, 6.5 => 7
double floor (double num) Returns the floor of num, which is the largest whole number less
than or equal to num. 6.0 => 6.0, 6.001 => 6.0, 6.99 => 6.0

Java Lecture Notes 22 Halil Özmen


double ceil (double num) Returns the ceiling of num, which is the smallest whole number
greater than or equal to num. 6.0 => 6.0, 6.001 => 7.0, 6.99 => 7.0
double exp (double power) Returns the value e (2.71828182) raised to the specified power.
epower
double cos (double angle) Returns the angle cosine, sine, or tangent of angle, which is
double sin (double angle) measured in radians.
double tan (double angle)
double acos (double num) Returns the arc cosine, arc sine, or arc tangent of num.
double asin (double num)
double atan (double num)
double log(double num) Returns the natural logarithm (base e) of double value
double log10(double num) Returns the base 10 logarithm of double value
double random () Returns a random number between 0.0 (inclusive) and
1.0 (exclusive).
double circleArea = Math.PI * radius * radius;
double sphereVolume = 4.0 / 3.0 * Math.PI * Math.pow(radius, 3);
double surfaceArea = 4 * Math.PI * radius * radius;
System.out.println("sqrt(19.36) => " + Math.sqrt(19.36));
for (int j = 0; j <= 10; j++)
{
double n = 40 + 0.1 * j;
System.out.print("floor(" + n + ") => " + Math.floor(n));
System.out.print(" ceil(" + n + ") => " + Math.ceil(n));
System.out.println(" round(" + n + ") => " + Math.round(n));
}

Exercise:
• Write a Java program (Quadratic) that inputs the three coefficients a, b and c of a quadratic equation (ax2 +
bx + c), then computes and outputs the roots of this equation if they are not complex numbers (i.e. (b2 - 4ac)
>= 0). roots = (-b ± √(b2 - 4ac) ) / 2a

5.6. The Random Class


The Random class, which is part of the java.util package, represents a pseudo-random number
generator. A random number generator picks a number at random out of a range of values.
Some of the useful methods of the Random class are:
Random () Constructor: creates a new pseudorandom number generator.
int nextInt () Returns a random number that ranges over all possible int values
(positive and negative).
int nextInt (int num) Returns a random number in the range 0 to (num-1).
double nextDouble () Returns a random number between 0.0 (incusive) and 1.0 (exclusive).

import java.util.Random;
Random rand = new Random (); // Create a random generator object
n1 = rand.nextInt(10); // generates random number from 0 to 9.
n2 = rand.nextInt(10) + 1; // random number from 1 to 10.
n3 = rand.nextInt(100) + 1; // random number from 1 to 100.
n4 = rand.nextInt(61) + 40; // 40 to 100
n5 = rand.nextInt(21) - 10; // -10 to +10
x1 = rand.nextDouble(); // 0.0 to 0.9999999999
x2 = rand.nextDouble() * 8; // 0.0 to 7.9999999999

Exercises:
• Write a Java program that inputs an integer, let's call it num, and outputs num times random dice values
(from 1 to 6).
• Write a Java program that generates a random number in 1-100 range, then inputs numbers from user till the
user correctly guesses the generated number. After each input, the program outputs "My number is greater
than yours." or "My number is less than yours." or "You found my number at the ..th try.".

Java Lecture Notes 23 Halil Özmen


5.7. Formatting Output
The printf Method:
In addition to print and println, the System class has another output method called printf, which allows
the user to print a formatted string containing data values.
System.out.printf (".... format string....", variables/objects)
Example: System.out.printf ("ID: %5d\tName: %s\n", id, name);
Type Format specifiers Examples  Output
int %d %nd %0nd %-nd ("%d %4d %04d %-4d", 24, 24, 24, 24)  24 __24 0024 24__
double %f %.nf %m.nf ("%f %.2f %8.2f", 2.4, 2.4, 24.246)  2.4 2.40 ___24.25
String %s %ns %-ns ("%s %6s %-6s", "Ant", "Ant", "Ant")  Ant ___Ant Ant___

The String.format() Method:


Same format specifiers can be used to create formatted strings. String.format returns a string.
String.format(".... format string....", variables/objects)
String s = String.format("ID: %5d Name: %-20s Dept: %s", id, name, dept);

NumberFormat Class:
The NumberFormat class and the DecimalFormat class are used to format information so that it looks
appropriate when printed or displayed. They are both part of the Java standard class library and are
defined in the java.text package.
The NumberFormat class provides generic formatting capabilities for numbers. There is no need to
instantiate a NumberFormat object by using the new operator. Some methods of the NumberFormat:
String format (double number) Returns a string containing the specified number formatted
according to this object's pattern.
static NumberFormat Returns a NumberFormat object that represents a currency format
getCurrencyInstance () for the current locale.
static NumberFormat Returns a NumberFormat object that represents a percentage
getPercentInstance () format for the current locale.

Sample usage: (Examine Purchase.java program on pages 160-161 in the textbook.)


import java.text.NumberFormat;
double total, incRate = 0.04;
NumberFormat curFmt = NumberFormat.getCurrencyInstance();
NumberFormat perFmt = NumberFormat.getPercentInstance();
System.out.println("... " + curFmt.format(total));
System.out.println("... " + perFmt.format(incRate));

DecimalFormat Class:
The DecimalFormat class is instantiated using the new operator. Its constructor takes a string that
represents the pattern that will quide the formatting process. Then the format() method can be used to
format a particular value. Some methods of the DecimalFormat class:
DecimalFormat (String pattern) Constructor: creates a new DecimalFormat object with the
specified pattern.
void applyPattern (String pattern) Applies the specified pattern to this DecimalFormat object.
String format (double number) Returns a string containing the specified number formatted
according to the current pattern.

Sample usage:
import java.text.DecimalFormat;
// Round the output to three decimal places:
DecimalFormat fmt1 = new DecimalFormat ("0.###");
// Round the output to four decimal places:
DecimalFormat fmt2 = new DecimalFormat ("0.####");
System.out.println("Area : " + fmt1.format(area));
System.out.println("Volume: " + fmt2.format(volume));

Java Lecture Notes 24 Halil Özmen


5.8. File Input and Output

File class:
The File class provides a constructor to create a file handle. This file handle is then used by
various file class methods to access the properties of a specific file or by file stream constructors
to open files.
File myFile = new File ("a.txt");

File Streams:
File streams are primitive streams whose sources or destinations are files. Both byte [8-bit]
(FileInputStream / FileOutputStream) and character [16-bit] (FileReader / FileWriter) quantities
can be used. Streams are opened when constructed. Some of the constructors are:
8-bit 16-bit
FileInputStream(fileObj) FileReader(fileObj)
FileInputStream(FilePath[,append_flag]) FileReader(filePath[,append_flag])
FileOutputStream(fileObj) FileWriter(fileObj)
FileOutputStream(FilePath[,append_flag]) FileWriter(filePath[,append_flag])

Reading from a text file:


For basic reading from character files (text files), the Scanner class can be used together with a
File object. To open a file stream:
Scanner fileScan = new Scanner (new File(fileName));
Then the file can be read as input is taken from keyboard with a Scanner object. The Scanner
methods like nextInt(), nextLine(), nextDouble(), ..., etc. can be used to read from text file.
String line = fileScan.nextLine(); // read a line from text file
int num = fileScan.nextInt(); // read next integer from text file
When reading the file is completed, the file has to be closed.
fileScan.close(); // close the text file
Example Java program that reads from a text file:
// File: FileRead1.java Halil Özmen
import java.util.*;
import java.io.*;

public class FileRead1


{
public static void main (String[] args) throws IOException
{
Scanner kb = new Scanner (System.in);
// Input file name:
System.out.print ("Enter file name: ");
String fileName = kb.nextLine();
kb.close();

int n = readFile(fileName); // Read and display file


System.out.printf ("\nNumber of lines in the file: %d\n", n);
} // end main

private static int readFile (String fname)


throws FileNotFoundException
{
// Open file:
Scanner fileScan = new Scanner (new File(fname));
int numLines = 0;
System.out.printf ("Contents of file %s:\n", fname);
// Until there is something in the file, read it.
while (fileScan.hasNextLine())
{
Java Lecture Notes 25 Halil Özmen
String line = fileScan.nextLine();
numLines++;
System.out.println(line);
}
fileScan.close();
return numLines;
}
} // end FileRead1

Writing to a text file:

Class PrintWriter
PrintWriter supports the print( ), println( ) and printf() methods for all types including Object.
Thus, these methods can be used in the same way as they have been used with System.out.
If an argument is not a simple type, the PrintWriter methods call the object's toString( ) method
and then print the result.

Class FileWriter
The FileWriter is a class used for writing character files (text files). The constructors of this class
assume that the default character encoding and the default byte-buffer size are acceptable. To
specify these values, construct an OutputStreamWriter on a FileOutputStream.

Example Java program that writes to a text file:


// File: A_FileWrite_1.java
// Write to file

import java.util.Scanner;
import java.io.*;

public class A_FileWrite_1


{
public static void main (String[] args) throws IOException
{
Scanner kb = new Scanner(System.in);
// Input file name:
System.out.print("Enter file name: ");
String fileName = kb.nextLine();
kb.close();

// Open file for writing:


PrintWriter writer = new PrintWriter(fileName);

// Write 10 lines into file:.


for(int num = 1; num <= 10; num++)
{
writer.println("Line " + num);
// writer.printf("Line %04d\n", num);
}
writer.close();
} // end main
} // end A_FileWrite_1

Java Lecture Notes 26 Halil Özmen


6. Arrays and ArrayList

6.1. Arrays
An array is a simple but powerful programming language construct used to group and organize data.
When writing a program that manages a large amount of information, such as a list of 100 names, it is
not practical to declare separate variables for each piece of data. Arrays solve this problem by letting
us declare one variable that can hold multiple, individually accessible values.
An array is a list of values. Each value is stored at a specific, numbered position in the array. The
number corresponding to each position is called an index or a subscript.

6.1.1. Declaring and Using Arrays


An array cannot hold data of different types. An array can be set up to hold any primitive data type or
any object (class) type.
In Java, arrays have fixed size that cannot be changed, and array indexes always begin at zero.
In Java, arrays are objects. To create an array, the reference to the array must be declared.
int[] heights = new int[12]; // Declare an array of 12 integers
double[] nums = new double[1000]; // Declare an array of 1000 doubles
String[] names = new String[10]; // Declare an array of 10 strings

Array size: .length attribute gives the size of the array. Example: heights.length
The size of an array cannot be changed.

[ ] is index operator, and it has the highest precedence among all Java operators.

The array shown below has 12 elements, indexed from 0 to 11.


indexes: 0 1 2 3 4 5 6 7 8 9 10 11
array elements: 167 180 170 147 162 154 192 174 180 170 164 172

Sample statements using array elements:


heights[2] = 172;
heights[count] = feet * 30;
int average3 = (heights[0] + heights[1] + heights[2]) / 3;
System.out.println("The middle value is " + heights[MAX/2]);

The iterator version of the for loop can be used to get all the elements of an array. This for loop cannot
be used to change elements of an array.
for (<dataType> variable : <arrayName>)
Example: (Find the sum of all values of the array arr.)
int sum = 0;
for (int n : arr) // This for loop type is used to get all elements of an array
{ sum += n; } // The value of every element is added to sum

Sample Java program segment that creates an array:


final int LIMIT = 8, MULTIPLE = 10;
int[] arr = new int[LIMIT];
// Set the array values:
for (int index = 0; index < arr.length; index++) // all indexes
{ arr[index] = (index + 1) * MULTIPLE; }
arr[4] = 88; // Change value of an array element.
0 1 2 3 4 5 6 7
After the array is declared: arr ---> -- -- -- -- -- -- -- --
0 1 2 3 4 5 6 7
After for loop: arr ---> 10 20 30 40 50 60 70 80
0 1 2 3 4 5 6 7
After assignment to an element:
arr ---> 10 20 30 40 88 60 70 80

Java Lecture Notes 27 Halil Özmen


Bounds Checking
The index operator performs automatic bounds checking, which ensures that the array index is
in range for the array being referenced. The number of elements in an array is stored in the
"length" constant (which is a public constant, therefore can be referenced directly).

Printing array elements on same line:


for(int j = 0; j < arr.length; j++)
{ System.out.print(arr[j] + " "); }
for(int n : arr)
{ System.out.print(n + " "); }

Alternate Array Syntax:


int[] grades = new int[100];
int grades[] = new int[100];

Initializer List
When an initializer list is used, the new operator is not used. The size of the array is determined
by the number of items in the initializer list.
int[] scores = {87, 102, 89, 74, 92, 96, 84, 99}; // size: 8
char[] vowels = {'A', 'E', 'I', 'O', 'U'}; // size: 5

Arrays as Parameters
An entire array can be passed as a parameter to a method. Because an array is an object, when
an entire array is passed as a parameter, a copy of the reference to the original array is passed.
Any changes done to an array passed as parameter to a method changes the
actual array in the calling method.

6.1.2. Arrays of Objects


When objects are stored in an array, each element is a separate object.
An array of objects is really an array of object references.
String[] words = new String[4];
words[0} = "love";
words[1} = "peace";
words[2} = "compassion";

Initially, the array looks like this. Array after the assignments:

words ─ words "love"


─ "peace"
─ "compassion"
─ ─

After a few String objects are created and put in the array, it might look like the one at the right.
During the declaration, an initializer list can be used to populate an array of objects.
Examples:
String[] verbs = {"sleep", "eat", "laugh", "play", "work", "dance"};
Grade[] grades =
{
new Grade("A", 95), new Grade("A-", 90),
new Grade("B+", 85), new Grade("B", 80), new Grade("B-", 75),
new Grade("C+", 70), new Grade("C", 65), new Grade("C-", 60),
new Grade("D+", 55), new Grade("D", 50), new Grade("F", 0)
};

Java Lecture Notes 28 Halil Özmen


6.2. Two-Dimensional Arrays
Multidimensional Arrays
An array can have one, two, three, or even more dimensions.
An array with more than one dimension is called a multidimensional array.
Java does not directly support multidimensional arrays with more than 2 dimensions. Therefore
int[][][] cannot be used to declare a 3-dimensional array.

A two-dimensional array has values in two dimensions, which are often thought of as the rows and
columns of a table (or matrix).
int[][] board = new int[8][8]; // 8 x 8 matrix
double[][] mat = new double[10][4]; // 10 x 4 matrix
String[][] names = new String[24][2]; // 24 x 2 matrix
An initializer list can be used to instantiate a two-dimensional array.
int[][] mtrx = { {8, 2, 7, 7},
{2, 4, 3, 4},
{7, 5, 2, 4} };

Each row of a multidimensional array in Java can be of different lengths, these arrays are called
jagged arrays. See: https://www.geeksforgeeks.org/jagged-array-in-java/
int[][] ja = { {1, 2, 3}, {4, 5, 6, 9}, {7} };
System.out.println("Length of row 1: " + ja[0].length); // 3
System.out.println("Length of row 2: " + ja[1].length); // 4
System.out.println("Length of row 3: " + ja[2].length); // 1

One dimensional Two dimensional


column indexes: 0 1 2 3
index 0 row index 0
index 1 row index 1
index 2 row index 2
index 3 row index 3

Brackets are used to represent each dimension in the array.


int[][] table = new int[4][8];
for (int row = 0; row < table.length; row++)
{
for (int col = 0; col < table[row].length; col++)
{ table[row][col] = (row + 1) * 10 + col + 1; }
}
The above Java statements produces a two-dimensional array that has the following contents:
0 1 2 3 4 5 6 7
0 11 12 13 14 15 16 17 18
1 21 22 23 24 25 26 27 28
2 31 32 33 34 35 36 37 38
3 41 42 43 44 45 46 47 48

To print this array, we may write the following:


for (int row = 0; row < table.length; row++)
{
for (int col = 0; col < table[row].length; col++)
{ System.out.print(table[row][col] + "\t"); }
System.out.println();
}

Java Lecture Notes 29 Halil Özmen


6.3. Variable Length Parameter Lists
Examine the following function calls to the same function average():
ave1 = average (42, 74, 24);
ave1 = average (7, 36, 41, 84, 8, 26, 40, 14);
Java provides a way to define methods that accept variable length parameter lists. By using a special
syntax in the formal parameter list of the method, the method can be defined to accept any number of
parameters. The parameters are automatically put into an array for easy processing in the method.
public static double average (int a, int ... list) // int[] list
{
double result = 0.0;
if (list.length != 0)
{
int sum = 0;
for (int num : list)
{ sum += num: }
result = (double)sum / list.length;
}
return result;
}

Example that has variable length of object parameters:


public static void printGrades (Grade ... grades)
{
for (Grade letterGrade : grades)
{ System.out.println(letterGrade); }
}

A method that accepts a variable number of parameters, can also accept other parameters.
The varying parameters must come last in the formal arguments.
A single method cannot accept two sets of varying parameters.

public static void test (int count, String name, double ... nums)
{
// whatever
}

Exercises:
1. Fill the main (or secondary) diagonal of a 2-D array with a value, and the rest with another value.
2. Fill the upper and lower parts of main (or secondary) diagonal with some values. E.g. upper part
with the sum of indices and the lower part with the product of indices.
3. Perform matrix multiplication. E.g. 4x2 matrix multiplied with 2x3 matrix.
4. Write a static method that gets a 2-D array as parameter and fills the first row of this 2-D array
with random values from 100 to 199, the second row with random values from 200 to 299, the
third row with random values from 300 to 399, and so on.
5. Write a static method that gets as parameters a 2-D array of strings and a string, computes and
returns the number of occurences of the given string (2nd parameter) in the 2-D array.
6. Write a static method that gets as parameters two integer numbers (m, n), creates and returns a
2-D array (of size m x n) of integers filled with random numbers.

Java Lecture Notes 30 Halil Özmen


6.4. The ArrayList Class
The ArrayList class is part of the java.util package of the Java standard class library.
The difference between a usual array and an ArrayList object is that a usual array has a fixed size,
whereas an ArrayList object dynamically grows and shrinks as needed.
A data element can be inserted into or removed from any location (index) of an ArrayList object with a
single method invocation.
Unless specified otherwise, an ArrayList is not declared to store a particular type. That is, an ArrayList
object stores a list of references to the Object class, which means that any type of object can be
added to an ArrayList.
Because an ArrayList stores references, a primitive (basic) value must be stored in an appropriate
wrapper class in order to be stored in an ArrayList.

Specifying an ArrayList Element Type


The methods of the ArrayList class are designed to accept references to the Object class as
parameters, thus allowing a reference to any kind of object to be passed toit. Thus, by default, an
ArrayList can store any type of object.
An implication of this implementation is that the remove method's return type is an Object reference. In
order to retrieve a specific object from the ArrayList, the returned object must be cast to its original
class.
An ArrayList can be defined to accept particular types of objects.
The following Java statements create ArrayList's that can have elements of the same type.
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Double> doubles = new ArrayList<Double>();
ArrayList<Character> chars = new ArrayList<Character>();
ArrayList<String> strings = new ArrayList<String>();
The following line of code creates an ArrayList object called cs102 that will store Student objects.
ArrayList<Student> cs102 = new ArrayList<Student>();
Given this declaration, the Java compiler will not allow an object to be added to cs102 unless it is a
Student object (or one of its descendants through inheritence).
Declaring the element type of an ArrayList is usually a good idea because it adds a level of type-
checking that we otherwise wouldn't have. It also eliminates the need to cast (type cast) an object into
its true type when it is extracted from the ArrayList.

Some methods of the ArrayList class:


ArrayList() constructor: creates an initially empty list.
int size() Returns the number of elements in this list.
boolean add (Object obj) Appends (adds) the specified object to the end of the list.
void add (int index, Object obj) Inserts the specified object into the list at the specified index.
boolean addAll (ArrayList a) Appends the elements of the specified list to the end of the list.
boolean addAll (int index, Inserts the elements of the specified list into the list at the specified
ArrayList a) index.
Object get (int index) Returns the element at the specified index in this list without removing
it. ATTENTION: The returned object has to be type casted.
Object set(int index, Object Replaces the element at the specified position (index) in this list with
obj) the specified element.
boolean contains (Object obj) Returns true if this list contains the specified object
int indexOf (Object obj) Returns the index of the first occurence of the specified object.
Returns -1 if not found.
Object remove (int index) Removes the element at the specified index in this list and returns it.
ATTENTION: The returned object has to be type casted.
void clear() Removes all elements from this list.
boolean isEmpty () Returns true if this list contains no elements.

Java Lecture Notes 31 Halil Özmen


ArrayList examples:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(78); list.add(46); list.add(94); list.add(67);
list.add(83); list.add(70); list.add(92); list.add(83);
list.add(57); list.add(61);
System.out.println(list);
list.add(4, 80); // insert element to index 4
int k = list.indexOf(83); // Get index of 1st occurence of 83
if (k != -1) // If found, then
{ list.remove(k); } // Remove this found element.

ArrayList<Integer> list2 = new ArrayList<Integer>(


Arrays.asList(87, 68, 44, 71, 95, 72, 80, 36, 74, 85));

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


band.add ("Paul"); // add element to end
band.add ("Pete"); // add element to end
band.add ("John"); // add element to end
band.add ("George"); // add element to end
System.out.println(band);

int location = band.indexOf("Pete"); // find index


band.remove (location); // delete element at index
System.out.println(band);
band.add(2, "Ringo"); // insert element to index
System.out.println(band);
System.out.println("Size of the band: " + band.size());

IMPORTANT: When an element is deleted from an ArrayList, the list elements "collapses" so that
the indexes are kept continuous for the remaining elements. Likewise, when an element is inserted at
a particular point, the indexes of the other elements are adjusted accordingly.

Processing the elements of ArrayList:


// Print elements of an ArrayList of integers on separate lines.
private static void printAL(ArrayList<Integer> list)
{
for (int j = 0; j < list.size(); j++)
{ System.out.println(list.get(j)); }
}
// Count elements of an ArrayList of integers in a given range.
private static int countRange(ArrayList<Integer> list, int n1, int n2)
{
int count = 0;
for (int j = 0; j < list.size(); j++)
{ if(list.get(j) >= n1 && list.get(j) <= n2)
{ count++; }
}
return count;
}

ArrayList Efficiency
The ArrayList class is implemented using an array. That is, the ArrayList object stores an array of
Object references. The methods provided by the class manipulate that array so that indexes remain
continuous as elements are added and removed.
When an element is inserted into an ArrayList, all of the elements at higher indexes are copied into
their new locations to make room for the new element. If elements are added to or removed from the
end of an ArrayList, its efficiency is not affected. But if elements are added to and/or removed from the
front part of a long ArrayList, a huge amount of element copying will occur (causing performance
degradation).

Java Lecture Notes 32 Halil Özmen


7. Writing Object Classes
private String name;
private int size; Attribute
7.1. Classes and Objects private char category; (Data)
private double weight; declarations
A class is a blueprint of an object. The class represents
the concept of an object, and any object created from that
class is a realization (instance) of that concept.
For example, the Student class represents the general
concept of a student, and every object created from that Method
class represents an actual student attending the school. In declarations
a university, we would have one Student class and
thousands of Student objects.
Each object has a state, which is defined by the values of
its attributes. The attributes may also be called fields.
Figure 7.1. The members of a class:
And each object has behaviours, which are defined by
data and method declarations.
the operations associated with that object.
A class defines the attributes and the operations for the objects of that class.

Table 6.1. Examples of classes and some possible attributes and operations
Class Attributes (Data) Operations
Student StudentID Set address
Name Set department
Address Compute GPA
Department
GPA
Flight Airline Set airline
Flight number Set flight number
Origin city Set origin city
Destination city Set destination city
Current status Set status
Employee Name Set department
Department Set title
Title Set salary
Salary Compute bonus
Performance Compute taxes

7.2. Anatomy of a Class


A class has two main parts:
• Object attributes definitions which are definitions the data that will exist in each object created
from this class,
• Methods definitions which are implementations of operations on the objects of this class.

The object class methods can be categorized into several types:


• Constructor(s): these methods are used to create objects.
public Person(String name, int birthyear)
{ this.name = name;
this.birthyear = birthyear; }
• Accessor (get) Methods: these type of methods are used to access (get) the attributes of objects.
public double getRadius()
{ return radius; }
• Mutator (set) Methods: these type of methods are used to modify (set) the attributes of objects.
public void setName(String name)
{ this.name = name; }
• Operation Methods: these type of methods are for operations done by or on objects and modifies
some of the attributes of objects.

Java Lecture Notes 33 Halil Özmen


• Support Methods: these types of methods are usually called from other methods in the class and
cannot be called from outside the class.

Assume we want to write a Java program that uses dice, and we want to write a class called Die from
which our program will create objects. With the objects of this Die class, the program will be able to:
• create a new object (constructor),
• set face value (mutator / set method),
• get face value (accessor / get method),
• roll (randomly assign a value from 1 to 6),
• get string represention of the die's face value.
Thus, we will have the following methods in the Die class:
Die () Constructor: sets the initial value of the die to 1.
void setFaceValue (int value) Mutator: Sets the face value of the die to the specified value.
int getFaceValue () Accessor: Returns the current face value of the die.
void roll () Rolls the die by setting the face value to a random number in the
appropriate range.
String toString () Returns a string representation of the die indicating its current face
value.

The Die class source code:


// Die.java Author: Lewis/Loftus

public class Die


{
private final int MAX = 6; // maximum face value constant
private int faceValue; // current value showing on the die

// Constructor: Sets the initial face value.


public Die()
{
faceValue = 1;
}

// Face value accessor.


public int getFaceValue()
{ return faceValue; }

// Face value mutator.


public void setFaceValue (int value)
{ faceValue = value; }

// Rolls the die and returns the result.


public void roll()
{
faceValue = (int)(Math.random() * MAX) + 1; // random 1 to 6
}

// Returns a string representation of this die.


public String toString()
{
return Integer.toString(faceValue);
// return "" + faceValue;
}
} // end of class Die

Java Lecture Notes 34 Halil Özmen


Instance Data
Note that in the Die class, the constant MAX and the variable faceValue are declared inside the class,
but not inside any method. The location at which a variable is declared defines its scope, which is the
area within a program in which that variable can be referenced. By being declared at the class level
(not within a method), these variables and constants can be referenced in any method of the class.
Attributes such as the variable faceValue are called instance data, because new memory space is
reserved for that variable every time an instance of the class is created.

die1 facevalue 4
die2 facevalue 2

The die1 and die2 reference variables point to (that is, contain the address of) their respective Die
objects. Each object contains a faceValue variable with its own memory space. Thus each object can
store different values for its instance data.

The this Reference


The this reserved word in Java allows an object to refer to itself.
Let's examine the class Person:
public class Person
{
private String name;
private int birthYear;
private String address;

public Person (String nameP, int byear)


{
name = nameP;
birthYear = byear;
address = "";
}
....
}

The constructor of the Person class can also be written as:


public class Person
{
private String name;
private int birthYear;
private String address;

public Person (String name, int birthYear)


{
this.name = name;
this.birthYear = birthYear;
address = "";
}
....
}

Similarly, this keyword can also be used in mutators and other methods to refer to the members of
the current object.

Java Lecture Notes 35 Halil Özmen


UML Class Diagrams
UML diagrams are used to visualize relationships among classes and objects.
UML stands for the Unified Modelling Language, which has become the most popular notation for
representing the design of an object-oriented program.
A UML class diagram showing the classes involved in the RollingDice program:
RollingDice Die
-faceValue : int

main (args: String [] ) : void +roll() : int


+setFaceValue (int value) : void
+getFaceValue() : int
+toString() : String

7.3. Constructors, Mutators, Accessors


Constructors
A constructor is similar to a method that is invoked when an object is instantiated. When we define a
class, we usually define a constructor to help us set up the class. In particular, we often use a
constructor to initialize the variables associated with each object.
A constructor differs from a regular method in two ways:
• The name of the constructor is the same name as the class;
• A constructor cannot return a value and does not have a return type specified in the method
header. Not even void shall be put in the constructor header.
Generally, a constructor is used to initialize the newly instantiated object.
Every class need not have a constructor.
Some classes may have more than one constructors.
Constructors do not have a return type and therefore cannot return a value. A common mistake is to
put a void return type on a constructor. If a function has void type, it cannot be a constructor, therefore
it cannot be invoked as a constructor.
// Mutator: name
Mutators (set methods - setters) public void setName(String n)
{ name = n; }
A mutator method changes a particular attribute.
Their type is void. They contain an assignment statement that assigns
the parameter to an attribute. // Accessor: name
Mutator method names have the form setX, where X is the name of public String getName()
the attribute they are setting. Example: setHeight(). { return name; }

// Accessor: height
Accessors (get methods - getters) public double getHeight()
An accessor method returns the value of an attribute. { return height; }
They contain only a return statement. Their type is the same type as their returned attribute.
Accesssor method names have the form getX, where X is the name of the attribute to which it
provides access. Example: getHeight().

7.4. Encapsulation Object


An object should be self-governing. That is, the instance Interface
data of an object should be modified only by that object. Client
For example, the methods of the Die class should be solely Methods
responsible for changing the value of the faceValue
variable. Code outside of a class should not be able to
"reach in" and change the value of a variable that is
declared inside that class. This characteristic is called Data
encapsulation.

Java Lecture Notes 36 Halil Özmen


Visibility Modifiers
Some of the Java modifiers are called visibility modifiers because they control access to the members
of a class. The reserved words public and private are visibility modifiers that can be applied to the
variables and methods of a class.
If a member of a class has public visibility, it can be directly referenced from outside of the object.
If a member of a class has private visibility, it can be used anywhere inside the class definition, but
cannot be referenced externally.
A third visibility modifier, protected, is relevant only in the context of inheritance.
Public variables violates encapsulation. Instance data should be defined with private visibility. Data
that is declared as private can be accesses only by the methods of the class.
The visibility that is applied to a method depends on the purpose of that method. Methods that provide
services to the client must be declared with public visibility, so that they can be invoked by the client.
These methods are sometimes referred to as service methods. A private method cannot be invoked
from outside the class. The only purpose of a private method is to help the other methods of the class
do their job. Therefore they are sometimes referred to as support methods.

The table below summarizes the effects of public and private visibility of both variables and methods.
public private

Attributes Violate Enforce


Variables encapsulation encapsulation

Provide services Support other


Methods
to clients methods in the class

7.5. Inheritance
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
• superclass (parent) - the class being inherited from,
• subclass (child) - the class that inherits from another class.
To inherit from a class, use the extends keyword.
In the example below, the Student class (subclass) inherits the attributes and methods from the
Person class (superclass):
class Person
{
protected String name = null;
protected int birthYear = 0;

public Person(String pname, int by)


{
........
}
........
}

public class Student extends Person


{
private String dept = null;
private int stuClass = 0;

public Student(String pname, int by, String dpt, int cl)


{
........
}
........
}

Java Lecture Notes 37 Halil Özmen


The super keyword
The super keyword is similar to this keyword. Following are the scenarios where the super keyword is
used.
• It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
• It is used to invoke the superclass constructor from subclass.

Differentiating the Members


If a class is inheriting the properties of another class. And if the members of the superclass have the
names same as the sub class, to differentiate these variables we use super keyword as shown below.
super.variable
super.method();

8. Object-Oriented Design

The programming is really about problem solving.

8.1. Software Developments Activities


Creating software involves much more than just writing code.
Any proper software development effort consists of four basic development activities:
• establishing the requirements,
• creating a design,
• implementing the design,
• testing.
These steps overlap and interact.

Software requirements specify what a program must accomplish. Often requirements are expressed
in a document called Software Requirements Specification (SRS) document. This document
describes the tasks that software should perform, not how it performs them.
We create a program or a software system to solve a
particular problem. Requirements are the clear Require-
expression of that problem. ments
Analysis
A software design indicates how a program will
accomplish its requirements. The design specifies the Testing Design
classes and objects needed in a program and defines
how they interact. It also specifies the relationships
among the classes. Implemen-
tation
Implementation is the process of writing the source
code that will solve the problem. More precisely, implementation is the act of translating the design
into a particular programming language.

Testing is the act of ensuring that a program will solve the intended problem given all of the
constraints under which it must perform. Testing includes running a program multiple times with
various inputs and carefully scrutinizing the results.

8.2. Identifying Classes and Objects


A fundamental part of object-oriented software design is determining the classes that will contribute to
the program. We have to carefully consider how we want to represent the various elements that make
up the overall solution. These classes determine the objects that will be managed in the system.

Java Lecture Notes 38 Halil Özmen


One way to identify potential classes is to identify the objects discussed in the program requirements.
Objects are generally nouns. Of course not every noun in the problem specification will correspond to
a class in the program.
Classes that represents objects should generally be given names that are singular nouns, such as
Student, Product, Message, Concert.
Another key decision is whether to represent something as an object or as a primitive attribute of
another object.
The user must be allowed to specify each product by its primary characteristics, including
its name and product number. If the bar code does not match the product, then an error
should be generated to the message window and entered into the error log.
The summary report of all transactions must be structured as specified in section 7.A.

A partial problem description with the nouns circled.

In addition to classes that represents objects from the problem domain, we likely will need classes that
support the work necessary to get the job done. For example, in addition to Member objects, we may
want a separate class to help us manage all of the members of a club.

Assigning Responsibilities
Part of the process of identifying the classes needed in a program is the process of assigning
responsibilities to each class. Each class represents an object with cetain behaviors that are defined
by the methods of the class. Any activity that the program must accomplish must be represented
somewhere in the behaviors of the classes. That is, each class is responsible for carrying out certain
activities, and those responsibilities must be assigned as part of designing a program.
Verbs are generally used for the names of behaviors and the names of the methods that accomplish
them.

8.3. Static Class Members


All the methods of the Math class are static.
Recall that a static method is one that is invoked through it's class name, instead of through an
object of that class.

Not only can methods be static, but variables can be static as well.
The static class members are declared using the static modifier.

Static Variables
So far, we have seen two categories of variables: local variables that are declared inside a method,
and instance variables that are declared in a class but not inside a method.
The term instance variable is used because each instance of the class has its own version of the
variable.
A static variable, which is sometimes called a class variable, is shared among all instances of a
class There is only one copy of a static variable for all objects of the class. Therefore, changing the
value of a static variable in one object, changes it for all of the others.
Example:
private static int count = 0;
Constants, which are declared using the final modifier, are often declared using the static
modifier.

Static Methods
Static methods can also be called class methods.
Static methods are invoked through the class name. There is no need to instantiate an object of the
class in order to invoke the method.
A method is made static by using the static modifier in the method declaration.
All the methods of the Math class are static methods.
Example: System.out.println("Square root of 28: " + Math.sqrt(28));
Java Lecture Notes 39 Halil Özmen
As we have seen many times, the main method of a Java program must be declared with the static
modifier; this is done so that main can be executed by the interpreter without instantiating an object
from the class that contains main.

Because static methods do not operate in the context of a particular object, they cannot
reference instance variables, which exist only in an instance of a class. The compiler will issue
an error if a static method attempts to use a nonstatic variable. A static method can reference static
variables because static variables exist independent of specific objects. Therefore the main method
can access only static or local variables, and can only call static methods.

8.4. Class Relationships


The classes in a software system have various types of relationships to each other. Three of the more
common relationships are dependency, aggregation and inheritence.
• Dependency - "uses"
• Aggregation - "has-a"
• Inheritence - "is-a"

Dependency
Sometimes, one class "uses" another. I.e., the methods of one class invokes the methods of other
classes. This establishes a "uses" relationship.
Generally, if class A uses class B, then one or more methods of class A invoke one or more methods
of class B. If an invoked method is static, then A merely references B by name. If the invoked method
is not static, then A must have access to a specific instance of class B in order to invoke the method.
That is, A must have a reference to an object of class B.
In general, we want to minimize the number of dependencies among classes. The less dependent are
the classes on each other, the less impact changes and errors will have on the system.

Dependencies Among Objects of the Same Class


In some cases, a class depends on itself. That is, an object of one class interacts with another object
of the same class. To accomplish this, a method of the class may accept as a parameter an object of
the same class.
The concat method of the String class is an example of this situation. The method is executed through
one String object and is passed another String object as a parameter.
String str3 = str1.concat(str2);

Example: RationalTester.java and RationalNumber.java programs demonstrate dependencies


among the objects of the same class.

Aggregation
Some objects are made up of other objects. For example, a car is made up of its engine, its chassis,
iths wheels, and several other parts. Each of these parts can be considered a separate object. We can
say that a car is an aggregation, it is composed, at least in part, of other objects.
Aggregation is also described as a has-a relationship. For instance, a car has a chassis car has tires.

The methods of the aggregate object generally invoke the methods of the objects from which it is
composed.

Example: Address.java, Student.java and StudentApp.java programs demonstrate aggregation type


of dependencies among the objects.

Java Lecture Notes 40 Halil Özmen


8.5. Method Design
Once the classes are identified, and they are assigned basic responsibilities, the design of each
method will determine how exactly the class will define its behaviors. Some methods are
straightforward and require little thought. Others are more interesting and require careful planning.
An algorithm is a step-by-step process for solving a problem. A recipe is an example of an algorithm.
Each method implements an algorithm that determines how that method accomplishes its goals.
An algorithm is often described using pseudocode, which is a mixture of code statements and English
phrases.
Pseudocode provides enough structure to show how the code will operate, without getting bogged
down in the syntactic details of a particular programming language or becoming prematurely
constrained by the characteristics of particular programming constructs.

Method Decomposition
Sometimes, a service that an object provides is so complicated that it cannot reasonably be
implemented using one method. Therefore we sometimes need to decompose a method into multiple
methods to create a more understandable design.
Whenever a method becomes large or complex, we should consider decomposing it into multiple
methods to create a more understandable class design.

Method Parameters
In Java, all parameters are passed by value. That is, the current value of the actual parameter (in the
invocation) is copied into the formal parameter in the method header.
Essentially, parameter passing is like an assignment statement, assigning to the formal parameter a
copy of the value stored in the actual parameter.
This issue must be considered when making changes to a formal parameter inside a method. The
formal parameter is a separate copy of the value that is passed in, so any changes made to it have no
effect on the actual parameter. after control returns to the calling method, the actual parameter will
have the same value as it did before the method was called.
However, when an object is passed to a method, actually a reference to that object is passed. The
value that gets copied is the address of the object. Therefore the actual parameter and the formal
parameter become aliases of each other. If the state of the object is changed through the formal
parameter, the object referenced by the actual parameter is changed, because they both refer to the
same object.

Java Lecture Notes 41 Halil Özmen


9. Sorting and Searching

9.1. Sorting Algorithms


In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order.
The most-used orders are numerical order and lexicographical order. In addition, the order can be
increasing or decreasing (ascending or descending) order.
It is much easier to search for something in a sorted list than an unsorted one.
Efficient sorting is important for optimizing the use of other algorithms (such as search and merge
algorithms) that require sorted lists to work correctly.
There are many sorting algorithms. Some of the algorithms sorts slower than the others.

Selection Sort
The selection sort algorithm is one of the most intuitive algorithms.
In selection sorting algorithm, the minimum value is found in the array then it is swapped with the
first element. In next step leave the first value and find the minimum value within remaining
values, then swap it with the value of minimum index position. Sort the remaining values by
using same steps.
At each step, one more element from the beginning of the array is in its correct place.

// Sort an array using the Selection Sort algorithm.


private static void selectionSort (int[] arr)
{
for (int j = 0; j < arr.length - 1; j++)
{
int minIdx = findMinIdx(arr, j);
if (minIdx != j)
{ // Swap the minimum with the current element
int temp = arr[j];
arr[j] = arr[minIdx];
arr[minIdx] = temp;
}
}
} // end selectionSort

// Returns index of the minimum value in array starting


// from a given index.
private static int findMinIdx(int[] arr, int startIdx)
{
// Set as the start
int min = arr[startIdx]; // Initialize minimum
int idxMin = startIdx; // Index of minimum value

// Find the minimum in the rest of the array.


for (int j = startIdx + 1; j < arr.length; j++)
{
if (arr[j] < min)
{ // Set this element as minimum.
min = arr[j];
idxMin = j; // set index of minimum
}
}
return idxMin;
} // end findMinIdx

Java Lecture Notes 42 Halil Özmen


Bubble Sort
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the array to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The
pass through the array is repeated until no swaps are needed, which indicates that the array is sorted.
The algorithm gets its name from the way smaller elements "bubble" to the top of the list, while bigger
element go to the bottom when sorting is done in ascending order.

// Sort an array using the Bubble Sort algorithm.


private static void bubbleSort (int[] arr)
{
for (int pass = 0; pass < arr.length - 1; pass++) // Passes
{
boolean sorted = true; // Assume sorted.
for (int k = 0; k < arr.length - 1 - pass; k++)
{
if (arr[k] > arr[k+1]) // Consecutive values not sorted
{
sorted = false; // Wasn't sorted yet.
// Swap the current and next elements.
int temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
}
if(sorted)
break; // If already sorted, then finish.
}
} // end bubbleSort

9.2. Searching Algorithms


In computer science, a search algorithm is an algorithm for finding an item with specified properties
among a collection of items. The items may be stored individually in an array, as records in a
database, or may be elements of a search space defined by a mathematical formula or procedure.

Linear Search
In computer science, linear search or sequential search is a method for finding a particular value
in an array or a list, that consists of checking every one of its elements, one at a time and in
sequence, until the desired one is found.
// Returns the index of the first occurrence of val in the array.
// Returns -1 if search value does not exist in the array.
private static int linearSearch (int[] arr, int searchVal)
{
for (int j = 0; j < arr.length; j++)
{
if (searchVal == arr[j])
{
return j; // Found, return index
}
}
return -1; // Not found, return -1
} // end linearSearch

Java Lecture Notes 43 Halil Özmen


Binary Search
In computer science, a binary search or half-interval search algorithm finds the position of a
specified value (the input "key") within a sorted array.
To perform binary search, the array (or the list) must be sorted.
At each stage, the algorithm compares the input key value with the key value of the middle
element of the array. If the keys match, then a matching element has been found so its index, or
position, is returned. Otherwise, if the sought key is less than the middle element's key, then the
algorithm repeats its action on the sub-array to the left of the middle element or, if the input key
is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero,
then the key cannot be found in the array and a special "not found" indication (such as -1) is
returned.
A binary search halves the number of items to check with each iteration, so locating an item (or
determining its absence) takes logarithmic time.

// Returns index if value is found, returns -1 if not found.


private static int binarySearch(int[] sorted, int value)
{
int startIdx = 0;
int endIdx = sorted.length - 1;
while (startIdx <= endIdx)
{
int midIdx = (startIdx + endIdx) / 2; // Compute mid idx
if (value < sorted[midIdx])
{
endIdx = midIdx - 1; // Set endIdx for top half
}
else if (value > sorted[midIdx])
{
startIdx = midIdx + 1; // Set startIdx for bottom half
}
else // (value == sorted[midIdx])
{
return midIdx; // Found it, return index.
}
}
return -1; // Failed to find value.
} // end binarySearch

Java Lecture Notes 44 Halil Özmen


10. Recursion
Recursion is a powerfull programming technique that provides elegant solutions to certain problems.
Recursion is a programming technique in which a method calls itself in order to fulfill its purpose.

Recursive Thinking
The problem is divided to two parts: (1) Base case or simple case, (2) Recursive definition.
The part of the definition which is not recursive is called the "base case" (or the "simple case").
The recursive definition may also be called "complex case".

Factorial Problem:
The value referred to as N! (N factorial) is defined for any positive integer N as the product of all
integers between 1 and N inclusive.
4! = 4 * 3 * 2 * 1 = 24 12! = 12 * 11 * 10 * ... * 3 * 2 * 1 = 479001600
N! = N * (N-1) * (N-2) * (N-3) * ... * 2 * 1
The definition of N! can be expressed recursively as:
N! = N * (N-1)! for N > 1. (Recursive definition.)
1! = 1 (Base case) (Also: 0! = 1)

The base case of the factorial definition is 1!.


All other values of N! (for N > 1) are defined recursively as N times the value of (N-1)!.
The recursion is that the factorial function is defined in terms of the factorial function.

Recursive Programming
The recursive solution in Java for the factorial problem can be as follows:
public static double factorial (int n)
{
double result;
if (n <= 1) // Base case
{ result = 1; }
else // Complex case
{ result = n * factorial (n-1); }
return result;
} // end factorial

Example: Let's consider the process of finding the sum of the elements of an array of integers.
public static int sumArray (int[] arr, int lastIndex)
{
if (lastIndex < 0) // Base case: no element (lastindex < 0)
{ return 0; }
else // Complex case (recursive definition)
{ return arr[lastIndex] + sumArray (arr, lastIndex-1); }
} // end sumArray
This can also be written as:
public static int sumArray (int[] arr, int lastIndex)
{
int result = 0; // Base case is the default here.
if (lastIndex >= 0) // Complex case (recursive definition)
{ result = arr[lastIndex] + sumArray (arr, lastIndex-1); }
return result;
} // end sumArray

Recursive method for Fibonacci numbers: https://www.tutorialspoint.com/recursive-fibonacci-method-in-java

Java Lecture Notes 45 Halil Özmen

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy