Java Lecture Notes
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
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.
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.
Central Arithmetic
Processing Memory Control Unit Logic Unit
Unit (ALU)
System Intercon-
(CPU)
Intercon- nection in
nection CPU
Input/
Output Registers
Modules
Input Devices: keyboard, mouse, harddisk, flash disk, microphone, modem, etc.
Output Devices: monitor, harddisk, flash disk, sound speaker, modem, printer, etc.
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 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).
.java .class
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.
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.
Java identifiers are case sensitive. Therefore, total, Total, ToTal, TOTAL are all different identifiers.
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 /* ... */.
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
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
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;
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;
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);
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.");
}
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.)
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.");
}
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
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 ****
is found.
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.
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
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");
{
Method
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);
.... ....
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 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
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
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.
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.
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
}
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
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.".
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.
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));
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])
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.
import java.util.Scanner;
import java.io.*;
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.
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 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
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.
Initially, the array looks like this. Array after the assignments:
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)
};
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
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.
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.
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).
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
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.
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.
Similarly, this keyword can also be used in mutators and other methods to refer to the members of
the current object.
// 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().
The table below summarizes the effects of public and private visibility of both variables and methods.
public private
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;
8. Object-Oriented Design
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.
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.
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.
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.
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.
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.
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.
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
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)
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