0% found this document useful (0 votes)
11 views27 pages

Unit - Iii - Arrays Updated

This document provides an overview of arrays in Java, detailing their structure, declaration, initialization, and memory storage. It covers operations on arrays, including accessing elements, assigning arrays, and dynamic sizing, as well as introducing two-dimensional and three-dimensional arrays. Additionally, it touches on inheritance in Java, explaining its principles, the Object class, and the use of the final keyword to inhibit inheritance.

Uploaded by

Praveena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Unit - Iii - Arrays Updated

This document provides an overview of arrays in Java, detailing their structure, declaration, initialization, and memory storage. It covers operations on arrays, including accessing elements, assigning arrays, and dynamic sizing, as well as introducing two-dimensional and three-dimensional arrays. Additionally, it touches on inheritance in Java, explaining its principles, the Object class, and the use of the final keyword to inhibit inheritance.

Uploaded by

Praveena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT – III

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.

Declaration and Initialization of Arrays

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

Declaring and Initializing with Values:

java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // declares and initializes an array with values

Storage of Arrays in Computer Memory

Arrays are stored in contiguous memory locations. Each element is placed next to its neighbor,
which allows for efficient indexing and access.

Memory Layout:

 The base address is the memory location of the first element.


 The size of the array determines the total amount of memory allocated.
 The index of an element is used to calculate its address in memory.

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.

 numbers[2] is stored at address baseAddress + 8.

Example Code

Declaration, Initialization, and Access

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]);
}
}
}

Accessing Elements of an Array

In Java, arrays are accessed using their index, starting from 0.

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};

// Accessing elements of the array


System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[2]); // Output: 30
}
}

Operations on Array Elements

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;

// Iterating through the array


for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

// Calculating the sum of elements


int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum);
}
}

Assigning One Array to Another Array

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;

// Modifying the copy array


copy[0] = 10;

// Both arrays reflect the change


System.out.println(original[0]); // Output: 10
System.out.println(copy[0]); // Output: 10
}
}

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;

public class Main {


public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, original.length);

// Modifying the copy array


copy[0] = 10;

// Original array remains unchanged


System.out.println(original[0]); // Output: 1
System.out.println(copy[0]); // Output: 10
}
}

Dynamic Change of Array Size

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;

public class Main {


public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};

// Creating a new array with a larger size


int[] largerArray = new int[original.length + 5];

// Copying elements from the original array to the new array


System.arraycopy(original, 0, largerArray, 0, original.length);

// The new array has additional space for more elements


System.out.println(Arrays.toString(largerArray)); // Output: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

// Adding new elements to the larger array


largerArray[5] = 6;
largerArray[6] = 7;

System.out.println(Arrays.toString(largerArray)); // Output: [1, 2, 3, 4, 5, 6, 7, 0, 0, 0]


}
}

Using ArrayList for Dynamic Sizing

For dynamic sizing without manual copying, you can use an ArrayList, which resizes
automatically.

Example

java
Copy code
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new 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

// Iterating through the list


for (int num : numbers) {
System.out.println(num);
}
}
}

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;

public class SortArrayExample {


public static void main(String[] args) {
int[] numbers = {5, 2, 8, 14, 1};

Arrays.sort(numbers); // Sorting the array in ascending order

System.out.println("Sorted array: " + Arrays.toString(numbers));


}
}

Sorting Strings
java
Copy code
import java.util.Arrays;

public class SortStringArrayExample {


public static void main(String[] args) {
String[] names = {"John", "Alice", "Bob"};
Arrays.sort(names); // Sorting the array of strings

System.out.println("Sorted array: " + Arrays.toString(names));


}
}

Searching for Values in Arrays

The Arrays class provides a method called binarySearch for searching values in a sorted array.

Example
java
Copy code
import java.util.Arrays;

public class SearchArrayExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 5, 8, 14};

int index = Arrays.binarySearch(numbers, 8); // Searching for the value 8

System.out.println("Index of 8: " + index); // Output: 3


}
}

Class Arrays

The Arrays class provides various utility methods for arrays, such as sorting, searching, filling,
comparing, etc.

Example Methods

 Arrays.sort(): Sorts the array.


 Arrays.binarySearch(): Searches for a value in a sorted array.

 Arrays.fill(): Fills the array with a specified value.

 Arrays.equals(): Compares two arrays.

 Arrays.toString(): Returns a string representation of the array.

Example
java
Copy code
import java.util.Arrays;

public class ArraysClassExample {


public static void main(String[] args) {
int[] numbers = {5, 2, 8, 14, 1};
// Filling the array with 0
Arrays.fill(numbers, 0);
System.out.println("Array after fill: " + Arrays.toString(numbers)); // [0, 0, 0, 0, 0]

// Comparing two arrays


int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
System.out.println("Arrays are equal: " + Arrays.equals(array1, array2)); // true
}
}

Two-Dimensional Arrays

Two-dimensional arrays are arrays of arrays. They are used to represent data in a grid or table
format.

Declaration and Initialization


java
Copy code
public class TwoDimensionalArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing elements
System.out.println(matrix[0][0]); // 1
System.out.println(matrix[1][2]); // 6

// Iterating over elements


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();
}
}
}

Arrays of Varying Lengths (Jagged Arrays)

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}
};

// Iterating over elements


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();
}
}
}

Three-Dimensional Arrays

Three-dimensional arrays are arrays of two-dimensional arrays.

Declaration and Initialization


java
Copy code
public class ThreeDimensionalArrayExample {
public static void main(String[] args) {
int[][][] cube = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};

// Accessing elements
System.out.println(cube[0][1][2]); // 6
System.out.println(cube[1][0][1]); // 8

// Iterating over elements


for (int i = 0; i < cube.length; i++) {
for (int j = 0; j < cube[i].length; j++) {
for (int k = 0; k < cube[i][j].length; k++) {
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Arrays as Vectors

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.

Example Using ArrayList


java
Copy code
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<Integer> vector = new ArrayList<>();

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

// Iterating over elements


for (int i = 0; i < vector.size(); i++) {
System.out.print(vector.get(i) + " ");
}
}
}

Inheritance Introduction

Inheritance is a fundamental concept of object-oriented programming (OOP) that allows a new


class (subclass or derived class) to inherit fields and methods from an existing class (superclass
or base class). This promotes code reuse and establishes a natural hierarchy between classes.

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.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}

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.");
}
}

public class Main {


public static void main(String[] args) {
Bird bird = new Bird();
bird.eat(); // Overridden method in Bird
bird.fly(); // Method in Bird
}
}

Universal Superclass: Object

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 String toString(): Returns a string representation of the object.


 public boolean equals(Object obj): Compares this object to the specified 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());
}
}

Inhibiting Inheritance of Class Using final

The final keyword can be used to prevent a class from being subclassed or to prevent methods
from being overridden.

Final Class

A class declared as final cannot be extended.

Example
java
Copy code
public final class FinalClass {
// Class code
}

// This will cause an error


// public class SubClass extends FinalClass {}

Final Methods

A method declared as final cannot be overridden by subclasses.

Example
java
Copy code
public class BaseClass {
public final void finalMethod() {
System.out.println("This is a final method.");
}
}

public class SubClass extends BaseClass {


// This will cause an error
// public void finalMethod() {
// System.out.println("Trying to override 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.

Example: Using Inheritance and Final Class


java
Copy code
public class Vehicle {
public void startEngine() {
System.out.println("The engine is starting.");
}
}

public class Car extends Vehicle {


@Override
public void startEngine() {
System.out.println("The car engine is starting.");
}
}

public final class SportsCar extends Car {


@Override
public void startEngine() {
System.out.println("The sports car engine is starting.");
}
}

// This will cause an error


// public class SuperSportsCar extends SportsCar {}

public class Main {


public static void main(String[] args) {
SportsCar sportsCar = new SportsCar();
sportsCar.startEngine(); // The sports car engine is starting.
}
}
Access Control and Inheritance

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.

o Not accessible by subclasses or other classes in the same package.

2. Default (no modifier)

o Accessible only within the same package.

o Also known as package-private.

3. Protected (protected)

o Accessible within the same package and by subclasses, even if they are in different
packages.

4. Public (public)

o Accessible from any other class.

Example
java
Copy code
public class Parent {
private int privateVar = 1;
int defaultVar = 2;
protected int protectedVar = 3;
public int publicVar = 4;

public void display() {


System.out.println("Private: " + privateVar);
System.out.println("Default: " + defaultVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Public: " + publicVar);
}
}

public class Child extends Parent {


public void displayChild() {
// System.out.println("Private: " + privateVar); // Error: privateVar is not accessible
System.out.println("Default: " + defaultVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Public: " + publicVar);
}
}

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");
}
}

public class MultilevelInheritanceDemo {


public static void main(String[] args) {
C obj = new C();
obj.methodA(); // Inherited from class A
obj.methodB(); // Inherited from class B
obj.methodC(); // Method of class C
}
}

Application of Keyword super

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.

Using super to Access Parent Class Members


java
Copy code
class Parent {
int num = 100;

void display() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


int num = 200;

void display() {
System.out.println("Child class method");
}

void print() {
// Accessing parent class variable
System.out.println("Parent num: " + super.num);

// Accessing parent class method


super.display();
}
}

public class SuperDemo {


public static void main(String[] args) {
Child obj = new Child();
obj.print();
}
}

Using super to Call Parent Class Constructor


java
Copy code
class Parent {
Parent() {
System.out.println("Parent class constructor");
}
}

class Child extends Parent {


Child() {
// Calling parent class constructor
super();
System.out.println("Child class constructor");
}
}

public class SuperConstructorDemo {


public static void main(String[] args) {
Child obj = new Child();
}
}

Example of Multilevel Inheritance with super


java
Copy code
class Grandparent {
void display() {
System.out.println("Grandparent class method");
}
}

class Parent extends Grandparent {


void display() {
super.display();
System.out.println("Parent class method");
}
}

class Child extends Parent {


void display() {
super.display();
System.out.println("Child class method");
}
}

public class MultilevelSuperDemo {


public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}

Key Points

 Private Members: Not accessible by child classes.


 Default Members: Accessible by child classes within the same package.

 Protected Members: Accessible by child classes even in different packages.

 Public Members: Accessible from any class.

 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.

Constructor Method and Inheritance

Constructor in a Base 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;
}
}

Constructor in a Derived Class

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;
}

public void display() {


System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


Dog d = new Dog("Buddy", 5);
d.display(); // Output: Name: Buddy, Age: 5
}
}

Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method


already defined in its superclass. The method in the subclass must have the same signature as the
method in the superclass.

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");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Dog barks
}
}

Dynamic Method Dispatch

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at


runtime rather than compile-time. This is achieved through 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");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Animal a;
a = new Dog();
a.makeSound(); // Output: Dog barks

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();

public void sleep() {


System.out.println("Animal is sleeping");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks
d.sleep(); // Output: Animal is sleeping
}
}

Interfaces and Inheritance

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();
}

class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}

@Override
public void eat() {
System.out.println("Dog eats");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks
d.eat(); // Output: Dog eats
}
}

Multiple Inheritance with Interfaces

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();
}

class Dog implements Animal, Pet {


@Override
public void makeSound() {
System.out.println("Dog barks");
}

@Override
public void play() {
System.out.println("Dog plays");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks
d.play(); // Output: Dog plays
}
}

Default Methods in Interfaces

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();

default void sleep() {


System.out.println("Animal is sleeping");
}
}

class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks
d.sleep(); // Output: Animal is sleeping
}
}

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

 Interfaces are declared using the interface keyword.


 A class implements an interface by using the implements keyword.

 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();
}

public class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog is eating");
}

@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}

Default Methods in Interfaces

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();

default void defaultMethod() {


System.out.println("This is a default method.");
}
}

Example
java
Copy code
public interface Animal {
void eat();
void sleep();

default void makeSound() {


System.out.println("Animal makes a sound");
}
}

public class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog is eating");
}

@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

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();

static void showInfo() {


System.out.println("This is an animal interface.");
}
}

public class Main {


public static void main(String[] args) {
Animal.showInfo(); // Calling static method of the interface
}
}

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");
}
}

Usage with Lambda Expressions


java
Copy code
public class Main {
public static void main(String[] args) {
MyFunctionalInterface func = () -> System.out.println("Lambda expression");
func.singleAbstractMethod();
}
}

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();
}

public class CustomAnnotationExample {


@MyCustomAnnotation(value = "Custom annotation example")
public void annotatedMethod() {
System.out.println("This method is annotated with @MyCustomAnnotation.");
}

public static void main(String[] args) {


CustomAnnotationExample example = new CustomAnnotationExample();
example.annotatedMethod();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy