0% found this document useful (0 votes)
5 views58 pages

Presentation 5

The document covers key concepts in Object-Oriented Programming using Java, focusing on arrays, their initialization, and manipulation. It also discusses the Java Collection Framework, particularly the ArrayList class, and the use of enums for type safety. Additionally, it addresses memory management and null values in Java programming.

Uploaded by

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

Presentation 5

The document covers key concepts in Object-Oriented Programming using Java, focusing on arrays, their initialization, and manipulation. It also discusses the Java Collection Framework, particularly the ArrayList class, and the use of enums for type safety. Additionally, it addresses memory management and null values in Java programming.

Uploaded by

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

IT 214

Object
Oriented
Programming
Dr. Abdulaziz Saleh Algablan
Email: [email protected]
2023
Topics
Arrays
Java Collection Framework
Null Value
Enumeration
Garbage Collection
Object Class
Array
• An array is a collection of data values of the same type.
• The following declares an array of double:
double[] rainfall;
• The square brackets indicate the array declaration.
• The brackets may be attached to a variable instead of the data type.
• For example, the declaration
double rainfall[];
is equivalent to the previous declaration
An Array of String
• We can also declare and allocate
memory for an array in one
statement, as in:
String[] monthName = new String[12]; monthName[0] = "January";
monthName[1] = "February";
monthName[2] = "March";
monthName[3] = "April";
• Then, elements of the array can be monthName[4] = "May";
monthName[5] = "June";
initilaized using the index: monthName[6] = "July";
monthName[7] = "August";
monthName[8] = "September";
monthName[9] = "October";
monthName[10] = "November";
monthName[11] = "December";
An Array of String
• Java allows you to initialize an array at the time of
declaration:
String[] monthName = { "January", "February", "March","April", "May",
"June", "July",
"August", "September", "October","November", "December" };
Length of Array
• An array has a public constant length for the size of an array.
String array[] = new String[] {"Toyota", "Mercedes", "BMW", "Volkswagen",
"Skoda" };
int arrayLenght = array.length;

• Using this constant, we can rewrite the for loop as


for (int i = 0; i < array.length; i++) {
// some code here...
}
Pass Array to Method
/* The method returns the index of the minimum element.
The input is an integer array.
*/
public static int searchMinimum(double[] arrayOfIntNumbers) {
int indexOfMinimum = 0; // assume that the first element is the smallest.
for (int i = 1; i < arrayOfIntNumbers.length; i++) {
if (arrayOfIntNumbers[i] < arrayOfIntNumbers[indexOfMinimum])
{
indexOfMinimum = i; //smaller element
}
}
return indexOfMinimum;
}
Array’s Index
• An array’s index allows values starting from 0 index and ends with
length – 1:
String array[] = new String[] {"Toyota", "Mercedes",
"BMW", "Volkswagen", "Skoda" };
int first_element = 0;
int last_element = array.length - 1;
System.out.print(array[first_element] );
System.out.print(array[last_element ] );
Index Out of Bound Exception
• ArrayIndexOutOfBoundsException will be thrown if the index
provided is equal or greater than the array’s length :

int[] numbers = new int[] {1, 2, 3, 4, 5};


int lastNumber = numbers[5];

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:


Index 5 out of bounds for length 5
at ...
For-each Loop
• The syntax of the Java for-each loop is:
for(DataType variable: array) {
...
}

• For example:
// create an array
int[] numbers = {1, 3, 5, 15};

// for each loop


for (int i_number: numbers) {
System.out.println((i_number * 10));
}
Will print: 10
30
50
150
2-dimensional Arrays
• int[][] a = new int [3] [4] ;
Two-Dimensional Arrays
double[][] payScaleTable = {
{10.50, 12.00, 14.50, 16.75, 18.00},
{20.50, 22.25, 24.00, 26.25, 28.00},
{34.00, 36.50, 38.00, 40.35, 43.00},
{50.00, 60.00, 70.00, 80.00, 99.99} };
// payScaleTable.length == 4
// payScaleTable[1].length == 5

int[][] a = new int [3][4];


Two-Dimensional Arrays
• Subarrays can have different lengths.
• This can be achieved during the initialization of 2 dimensional array
• length of columns can be left empty.
• The following code creates a triangular array whose subarray
triangularArray[i] has variable length:

double[][ ] triangularArray = new double[4][ ];


for (int i = 0; i < 4; i++)
triangularArray[i] = new double[i+1];
2-dimensional Arrays
• Arrays that require two indices to identify each element are called two-dimensional arrays.
int[][] b = new int [2] [2] ;
int [] [] c = new int [3][];
c[0] = new int [2];
c[1] = new int [3];
c[3] = new int [4];

Object [] [] arrayOfobject = new Object [5] [];


Multidimensional Arrays
• Multidimensional arrays can have more than two dimensions.
• Java does not support multidimensional arrays directly, but it allows
you to specify one-dimensional arrays whose elements are also one-
dimensional arrays, thus achieving the same effect
Multidimensional Arrays
• Multidimensional arrays can be initialized with array initializers in declarations.
• A two-dimensional array b with two rows and two columns could be declared and
initialized with nested array initializers as follows:
int[][] b = { { 1, 2 }, { 3, 4 } };
• The initial values are grouped by row in braces.
• The compiler counts the number of nested array initializers to determine the
number of rows in array b.
• The compiler counts the initializer values in the nested array initializer for a row to
determine the number of columns in that row.
• Rows can have different lengths.
• Multidimensional arrays are maintained as arrays of one-dimensional arrays.
String Array in the main(String []
args)
• In Java, it’s possible to pass arguments from the command line.
• The main method received the provided arguments
• main(String[] args).
• By convention, the parameter is named args.
• When an application is executed using the java command, Java passes
the command-line arguments that appear after the class name to the
application’s main method
• As Strings in the array args.
• Common uses of command-line arguments include passing options
and file names to applications
main(String [] args)
• The command line “java <ClassName> <arg0> <arg1> …. <argn>” is
used to run the java program. For example:
CommandLineArguments.ja
public class CommandLineArguments { va

public static void main(String[] args) {


System.out.println("Number of Command Line Argument = "+args.length);

for(int i = 0; i< args.length; i++) {


System.out.println("Command Line Argument ”+ i +” is ”+ args[i]));
} }
}
 javac CommandLineArguments.java
 java CommandLineArguments “A” “B” “C”

Number of Command Line Argument = 3


Command Line Argument 0 is A
Command Line Argument 1 is B
Command Line Argument 2 is C
Array of Objects
• Array types are not limited to primitive data types.
• instead, an array may hold objects.
• Since a String is actually an object, we have already seen an example
of an array of objects.
• How we can create and manipulate an array of Person objects.
Person[] personArray; //declare the person array
personArray = new Person[20]; //and then create it
Array of Objects
• Notice that the elements, that is, Person objects, are not yet created
in previous slide; only the array is created.
• Array elements are initially null.
• Since each individual element is an object, it also must be created.
• To create a Person object and set it as the array’s first element, we
may write:
personArray[0] = new Person( );
An array of Objects
• Notice that no data values are assigned to the object yet.
• The object has default values at this point.
• To assign data values to this object, we can execute:
personArray[0].setName ( "Ms. Latte" );
personArray[0].setAge ( 20 );
personArray[0].setGender( 'F’ );
• The array’s index can be used to access and modify the values of
stored objects
Initialization of Objects
• We can initialize all elements of the array with new instance with
default values, for example.

Person[] personArray;
personArray = new Person[20];

for (int i = 0; i < personArray.length; i++) {


personArray[i] = new Person();
}
Initialization of Objects
• If we have a Student and Doctor that are both child of the Person
class we can do the following:

Person[] personArray;
personArray = new Person[3];

• Since a student is a person, we can do the following:


personArray[0] = new Person();
personArray[1] = new Student();
personArray[1] = new Doctor();
Example
public class ArrayOfObjectTest { class Person {
public String toString(){
;"return "I am a person
public static void main(String[] args) {
}
Person[] personArray = new Person[3];
}
personArray[0]= new Person();
class Student extends Person{
personArray[1]= new Student();
public String toString(){
personArray[2]= new Doctor();
;"return "I am a student
for (Person tempPersonObject :
personArray) }
{ }
System.out.println(tempPersonObject); class Doctor extends Person{
} public String toString(){
} return "I am a doctor";
} I am a person }
I am a student }
I am a doctor
Java Collection Framework
• The Java API provides several predefined data structures, called
collections.
• They can be used to store groups of related objects.
• These classes provide efficient methods that organize, store and
retrieve your data without requiring knowledge of how the data is
being stored.
• This reduces application-development time.
• Java Collection framework provides many usefull classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
ArrayList
• Arrays do not automatically change their size at execution time to
accommodate additional elements.
• The collection class ArrayList<T> provides a convenient solution to this
problem:
• from package java.util.
• it can dynamically change its size to accommodate more elements.
• The T (by convention) is a placeholder—when declaring a new ArrayList, replace it
with the type of elements that you want the ArrayList to hold.
• This is similar to specifying the type when declaring an array, except that only
nonprimitive types can be used with these collection classes.
• Classes with this kind of placeholder that can be used with any type are
called generic classes.
ArrayList
• For example, to declare a list as an ArrayList collection that can store
only Strings:
ArrayList<String> aStringList = new ArrayList<String>();

• ArrayList class differs than Java array


• doesn’t have length as attribute, instead it has size() method which return the
number of the actual elements.
• It has several methods:
• add(…), remove(), contains(), etc.
ArrayList’s Methods
ArrayList Example
import java.util.ArrayList;
public class ArrayListCollection
{
public static void main( String[] args )
{
ArrayList< String > cars = new ArrayList<String> ();
cars.add("Volvo"); cars.add("BMW");cars.add("Ford");cars.add("Mazda");
[Volvo, BMW, Ford, Mazda]
System.out.println(cars);
//To remove an element, use the remove() method and refer to the index number. For example:
cars.remove(0);
cars.add( 0, “Jeep" ); // insert the value at index 0
//To find out how many elements an ArrayList have, use the size method:
int sizeOfArrayList = cars.size();
//We can also loop through an ArrayList with the for-each loop:
for (String i : cars) { Jeep
System.out.println(i); BMW
} Ford
//To find out if “Ford” is in ArrayList , use the contains method. For example:
Mazda
boolean flag = cars.contains(“Ford”);
}
}
Null Values
• null—the default initial value for reference types:
• String variables
• Class variables
• It is just a value that shows that the object is referring to nothing.
• Often, you need to check if a reference points to null.
• NullPointer Exception (NPE)
• NullPointerException is a runtime exception is thrown when an application
attempts to use an object with a null value.
Null Operations
• There are only two kinds of operations.
• Initialise or set a reference to null (e.g name = null):
• The only thing to do is to change the content of one memory cell (e.g. setting
it 0).
• Check if a reference points to null (e.g. if name == null).
Enum
• Enum in Java is a data type which contains a fixed set of constants.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

• Properites of Enum:
• Improves type safety.
• Easily used in switch.
• Easily traversed.
• can have fields, constructors and methods.

• By defining an enumerated type, a variable of that type can only accept the associated
enumerated constants.
• Any violation will be detected by the compiler.
• Eliminate the possibility of assigning a nonsensical value as seen in the case for the numerical
constants.
Enum
• For example:
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
enum Month {JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST,
SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER}
enum Gender {MALE, FEMALE}
enum SkillLevel {NOVICE, INTERMEDIATE, ADVANCED, EXPERT}

• Here the Day enum is public, it should be defined in its own file.
• The file name should be “Day.java”
Enum - Improves type safety
//=== version 1
enum Fruit {APPLE, ORANGE, BANANA};
Fruit f1, f2, f3;
f1 = Fruit.APPLE;
f2 = Fruit.BANANA;
f3 = f1;
//=== version 2
final int APPLE = 1; final int ORANGE = 2; final int BANANA = 3;
int fOne, fTwo, fThree;
fOne = APPLE;
fTwo = ORANGE; fThree = fOne;
• The code may look comparable to the one that uses enumerated constants, but what will happen if we write the following?
fOne = 45;
Enum - Easily used in switch
Fruit fruit;
fruit = ...;
switch (fruit) {
case APPLE: . . .;
break;
Enum
• The Java compiler internally adds some methods when it creates an enum:
• values()
• valueOf(..)
• Ordinal()
• values() :
• returns an array containing all the values of the enum.
• valueOf() :
• returns the value of given constant enum.
• ordinal() method in the enum:
• returns the index of the enum value.
Enum - valueOf(…)
• The method accepts one String argument and returns the
enumerated constant whose value matches the given argument.
• For example:
Fruit fruit = Fruit.valueOf("APPLE");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your favorite fruit " +"(APPLE, ORANGE,
BANANA): ");
String fruitName = scanner.next( );
Fruit favoriteFruit = Fruit.valueOf(fruitName);
Traversing the
Values of Enum
Values of the Enum Constants
Memory Management

:++ Example in C
• What happen for variables after definitions and
assignment?
• Is some programming languages, there is explicit
way to free the memory (if no use for variables).

• Problems with Manual Management


• Memory leaks where resources are never freed.
• Double frees where a resource is freed twice (major
security risk).
• Use-after-frees where a deallocated resource is still
used (major security risk)
Garbage Collection
• Every object uses system resources, such as memory.
• Java needs a disciplined way to give resources back to the system
when they’re no longer needed.
• The JVM performs automatic garbage collection to reclaim the
memory occupied by objects that are no longer used.
• When there are no more references to an object, the object is eligible
to be collected.
• Collection typically occurs when the JVM executes its garbage
collector, which may not happen for a while, or even at all before a
program terminates.
Garbage Collection
• Not programming languages has garbage collection:
• C and C++ do not have garbage collection
• The biggest benefit of Java garbage collection is that it automatically
handles the deletion of unused objects or objects that are out of reach
to free up vital memory resources.
• Programmers working in languages without garbage collection (like C
and C++) must implement manual memory management in their code.
• Some programmers argue in favour of manual memory management
over garbage collection, primarily for reasons of control and
performance.
Garbage Collection
• Even though the programmer in Java is not responsible for destroying
useless objects but it is highly recommended to make an object
unreachable(thus eligible for GC) if it is no longer required.
• Its important to know that garbage collection frees Java heap
(memory) but not OS resources used in your code.
• FileStream, database connection, etc. require explicit close() method.
GC Example

public class ArrayListCollection


{
public static void main( String[] args )
{
String aString = “Happy”;
m1();

}
public static void m1()
{
String bString = “This is m1”;
}

}
GC Example – Cont.
Stack Heap

• at beginning, JVM will


create a stack and heap
for the program.
• main() stack is created. aString
• main() stack is active.
• The String object String
aString is created. “Happy”
GC Example – Cont.
Stack Heap

• After calling m1(), m1()


stack will be created.
• m1() stack is active. String
“This is m1.”
• Execution continues in
m1(). bString

• Heap may expend due String


to bString. aString “Happy”
• main() stack is not
active.
GC Example – Cont.
Stack Heap

• After finishing the call


of m1(), m1() stack will
be destroyed. String
• main() stack is active “This is m1.”
again.

String
aString “Happy”
GC Example – Cont.
Stack Heap

• the String object “This is m1” will not be used anymore.


• GC will delete it.
String
“This is m1.”

String
aString “Happy”
GC Example – Cont.
Stack Heap

• GC deleted the String


object “This is m1” .
• The heap shrinks.
• The execution continues.

String
aString “Happy”
GC Example – Cont.
Stack Heap

• GC deleted the String


object aString.
• The execution continues.
The Object Class
• In Java, every class descends from (and
inherits features from) the Object class.
• Therefore, every object of every class is of
child of the Object class.
• Unless a class is declared explicitly to be a
descendant of some other class, it is an
immediate child of the class Object.

51
The Class Object, cont.
• An object of any class can be substituted as a
parameter of Object is expected.
• Every class inherits some methods from the
class Object:
• equals()
• toString()
• hashCode()
• getClass()
• These methods can be overridden by the
derived class or by an intermediate ancestor
class.52
Method toString
• Inherited method toString() takes no
arguments.
• Typically, method toString() is coded to
produce and return a string which contains
everything of interest about the object.

53
Method toString, cont.
• Example:
public String toString();
{
return (“Name: “ + getName()+ \n
+ “Number: “ + getNumber());

}
• Whenever a new class is created, a suitable
toString method should be defined.

54
Method toString, cont.
• Method toString can be called my the
conventional means, Object_Name.toString,
or by using only Object_Name.
• Example:
String s = new String(“Hi”);
System.out.println(s.toString());
or
System.out.println(s);

55
Method clone()
• Method clone also is inherited from the class
Object.
• Method clone takes no arguments and returns
a copy of the calling object.
• Even though the data is identical, the
objects are distinct.
• Typically, method clone needs to be
overridden to function properly.

56
Method equals()
class Car { public class TestObjectClass {
int vin; // vehicle identification number. public static void main(String []
sr)
MyCar(int a){ {
vin = a;} Car i1 = new Car(2121);
Car i2 = new Car(2121);
public boolean equals(Object obj) { Car i3 = new Car(66443);
if(
obj.getClass().getName().equals(this.getClass().getName())) System.out.println(i1.equals(i1));
System.out.println(i1.equals(i2));
{ System.out.println(i1.equals(i3));
Car objAsMyCar = (Car)obj; }
}
return objAsMyCar.vin == this.vin;
} true
true
else false
return false;
}
}

57
The End

You might also like