0% found this document useful (0 votes)
9 views21 pages

PSOOP - Lecture 4-24-25

The document provides an overview of arrays and the static keyword in Java, detailing various types of arrays including one-dimensional, two-dimensional, and jagged arrays, along with examples of their declaration and usage. It also explains the static keyword's role in memory management, its application in class variables and methods, and includes examples demonstrating static methods and blocks. Additionally, it presents a practical example involving a café order system to illustrate the use of arrays in a real-world scenario.

Uploaded by

dhruvvbhalani
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)
9 views21 pages

PSOOP - Lecture 4-24-25

The document provides an overview of arrays and the static keyword in Java, detailing various types of arrays including one-dimensional, two-dimensional, and jagged arrays, along with examples of their declaration and usage. It also explains the static keyword's role in memory management, its application in class variables and methods, and includes examples demonstrating static methods and blocks. Additionally, it presents a practical example involving a café order system to illustrate the use of arrays in a real-world scenario.

Uploaded by

dhruvvbhalani
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/ 21

PSOOP (JAVA)

-Lecture 4
Compiled by Nikahat Mulla
AGENDA

 Understanding Arrays and Static Keyword in


Java
 Array of Objects example

2
INTRODUCTION TO ARRAYS IN JAVA

 Definition: Arrays are fixed-size, contiguous


memory structures used to store elements of the
same data type.
 Why use arrays?
 Efficient storage and retrieval of data
 Easy access via indexing
 Useful for sorting and searching algorithms
TYPES OF ARRAYS IN JAVA
 1D Arrays (Single Dimensional)
 2D Arrays (Multidimensional)

 Jagged Arrays (Irregular multidimensional


arrays)
 Array of Objects
ONE-DIMENSIONAL ARRAYS (1D)
 Declaration & Initialization
 int[] arr = new int[5]; // Declaring an array of size 5
 arr[0] = 10; // Initializing array elements

OR
 int[] arr = {10, 20, 30, 40, 50}; // Inline initialization

 Example: Printing 1D Array


for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
TWO-DIMENSIONAL ARRAYS (2D)
 Declaration & Initialization
 int[][] matrix = new int[3][3]; // Declaring a 3x3
matrix
 matrix[0][0] = 1; // Initializing elements

OR
 int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
 Example: Printing a 2D Array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
JAGGED ARRAYS IN JAVA
 Definition:
 A jagged array is an array of arrays with variable
column sizes.
 Declaration & Initialization
int[][] jaggedArray = new int[3][]; // Declaring a jagged
array
jaggedArray[0] = new int[2]; // First row has 2
elements
jaggedArray[1] = new int[4]; // Second row has 4
elements
jaggedArray[2] = new int[3]; // Third row has 3
elements
EXAMPLE: PRINTING A JAGGED ARRAY
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
ARRAY OF OBJECTS IN JAVA
 Definition:
 Arrays can store objects instead of primitive data
types.
 Example: Student Class with Array of Objects
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + " " + age);
}
}
ARRAY OF OBJECTS IN JAVA
public class Main {
public static void main(String[] args) {
Student[] students = new Student[3]; // Array of Student objects
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 21);

for (Student s : students) {


s.display();
}
}
}
SORTING AN ARRAY IN JAVA
 Using Arrays.sort() Method
import java.util.Arrays;//you need to import Arrays from java.util
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1};
Arrays.sort(arr); // Sorting the array using Arrays.
//Arrays.toString() method is implemented for all arrays
//which prints all the elements of the array
System.out.println(Arrays.toString(arr)); // Output: [1, 2, 3, 5, 8]
String str[]={"Tina","Mina","Sina","Nita","Nikita"};
Arrays.sort(str);//strings also can be sorted as compareTo() method is
implemented in strings
System.out.print(Arrays.toString(str));
//but other array of objects need to implement compareTo() or use
//Comparator, which we will discuss later
}
}
SORTING AN ARRAY IN JAVA
 Using Bubble Sort Algorithm
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1};
for (int i = 0; i < arr.length - 1; i++) {//pass loop
for (int j = 0; j < arr.length - 1 - i; j++)//pass-i comparisons {
//if out of order
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));//printing array
}
}


UNDERSTANDING THE STATIC KEYWORD IN
JAVA

 Definition:
 The static keyword is used for memory management
in Java.
 It applies to variables, methods, and blocks.
 Key Features:
 Belongs to the class rather than an instance.
 Allocated only once when the class is loaded.
USING STATIC
 static keyword can be used in three scenarios:

 For class variables

 For methods

 For a block of code

note
USING STATIC (CONTD…)
 static variable
 Belongs to a class
 A single copy to be shared by all instances of the class
 Creation of instance not necessary for using static variables
 Accessed using <class-name>.<variable-name> unlike instance
variables which are accessed as <object-name>.<variable-name>

 static method
 It is a class method
 Accessed using class name.method name
 Creation of instance not necessary for using static methods
 A static method can access only other static data & methods, and
not non-static members
note
STATIC VARIABLES & METHODS
 Static Variable
Example
class Example {
static int count = 0; // Shared across public class Main {
all instances public static void main(String[] args) {
Example obj1 = new Example();
Example() { Example obj2 = new Example();
obj1.display(); // Output: Count: 2
count++;
obj2.display(); // Output: Count: 2
} }
}
void display() {
System.out.println("Count: " +
count);
}
}
USING STATIC (CONTD…)
class Student { The static studCount variable is
private int rollNo; initialized to 0, ONLY when the class is
first loaded, NOT each time a new
private static int studCount; instance is made

public Student(){
studCount++;
Each time the constructor is invoked, i.e.
} an object gets created, the static variable
studCount will be incremented thus keeping
public void setRollNo (int r){ a count of the total no of Student objects
created
rollNo = r;
}
public int getRollNo (int r){ Which Student? Whose rollNo? A
static method cannot access anything
return rollNo; non-static

}
public static void main(String args[]){
System.out.println(“RollNo of the Student is;” +
rollNo);
}
}
STATIC METHOD EXAMPLE
class MathUtils {
// Static method for addition
static int add(int a, int b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
// Calling the static method without creating an object
int sum = MathUtils.add(10, 20);
System.out.println("Sum: " + sum);
}
}
STATIC BLOCK
 Java supports a special block, called a static block
(also called static clause) that can be used for
static initialization of a class.
 This code inside the static block is executed only
once: the first time the class is loaded into memory
 static block executes automatically when the class
is loaded in memory.
 Refer: TestStaticBlock.java
ARRAYS IN JAVA: EXAMPLE
A Café provides a small list of items in the menu as under:
1. Cheese Burger
2. Chocolate Cake
3. Cold Coffee
4. Cappuccino
5. Cheese Pizza
Consider an Order placed at the Café
The order consists of a list of items along with the quantity and price
of each item.
Create a class called Order with data: order_id,
item[],item_price[],item_qty[]
Write a method called calculateTotal() which computes total for a
given order. Create an array of orders in main() and call the
calculateBill() method for all orders.
Later, call a method called analyseOrders(Order[], int total) which
finds which orders fetch more than the given total.
THANK YOU

You might also like