Object-Oriented Programming using Java PDF

Document Details

SalutaryBegonia

Uploaded by SalutaryBegonia

Suez Canal University

2024

Dr. Mohamed Gamal

Tags

Java programming object-oriented programming arrays exception handling

Summary

This document is a Java programming tutorial focused on object-oriented programming concepts. It covers topics such as static methods, wrapper classes, arrays, and exception handling, along with illustrative examples.

Full Transcript

Object Oriented Programming using Java Dr. Mohamed Gamal © Mohamed Gamal 2024 Static Methods – Static fields and static methods do not belong to a single instance of a class. – Static methods are convenient because they may be called at the class...

Object Oriented Programming using Java Dr. Mohamed Gamal © Mohamed Gamal 2024 Static Methods – Static fields and static methods do not belong to a single instance of a class. – Static methods are convenient because they may be called at the class level using the class name. – They are typically used to create utility classes, such as the Math class in the Java Standard Library. – Static methods may not communicate with instance fields of the class, only static fields, however, the reverse is true. – To invoke a static method or use a static field, the class name, rather than the instance name, is used. double val = Math.sqrt(25.0); Class name Static method Static Methods – Example 1 package MyPackage; package MyPackage; public class Test { public class Hello { // Static variable private static int no_objects = 0; public static void main(String[] args) { // Constructor Test t1 = new Test(); public Test() { Test t2 = new Test(); no_objects += 1; Test t3 = new Test(); } Test t4 = new Test(); Test t5 = new Test(); // Static method public static int getNoObjects() { System.out.println(Test.getNoObjects()); return no_objects; } } } } Static Methods – Example 2 package MyPackage; package MyPackage; public class Calculator { public class Hello { public static int add(int x, int y) { return x + y; public static void main(String[] args) { } Calculator.add(10, 20); public static int sub(int x, int y) { Calculator.sub(7, 2); return x - y; Calculator.mult(20, 30); } } } public static int mult(int x, int y) { return x * y; }... } Java Wrapper Classes – In Java, wrapper classes are objects that encapsulate (or "wrap") primitive data types so that they can be used as objects when needed. – Java provides a corresponding wrapper class for each of its eight primitive data types. byte → Byte float → Float short → Short double → Double int → Integer char → Character long → Long boolean → Boolean Integer x = 5; Character.toUpperCase('A'); Class name Static method Arrays in Java – An array is a multiple values of the same data type that can be stored with only one variable name. – The use of arrays allows for the development of smaller and more clearly readable programs. F E D C 5 B 4 A Tip: 3 2 1 Array indices generally start with zero; 0 the first element of an array is zero elements away from the start, the next is one element away from the start, and so on. Arrays in Java (Cont.) – Consider a scenario where you need to store 100 students scores in the exam and then calculate the average. Scanner scan = new Scanner(System.in); Why don't we have a single int student1, student2, student3 … student100; variable that holds all the students variables ?! student1 = scan.nextInt(); student2 = scan.nextInt(); … student100 = scan.nextInt(); float average = (student1 + student2 + student3 …. student100) / 100.0; Arrays in Java (Cont.) All the array elements occupy contiguous space in memory. name no. elements int[] arr = new int; 30 89 97 89 68 22 17 63 55 40 ← Array values 0 1 2 3 4 5 6 7 8 9 ← Array indices Array Length = 10 The topmost element is arr, there’s no arr First Index = 0 Last index = 9 A rr ay Tip: Arrays in programming are similar to vectors or matrices in mathematics. Arrays in Java String[] arr = new String Or String arr[] = new String Array Object Declaration int[] arr = new int; Or int[] arr; arr = new int; Contiguous Multiple Arrays char[] arr1, arr2, arr3; Declaration Arrays and double arr1[], x, y; Variables Array length 0 1 2 3 Fixed Length int[] arr = { 10, 20, 30, 40 }; inference Accessing array elements – You can use array subscript (or index) to access any element stored in an array, by using a numeric index in square brackets [ ]. arr; Index = 8 40 55 63 17 22 68 89 97 89 30 0 1 2 3 4 5 6 7 8 9 A rr ay arr; Arrays are objects – Arrays are objects, so, they are reference types. float[] a = { 1.0f, 2.0f, 3.0f }; float[] b; b = a; // same memory location System.out.println(a); System.out.println(b); if (a == b) System.out.println("Same memory location."); else System.out.println("Different memory location."); Printing Array Elements 0 1 2 3 4 String[] arr = { "Java", "Python", "C", "C++", "C#" }; for (int i = 0; i < arr.length; i++) System.out.print(arr[i] + " "); for (String val : arr) for-each System.out.print(val + " "); Loop import java.util.Arrays; System.out.println(Arrays.toString(arr)); Arrays as return values Driver Code Method that returns an array public static void main(String[] args) { // Create an instance of ArrayInitializer public int[] initArray(int size, int initValue) { TestApp t1 = new TestApp(); int[] array = new int[size]; // Initialize an array for (int i = 0; i < array.length; i++) int[] myArray = t1.initArray(5, 10); array[i] = initValue; } // Print the array elements to verify for (int num : myArray) System.out.print(num + " "); } Array Search Driver Code Method that searches for an element in an array public static void main(String[] args) { // Create an instance of ArrayInitializer // Returns true if array contains item, false otherwise. TestApp t1 = new TestApp(); private boolean contains(String[] items, String element) { // Initialize an array for (var item : items) String[] items = { "apple", "banana", "orange" }; if (item.equalsIgnoreCase(element)) return true; // Testing the 'contains' method return false; boolean found = t1.contains(items, "APPLE"); } System.out.println(found); } Array of Objects – Example 1 public static void main(String[] args) { // Create an object array of Food Class Food[] refrigerator = new Food; Food food1 = new Food("Pizza"); Food Food food2 = new Food("Hamburger"); Food food3 = new Food("Donut"); name refrigerator = food1; refrigerator = food2; Food( … ) refrigerator = food3; System.out.println(refrigerator); System.out.println(refrigerator); System.out.println(refrigerator); } Array of Objects – Example 2 Class public static void main(String[] args) { Book // Create an object array of Book Book[] books = new Book; title author // Create Book objects price Book b1 = new Book("The Equalizer", "Michael Sloan", 9.99f, 2014); year Book b2 = new Book("Harry Potter", "J.K. Rowling", 19.99f, 1997); Book( ) books = b1; Book( … ) books = b2; setTitle( … ) getTitle( ) for (int i = 0; i < books.length; i++) setAuthor( … ) getAuthor( ) System.out.println(books[i].getTitle()); setPrice( … ) getPrice( ) for (Book b : books) setYear( … ) getYear( ) System.out.println(b.getTitle()); display() } Arrays of Arrays (Multi-dimensional Arrays) – We can use array of arrays which is organized as matrices and can be represented as a collection of rows and columns. 0 1 2 3 int[][] arr = { {40, 55, 63}, {17, 22, 68}, {89, 97, 89}, {30, 15, 27} }; 0 1 2 0 1 2 0 1 2 0 1 2 Columns We don't need to specify the size of the array if the declaration 0 1 2 and initialization are being done simultaneously. 0 40 55 63 There’re no multi-dimension arrays. There are arrays of arrays. 1 17 22 68 Rows 2 89 97 89 3 30 15 27 String[][] users = { { "Ahmed", "Mohamed", "Ali" }, { "Gamal", "Hassan", "Mahmoud" }, { "Reda", "Ibrahim", "Mazen" } }; j Columns 0 1 2 0 arr arr arr i 1 arr arr arr Rows 2 arr arr arr Printing the ND array elements int[][] arr = { {10, 20, 30}, {40, 50, 60}, {70, 80, 90} }; int rows = arr.length; int columns = arr.length; for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) System.out.printf("arr[%d][%d] = %d\n", i, j, arr[i][j]); Limitations of standard Arrays – You must explicitly specify the array size when you create it. – Array size cannot change once created. – No bounds checking for out-of-bound accesses. Solution: – Use ArrayList, they stretch as you add elements to them or shrink as you remove elements from them. – ArrayLists are similar to standard arrays but allow Dynamic resizing and have many other useful features. – When declaring an ArrayList, only non-primitive types (i.e., objects) can be used with these collection classes. – To use other primitive data types, such as int, you must specify an equivalent wrapper class. import java.util.ArrayList; ArrayList Methods Elements (objects) are of type "String" ArrayList list = new ArrayList(); Description Method ( ) Create an empty list new ArrayList() Add an element to the end of the list (append) add(element) Remove an element from the list remove(element) or remove(index) Remove all the elements in the list clear() Get the number of elements in the list size() Get an element at a specific index get(index) Check if an element exists in the list contains(element) Replace the value at a specific index by a new one set(index, new value) ArrayList – Example 1 public static void main(String[] args) { // Create an ArrayList ArrayList languages = new ArrayList(); // Add elements to the ArrayList languages.add("Java"); languages.add("Python"); languages.add("C++"); languages.add("C#"); // Remove an element from the ArrayList languages.remove("C++"); // Display the elements in the ArrayList for (String lang : languages) { System.out.println(lang); } ArrayList – Example 2 public static void main(String[] args) { // Create an ArrayList ArrayList entries = new ArrayList(); // Add elements until a random number less than 0.1 is generated double d; while ((d = Math.random()) > 0.1) { entries.add("Value: " + d); } // Display the elements in the ArrayList for (String entry : entries) System.out.println(entry); } ArrayList – Example 3 Class public static void main(String[] args) { // Create an object array of Book Book ArrayList books = new ArrayList(); // Create Book objects title Book b1 = new Book("The Equalizer", "Michael Sloan", 9.99f, 2014); author Book b2 = new Book("Harry Potter", "J.K. Rowling", 19.99f, 1997); price year books.add(b1); books.add(b2); Book( ) Book( … ) for (int i = 0; i < books.length; i++) System.out.println(books.get(i).getTitle()); setTitle( … ) getTitle( ) setAuthor( … ) getAuthor( ) for (Book b : books) setPrice( … ) getPrice( ) System.out.println(b.getTitle()); setYear( … ) getYear( ) // replaces item at position 0 books.set(0, new Book("Hunger Games", "Suzanne", 14.99f, 2008)); display() } ArrayList – Example 4 public static void main(String[] args) { // Foods ArrayList ArrayList foods = new ArrayList(); foods.add("Hamburger"); foods.add("Donuts"); foods.add("Pizza"); // 2D ArrayList ArrayList total = new ArrayList(); total.add(foods); // Add foods ArrayList System.out.println(total); } Exception Handling in Java – An exception indicates a problem that occurs during program execution, such as an invalid array index or method argument. – Java performs bounds checking to prevent accessing invalid array indices. If an invalid index is used, the JVM (Java Virtual Machine) throws an exception. – Exception handling enables fault-tolerant programs by resolving or handling exceptions. – Place code that might throw exceptions in a try block. If an exception occurs, it’s caught in a catch block where it can be handled. – Multiple catch blocks can handle different types of exceptions from a single try block. – Use.toString() or.getMessage() methods on an exception object to retrieve the error message. try { // Some Code... } catch (Exception 1) { // Some Code... } catch (Exception 2) { // Some Code... }... } catch (Exception n) { // Some Code... } List of Java Exceptions Exception Handling – Example 1 Index out-of-bound exception → IndexOutOfBoundsException public static void main(String[] args) { try { int nums[] = { 3, 5, 9 }; System.out.println(nums); // Error System.out.println("nums array size: " + nums.length); } catch (IndexOutOfBoundsException ex) { System.err.println(ex.getMessage()); } } Exception Handling – Example 2 Null Pointer exception → NullPointerException public static void main(String[] args) { try { int nums[] = null; System.out.println("nums array size: " + nums.length); // Error } catch (NullPointerException ex) { System.err.println(ex.getMessage()); } } Exception Handling – Example 3 Null Pointer exception → Exception public static void main(String[] args) { try { int nums[] = null; System.out.println("nums array size: " + nums.length); // Error } catch (Exception ex) { System.err.println(ex.getMessage()); } } Exception Handling with Finally – The finally block executes code after the try-catch blocks, regardless of whether an exception was thrown or not. public static void main(String[] args) { try { int nums[] = { 1, 2, 3, 4 }; System.out.println(nums); // Error } catch (Exception ex) { System.out.println("Something went wrong!"); // System.err.println(ex.getMessage()); } finally { System.out.println("The 'finally' block has executed."); } } Assignment Thank You!

Use Quizgecko on...
Browser
Browser