0% found this document useful (0 votes)
8 views9 pages

Arrays

The document provides an overview of arrays in Java, detailing primitive and reference types, their memory allocation, and default values. It explains how to declare, create, and initialize arrays, along with examples of passing arrays to methods and modifying them. Additionally, it includes various examples demonstrating array operations such as finding maximum values, reversing arrays, and user input handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Arrays

The document provides an overview of arrays in Java, detailing primitive and reference types, their memory allocation, and default values. It explains how to declare, create, and initialize arrays, along with examples of passing arrays to methods and modifying them. Additionally, it includes various examples demonstrating array operations such as finding maximum values, reversing arrays, and user input handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Arrays

1. Primitive Types

Primitive types are the most basic data types predefined by Java. They store single
values directly in the variable.

Memory: They are stored in Stack memory.

Default Value: They always have a default value (e.g., int defaults to 0, boolean to
false).

Behavior: When you assign one primitive to another, a copy of the value is created.

Types: There are 8 types: byte, short, int, long, float, double, boolean, char.

Example:

int a = 10;

int b = a; // b gets a copy of 10

int b = 20; // Changing b does not affect a (a is still 10)

2. Reference Types (Non-Primitive)

Reference types refer to objects. Instead of storing the actual data, the variable stores
the memory address (reference) where the object is located.

Memory: The actual object is stored in Heap memory, while the reference (address) is
stored in the Stack.

Default Value: Their default value is null.

Behavior: When you assign one reference variable to another, both point to the same
object in memory.

Types: Examples include String, Arrays, Classes, and Interfaces.

Example:

int[ ] list1 = {99, 2, 3};

int[ ] list2 = list1; // list2 now points to the same memory address as list1

list2[0] = 99; // This changes list1[0] to 99 as well!


1. Arrays in Java:

An array is a group of variables (called elements or components)


containing values that all have the same type. Arrays are objects, so
they’re considered reference types.
A program refers to any one of these elements with an array-access
expression that includes the name of the array followed by the index of
the particular element in square brackets ([ ]). The first element in every
array has index zero and is sometimes called the zeroth element.

2. Declaring and Creating Arrays

// 1. Declaration
int[ ] numbers;

// 2. Allocation (Creating space for 5 integers)


numbers = new int[5]; // user input

// 3. Initialization (Assigning values)


numbers[0] = 10;
numbers[1] = 20;

// Declaration and Initialization


int[] marks = {85, 90, 75, 88, 92};

Complete example:

public class New {


public static void main(String[] args) {
// Creating an array of Strings
String[] cars = {"Volvo", "BMW", "Fortuner", "Suzuki"};

S.O.P ("First car: " + cars[0]); // Volvo

// Finding the length of the array


S.O.P ("Array Size: " + [Link]); // 4

// Changing an element
cars[0] = "Toyota";
S.O.P ("Updated first car: " + cars[0]); // Volvo = Toyota
}}
Using new keyword:
public class ArrayExample {
public static void main(String[ ] args) {

// This creates 3 "boxes" in memory, all initialized to 0 by default.


int[] scores = new int[3];

// Step 2: Assigning values to those boxes


scores[0] = 90;
scores[1] = 85;
scores[2] = 70;
S.O.P ("Score at index 1 is: " + scores[1]); //85
}
}

Example 2:

import [Link];
public class OOP {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);

// 2. Ask for the size of the array


[Link]("Enter the number of students: ");
int size = [Link](); //Size variable

// 3. Create (Allocate) the array using 'new'


int[] marks = new int[size];

// 4. Initialize the array using a loop

[Link]("Enter marks for " + size + " students:");


for (int i = 0; i < size; i++) {
[Link]("Student " + (i + 1) + ": ");
marks[i] = [Link](); // Taking input for each index
}

// 5. Display the stored values


[Link](" Student Marks List ");
for (int i = 0; i < size; i++) {
[Link]("Student " + (i + 1) + " scored: " + marks[i]);
}
}
}

Output:

Enter the number of students: 3


Enter marks for 3 students:
Student 1: 85
Student 2: 92
Student 3: 78

--- Student Marks List ---


Student 1 scored: 85
Student 2 scored: 92
Student 3 scored: 78

Example 3:

import [Link];

public class NameList {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("How many friends do you want to list? ");


int count = [Link](); // no of friends
[Link]();

String[] friends = new String[count];

for (int i = 0; i < count; i++) {


[Link]("Enter name of friend " + (i + 1) + ": ");
friends[i] = [Link]();
}

[Link]("\nYour Friend List:");


for (String name : friends) { // Friends are string type
[Link]("Hello, " + name + "!");
}
}
}
Output:
How many friends do you want to list? 2
Enter name of friend 1: Ali
Enter name of friend 2: Ahmed

Your Friend List:


Hello, Ali!
Hello, Ahmed!

Example 4:
public class SumArray {
public static void main(String[] args) {
int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
int total = 0;

for (int i = 0; i < [Link]; i++) {


total += array[i]; // Logic added here
[Link]("Total of array elements:” + total);
}
}

Output:
Total of array elements: 849

3. Passing Arrays to Methods


In Java, when you pass an array to a method, you are passing the reference (the
memory address) of the array, not a copy of the actual values. This is because arrays
are Reference Types. This means if you modify the array inside the method, the
changes will reflect in the original array as well.

Example 1:

public class PassArray {

public static void main(String[] args) {

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

S.O.P("Before method call: " + myNumbers[0]); // Output: 1

// Passing the array to the method

modifyArray(myNumbers); //method create

S.O.P("After method call: " + myNumbers[0]); // Output: 2


}

public static void modifyArray(int[] arr) {

for (int i = 0; i < [Link]; i++) {

arr[i] = arr[i] * 2; // Doubling the value // arr 0= 1*2=2, 2*2=4 }

Example 2:

public class MaxFinder {

public static void main(String[] args) {

int[] scores = {45, 92, 78, 95, 88};

// Method call: Passing the array

findMax(scores);

[Link]("The highest score is: " + highest); // 95

// Method definition

public static int findMax(int[] arr) {

int max = arr[0]; // 45 max suppose

for (int i = 1; i < [Link]; i++) {

if (arr[i] > max) { // 92>45, 78>92,, 95>92, , 88>95

max = arr[i]; // 95

return max; //

Output:
The array is initialized with the values: {45, 92, 78, 95, 88}.

Action: max = 45

Comparison 1: It checks: "Is 92 > 45?" Yes! Since 92 is larger, the old max is replaced.

New Max: 92

Comparison 2: It checks: "Is 78 > 92?" No. The current max remains unchanged.

Current Max: 92

Comparison 3: It checks: "Is 95 > 92?" Yes! A new champion is found.

New Max: 95

Comparison 4: It checks: "Is 88 > 95?" No. 95 is still the winner.

Final Max: 95

Example 3:

import [Link];

public class ReverseArray {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter numbers you want? ");

int n = [Link]();

int[] original = new int[n]; //array size

for (int i = 0; i < n; i++) {

[Link]("Enter number " + (i+1) + ": ");

original[i] = [Link](); //save user input }

// Method call:

reverse(original);

[Link]("\nReversed Array:")

}
public static void reverse(int[] arr) {

int start = 0; // {10, 20, 30, 40},

int end = [Link] - 1; 5-1=4

while (start < end) { 10<40, 20<30

// Swapping elements

int temp = arr[start]; // temp=10; temp=20

arr[start] = arr[end]; // arr start= 40 arr start =30

arr[end] = temp; // , arr end= 10 arr end=20 {40,30,20,10}

start++;

end--;

Output:

Original: [10,20,30,40]

Reverse:[40,30,20,10]

Check: Is start (0) < end (3)? Yes.

Action (Swap): The value at start (10) and end (40) are swapped.

Result: The array becomes [40, 20, 30, 10].

Update: start moves forward to 1, end moves backward to 2.

Iteration 2:

Check: Is start (1) < end (2)? Yes.

Action (Swap): The value at start (20) and end (30) are swapped.

Result: The array becomes [40, 30, 20, 10].


Update: start moves forward to 2, end moves backward to 1.

Final Condition Check:

Check: Is start (2) < end (1)? No.

Result: The pointers have met or crossed each other in the middle. The while loop
terminates (stops).

You might also like