Unit - Iii - Arrays Updated
Unit - Iii - Arrays Updated
ARRAYS
Introduction to Arrays
An array is a data structure that allows you to store multiple values of the same type in a single
variable. Arrays are useful for organizing large amounts of data and are a fundamental part of
many algorithms.
Key Concepts:
Array: A collection of elements, all of the same type, stored in contiguous memory
locations.
Element: Each item in an array.
Index: The position of an element in the array, starting from 0.
You need to declare an array before you can use it. Declaration involves specifying the type of
elements and the array name. Initialization involves allocating memory for the array and
optionally setting its values.
Declaration Syntax:
java
Copy code
type[] arrayName;
Example:
java
Copy code
int[] numbers;
Initialization Syntax:
java
Copy code
arrayName = new type[size];
Example:
java
Copy code
numbers = new int[5];
You can also declare and initialize an array in a single line:
java
Copy code
int[] numbers = new int[5]; // declares an array of integers with 5 elements
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // declares and initializes an array with values
Arrays are stored in contiguous memory locations. Each element is placed next to its neighbor,
which allows for efficient indexing and access.
Memory Layout:
Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // assumes int size is 4 bytes
numbers[0] is stored at address baseAddress.
numbers[1] is stored at address baseAddress + 4.
Example Code
java
Copy code
public class ArrayExample {
public static void main(String[] args) {
// Declaration and initialization
int[] numbers = new int[5];
// Assigning values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Syntax
java
Copy code
arrayName[index]
Example
java
Copy code
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
You can perform various operations on array elements such as updating values, iterating through
elements, and performing calculations.
Example
java
Copy code
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Updating an element
numbers[2] = 10;
When you assign one array to another, both arrays reference the same memory location.
Example
java
Copy code
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = original;
Independent Copies
To create an independent copy of an array, you can use the Arrays.copyOf() method or clone the
array.
Example
java
Copy code
import java.util.Arrays;
In Java, arrays have a fixed size. To dynamically change the size of an array, you can create a
new array with the desired size and copy the elements from the old array to the new one.
Example
java
Copy code
import java.util.Arrays;
For dynamic sizing without manual copying, you can use an ArrayList, which resizes
automatically.
Example
java
Copy code
import java.util.ArrayList;
// Adding elements
numbers.add(1);
numbers.add(2);
numbers.add(3);
// Removing elements
numbers.remove(1); // Removes the element at index 1
// Accessing elements
System.out.println(numbers.get(1)); // Output: 3
Sorting of Arrays
Java provides various ways to sort arrays. The Arrays class in the java.util package has a static
method called sort which can be used to sort arrays.
Example
java
Copy code
import java.util.Arrays;
Sorting Strings
java
Copy code
import java.util.Arrays;
The Arrays class provides a method called binarySearch for searching values in a sorted array.
Example
java
Copy code
import java.util.Arrays;
Class Arrays
The Arrays class provides various utility methods for arrays, such as sorting, searching, filling,
comparing, etc.
Example Methods
Example
java
Copy code
import java.util.Arrays;
Two-Dimensional Arrays
Two-dimensional arrays are arrays of arrays. They are used to represent data in a grid or table
format.
// Accessing elements
System.out.println(matrix[0][0]); // 1
System.out.println(matrix[1][2]); // 6
Jagged arrays are arrays of arrays where each sub-array can have a different length.
Example
java
Copy code
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jaggedArray = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
Three-Dimensional Arrays
// Accessing elements
System.out.println(cube[0][1][2]); // 6
System.out.println(cube[1][0][1]); // 8
In Java, arrays can be used similarly to vectors, but for dynamic array functionality, the ArrayList
class from the java.util package is usually preferred.
// Adding elements
vector.add(1);
vector.add(2);
vector.add(3);
// Accessing elements
System.out.println(vector.get(0)); // 1
System.out.println(vector.get(1)); // 2
// Removing elements
vector.remove(1); // Removes the element at index 1
Inheritance Introduction
Example
java
Copy code
// Superclass
public class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
Process of Inheritance
1. Subclass Definition: Define a new class that extends an existing class.
2. Inheritance of Members: The subclass inherits accessible fields and methods from the
superclass.
3. Addition of New Members: The subclass can add new fields and methods.
4. Override Methods: The subclass can override methods from the superclass to provide specific
implementations.
Example
java
Copy code
public class Bird extends Animal {
public void fly() {
System.out.println("The bird flies.");
}
@Override
public void eat() {
System.out.println("The bird eats seeds.");
}
}
In Java, every class implicitly inherits from the Object class if no other superclass is specified.
The Object class is the root of the class hierarchy.
Key Methods of Object
public int hashCode(): Returns a hash code value for the object.
public final Class<?> getClass(): Returns the runtime class of this object.
Example
java
Copy code
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
System.out.println(dog.toString());
System.out.println(dog.hashCode());
}
}
The final keyword can be used to prevent a class from being subclassed or to prevent methods
from being overridden.
Final Class
Example
java
Copy code
public final class FinalClass {
// Class code
}
Final Methods
Example
java
Copy code
public class BaseClass {
public final void finalMethod() {
System.out.println("This is a final method.");
}
}
Practical Usage
Final Classes: Used when a class should not be extended. For example, String class is final in
Java.
Final Methods: Used to prevent specific methods from being overridden to maintain consistent
behavior.
Access control in Java defines the visibility and accessibility of classes, methods, and variables.
It is crucial in object-oriented programming to encapsulate and protect data.
Access Modifiers
1. Private (private)
o Accessible only within the same class.
3. Protected (protected)
o Accessible within the same package and by subclasses, even if they are in different
packages.
4. Public (public)
Example
java
Copy code
public class Parent {
private int privateVar = 1;
int defaultVar = 2;
protected int protectedVar = 3;
public int publicVar = 4;
Multilevel Inheritance
Multilevel inheritance is a type of inheritance where a class is derived from another class, which
is also derived from another class, forming a chain.
Example
java
Copy code
class A {
void methodA() {
System.out.println("Class A Method");
}
}
class B extends A {
void methodB() {
System.out.println("Class B Method");
}
}
class C extends B {
void methodC() {
System.out.println("Class C Method");
}
}
The super keyword in Java is used to refer to the immediate parent class object. It is used to
access parent class members (variables and methods) and to call the parent class constructor.
void display() {
System.out.println("Parent class method");
}
}
void display() {
System.out.println("Child class method");
}
void print() {
// Accessing parent class variable
System.out.println("Parent num: " + super.num);
Key Points
super: Used to access parent class members and call parent class constructors.
Multilevel Inheritance: Allows a chain of inheritance, where a class is derived from another
derived class.
A constructor in the base (super) class is used to initialize the instance variables of that class.
Example
java
Copy code
class Animal {
String name;
// Constructor
Animal(String name) {
this.name = name;
}
}
When a derived (sub) class is instantiated, the constructor of the base class is called first. You
can explicitly call the base class constructor using the super keyword.
Example
java
Copy code
class Dog extends Animal {
int age;
// Constructor
Dog(String name, int age) {
super(name); // Call to the superclass constructor
this.age = age;
}
Method Overriding
Example
java
Copy code
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
Example
java
Copy code
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
a = new Cat();
a.makeSound(); // Output: Cat meows
}
}
Abstract Classes
An abstract class cannot be instantiated and may contain abstract methods, which are methods
declared without an implementation. Subclasses of the abstract class must provide
implementations for these abstract methods.
Example
java
Copy code
abstract class Animal {
abstract void makeSound();
An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot contain
instance fields or constructors.
Interface Declaration
java
Copy code
interface Animal {
void makeSound();
void eat();
}
Implementing an Interface
A class implements an interface by providing concrete implementations for all of its methods.
Example
java
Copy code
interface Animal {
void makeSound();
void eat();
}
@Override
public void eat() {
System.out.println("Dog eats");
}
}
Java supports multiple inheritance of type using interfaces. A class can implement multiple
interfaces.
Example
java
Copy code
interface Animal {
void makeSound();
}
interface Pet {
void play();
}
@Override
public void play() {
System.out.println("Dog plays");
}
}
Interfaces can have default methods with an implementation. This allows the addition of new
methods to interfaces without breaking the existing implementation.
Example
java
Copy code
interface Animal {
void makeSound();
Interfaces Introduction
An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot contain
instance fields or methods that implement behavior (except default methods). Interfaces provide
a way to achieve abstraction and multiple inheritance in Java.
Key Points
An interface can extend another interface, thereby inheriting its abstract methods.
Declaration of Interfaces
Syntax
java
Copy code
public interface MyInterface {
// Constant fields
int MY_CONSTANT = 100;
// Abstract methods
void abstractMethod();
}
Example
java
Copy code
public interface Animal {
void eat();
void sleep();
}
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}
Java 8 introduced default methods, which allow developers to add new methods to interfaces
without breaking the existing implementation of the classes that implement these interfaces.
Default methods are defined with the default keyword.
Syntax
java
Copy code
public interface MyInterface {
void abstractMethod();
Example
java
Copy code
public interface Animal {
void eat();
void sleep();
@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
// Dog does not override makeSound() method, so it uses the default implementation
}
Static methods in interfaces are similar to static methods in classes. They are associated with the
interface rather than any instance of the implementing class. They are defined using the static
keyword.
Syntax
java
Copy code
public interface MyInterface {
static void staticMethod() {
System.out.println("This is a static method.");
}
}
Example
java
Copy code
public interface Animal {
void eat();
void sleep();
Functional Interfaces
A functional interface is an interface that contains only one abstract method. They can have
multiple default or static methods. Functional interfaces are used as the basis for lambda
expressions and method references in Java.
Example
java
Copy code
@FunctionalInterface
public interface MyFunctionalInterface {
void singleAbstractMethod();
// Default methods
default void defaultMethod() {
System.out.println("Default method");
}
// Static methods
static void staticMethod() {
System.out.println("Static method");
}
}
Annotations
Annotations provide metadata about the program. They are used by the compiler and can also be
used at runtime. Commonly used annotations include @Override, @Deprecated, and
@SuppressWarnings.
Example
java
Copy code
public class AnnotationExample {
@Override
public String toString() {
return "Annotation Example";
}
@Deprecated
public void deprecatedMethod() {
System.out.println("This method is deprecated.");
}
@SuppressWarnings("unchecked")
public void uncheckedMethod() {
// Code that generates unchecked warnings
}
}
Custom Annotations
You can create your own annotations by using the @interface keyword.
Example
java
Copy code
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyCustomAnnotation {
String value();
}