Unit-3 Java (R23)
Unit-3 Java (R23)
Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to Another Array,
Dynamic Change of Array Size, Sorting of Arrays, Search for Values in Arrays, Class Arrays, Two-
dimensional Arrays, Arrays of Varying Lengths, Three-dimensional Arrays, Arrays as Vectors.
Arrays
An array is a group of continuous or related items that share a common name.
For instance, we can define an array name salary to represent a set of salaries of a group of employees.
A particular value is indicated by writing a number called index number or subscript in brackets after the
array name.
One –Dimensional Arrays
A list of items can be given one variable name using only one subscript and such a variable is called a
single-subscripted variable or a one-dimensional array.
Declaration of Array :
Arrays in java may be declared in two forms
Form1
type arrayname[ ];
Form2
type[ ] arrayname;
Creating Arrays :
you can create an array by using the new operator by using syntax
Syntax:
arrayname=new type[array_Size];
It creates an array using new type[array_Size]
It assigns the reference of the newly created array to the variable arrayname.
Declaring , Creating and assigning an array to the variable can be combined in one statement as:
type[]=arrayname=new type[array_Size];
(or)
type[] arrayname={value0, value 1,…..value k};
Array indices are start from 0 to arrayname. length-1
where Base_address is the memory address of the first element in the array, i is the index, and
size_of_element is the size of each array element in bytes.
3. Memory Layout Example:
o Consider the following integer array:
Address Value
1000 10 (arr[0])
1004 20 (arr[1])
1008 30 (arr[2])
1012 40 (arr[3])
1016 50 (arr[4])
o Here, each element takes 4 bytes (since it's an int), and the elements are stored consecutively.
Multi-Dimensional Arrays:
o In the case of multi-dimensional arrays (e.g., 2D arrays), the elements are stored in row-major
order in Java. This means that the elements of each row are stored sequentially in memory.
o Consider a 2D array:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
In memory, this array would be laid out as:
Address Value
1000 1 (matrix[0][0])
1004 2 (matrix[0][1])
1008 3 (matrix[0][2])
1012 4 (matrix[1][0])
1016 5 (matrix[1][1])
1020 6 (matrix[1][2])
1024 7 (matrix[2][0])
1028 8 (matrix[2][1])
1032 9 (matrix[2][2])
o row are stored first, followed by the elements of the second row, and so on.
2. Inefficient Insertion/Deletion:
o Inserting or deleting elements in the middle of an array requires shifting elements, which can
be slow (O(n) time complexity).
class ArrayOperations {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int min = numbers[0];
To compare two arrays in Java, you need to determine if they are equal in terms of their content and
order. You can use the Arrays class from the java.util package, which provides utility methods for
comparing arrays.
Using Arrays.equals()
The Arrays.equals() method checks if two arrays are equal by comparing their length and corresponding
elements.
Example Code
import java.util.Arrays;
System.out.println();
Arrays Sorting
Array sorting refers to the process of arranging the elements of an array in a specific order,
typically in ascending or descending order. In Java, there are several ways to sort arrays,
including using built-in methods or implementing custom sorting algorithmS
public class SortArrayExample2
{
public static void main(String[] args)
{
//creating an instance of an array
int[] arr = new int[] {4,2,3,1};
System.out.println("Array elements after sorting:");
//sorting logic
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
int tmp = 0;
if (arr[i] > arr[j])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
//prints the sorted element of the array
System.out.println(arr[i]);
}
}
}
Descending Order
public class SortArrayExample2
{
public static void main(String[] args)
{
//creating an instance of an array
int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};
System.out.println("Array elements after sorting:");
//sorting logic
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
int tmp = 0;
if (arr[i] < arr[j])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
//prints the sorted element of the array
System.out.println(arr[i]);
}
}
}
Linear Search
Class LinearSearch
{
Public static void main (String args[])
{
Int a[]={10,20,40,50,30};
Int search_ele=50;
Boolean flag=false;
For(int i=0;i<a.length;i++)
{
If(search_ele==a[i])
{
System.out.println(“the element is found at :+i);
flag=true;
break;
}
}
If(flag==false)
{
System.out.println(“element is not found”);
}
}
Binary search
int key = 5;
int l = 0;
int h = a.length - 1;
while (l <= h)
{
int m = (l + h) / 2;
if (a[m] == key) {
System.out.println("Element Found..");
flag = true;
break;
}
if (a[m] < key) {
l = m + 1;
}
if (flag == false) {
System.out.println("Element NOT found..");
}
}
}
Arrays as Vectors (Vector Class in Java)
The Vector class in Java implements a dynamic array where elements can be added or removed.
It is synchronized, which means it's thread-safe for use in multi-threaded applications. However,
because of the synchronization overhead, it's generally slower than ArrayList.
Key Features of Vector:
Dynamic resizing
Can hold any type of data
Supports operations like insertion, deletion, and searching
Synchronization makes it thread-safe
Declaring and Using a Vector in Java:
import java.util.Vector;
In Java, you can create arrays of varying lengths, also known as jagged arrays or ragged arrays.
A jagged array is an array whose elements are arrays of different lengths, unlike a regular
multidimensional array where all rows have the same number of elements.
Declaring and Using Jagged Arrays
When you declare a 2D array, you don’t have to specify the size of each row. Instead, you can
assign arrays of varying lengths to each row.
Example Program: Arrays of Varying Lengths (Jagged Arrays)
java
Copy code
public class JaggedArrayExample {
public static void main(String[] args) {
// Declaring a 2D array with 3 rows
int[][] jaggedArray = new int[3][];
Defining a Subclass
A Subclass is defined as follows
Class subclassname extends superclassname
{
Variables declaration
Methods declaration
}
The keyword extends signifies that the properties of the superclassname are extended
subclassname.
The subclass will now contain its own variables and methods as well those superclass.
This kind of situation occurs when we want to add some more properties to an
existing class without actually modifying it.
1. Single inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance (Does not supports in java)
5. Multiple inheritance
Process of deriving a subclass from one or more superclasses is called multiple
inheritance. Java does not directly implement multiple inheritance.
however, this concept is implemented using a secondary inheritance path in the form of
interfaces. Class A
{
Class B
{
Method Overrididng
A method in subclass, whose name, parameter list and return type are same as that
of the method in superclass is called overrided methods.
Abstract Methods and Classes
An Abstract method is a method without method body or a method without
implementation.
An Abstract method is written when the same method has to perform different tasks
depending on the object calling it.
Example:
System.out.println(“method 2”);
A Class that contains one or more Abstract Methods is called Abstract Class.
An Abstract class is a class that contains 0 or more Abstract Methods.
Abstract class can contain instance variables and concrete methods in addition to
abstract methods. Since, abstract class contains incomplete methods, it is not possible to
estimate the total memory required to create the object.
Example:
obj1.calculate(3);
obj2.calculate(4);
obj3.calculate(5);
}
}
Example:2
final class : prevents inheritance
sometimes we may like to prevent a class being further subclasses for security reasons. A
class that cannot be subclasses is called a final class. Any attempt to inherit final classes
will cause an error and the compiler will not allow it.
final class A
{
}
Interfaces:
Defining an Interface
An Interface is basically a kind of class
Like classes, interface contain methods and variables but with a major difference.
The difference is that interfaces define only
Abstract Method &
Final and Static Variables
i.e methods are declared without any body and variables are implicitly final and static,
meaning they cannot be changed by the implementing class. They must also be initialized.
All Methods and Variables in the interface are implicitly public.
The syntax for defining an interface is very similar to that of defining a class
Interface InterfaceName
{
Abstract Methods
}
Where Interface is the keyword and InterfaceName is any valid java variable
Example:
Interface Item
void display();
}
Implementing Interface
An Interface will have 0 or more abstract methods which are all public and abstract by
default.
An Interface can have variables which are public, static and final by default,
means all the variables of the interface are constants.
Objects cannot be created to an interface whereas reference can be created.
Once interface is defined, any number of classes can implement an interface.
Also one class can implement any number of interfaces.
To Implement an interface, a class must create the complete set of methods defined by the
interface.
To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.
General form of a class that includes the implements clause looks like
// class body
}
Example
Class A Extends B Implements I1,I2
}
i.e if a class implements more than one interface, the interfaces are separated with a
comma.
Example:
Interface Bank
{
float rateOfInterest();
}
Class SBI implements Bank
{
return (7.8f);
}
return (9.8f);
}
return (8.8f);
}
class InterfaceDemo
{
Body of Interface
}
Example:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
System.out.println(“implementing meth1()…..”);
}
System.out.println(“Implementing meth2()….”);
}
System.out.println(“Implementing meth3()….”);
}
}
Class InterfaceDemo
{
obj.meth2();
obj.meth3();