0% found this document useful (0 votes)
7 views35 pages

Java Arrays and Strings Overview

Books for data science

Uploaded by

allaswarnasri
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)
7 views35 pages

Java Arrays and Strings Overview

Books for data science

Uploaded by

allaswarnasri
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

Unit-2

1. Introduction to Arrays
An array is a collection of elements (variables) of the same type, stored in contiguous
memory locations.
Arrays in Java are objects, and they can store multiple values of the same data type
(e.g., int[], String[]).
Why Use Arrays?
They provide a convenient way to store multiple values under a single variable name.
Arrays allow you to access elements using an index, making it easier to manipulate
large sets of data.
2. Declaring and Initializing Arrays
Array Declaration:
java
CopyEdit
int[] numbers; // Declaration of an array of integers String[] names; // Declaration
of an array of Strings

Array Initialization:
 Arrays can be initialized at the time of declaration.
java
CopyEdit
int[] numbers = {1, 2, 3, 4, 5}; // Initialize with values
String[] names = {"John", "Jane", "Doe"}; // Initialize String array

Size of the Array:


 In Java, arrays have a fixed size, and you must specify the number of elements
when creating the array.
int[] numbers = new int[5]; // Array of 5 integers (default values: 0)

3. Accessing Array Elements


Using Index:
 Array elements are accessed by their index. Indexing in Java starts from 0.
int firstElement = numbers[0]; // Accessing the first element String secondName =
names[1]; // Accessing the second element

Modifying Elements:
 You can modify the values of array elements by accessing them using their index.
numbers[2] = 10; // Modifying the third element to 10 names[0] = "Mike"; //
Changing the first element to "Mike"

4. Array Length
 Getting the Length of an Array:
 Every array in Java has a length property, which tells you the number of elements
in the array.
int length = [Link]; // Length of the array
[Link]("Array length: " + length);
5. Example: Basic Array Operations

Here's a simple example demonstrating how to declare, initialize, and work with
arrays:

public class ArrayExample


{
public static void main(String[] args)
{
int[] numbers = {10, 20, 30, 40, 50}; // Accessing array elements
[Link]("First element: " + numbers[0]); // Output: 10
[Link]("Second element: " + numbers[1]); // Output: 20
numbers[2] = 100; // Printing the updated array
[Link]("Updated third element: " + numbers[2]); // Output: 100 //
Length of the array
[Link]("Array Length: " + [Link]); // Output: 5 } }

6. Multi-Dimensional Arrays
 A multi-dimensional array is an array of arrays. It can be thought of as a table or
matrix.
 The most common form is a 2D array (array of arrays).
Declaration of 2D Array:
int[][] matrix = new int[3][3]; // 3x3 matrix
Initialization:
java
CopyEdit
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Accessing 2D Array Elements:
java
CopyEdit
[Link](matrix[1][2]); // Accesses the element in the second row, third
column (Output: 6)

7. Common Array Operations


 Iterating through an Array:
 You can use loops (like for or for-each) to iterate through the array and process
each element.
For Loop:
java
CopyEdit
for (int i = 0; i < [Link]; i++) { [Link](numbers[i]); }

Sorting an Array:
 Java provides utility methods like [Link]() to sort an array.

[Link](numbers); // Sorts the array in ascending order

8. Array Example with User Input

You can also accept user input to populate an array. Here’s a simple example that
takes input from the user for an array of integers:

import [Link];
public class UserInputArray
{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]); // Create an array of size 5
int[] nu1mbers = new int[5]; // Taking input from the user
[Link]("Enter 5 numbers:");
for (int i = 0; i < [Link]; i++)
{
numbers1[i] = [Link]();
} // Display the entered numbers
[Link]("Entered numbers are:");
for (int num : numbers)
{
[Link](num);
}
[Link](); } }

What are Command Line Arguments?

Command line arguments allow users to pass parameters (or values) to a Java
program when running it from the command line or terminal. These arguments
can be used to customize how the program behaves without changing the actual
code.

1. Main Method:
Java programs start execution from the main method. This method can
accept an array of strings as arguments. The format of the main method
looks like this:
2. public static void main(String[] args) {
3. // Code goes here
4. }

Here, args is an array of strings (String[] args), and it will hold the command
line arguments passed to the program.

5. Running the Program with Arguments:


Suppose you have a Java program, and you want to pass some arguments
when running it. You compile the program and run it like this:
6. java MyProgram arg1 arg2 arg3

In this example, arg1, arg2, and arg3 are the command line arguments.

7. Accessing the Arguments:


Inside the main method, you can access the arguments from the args array.
For example:

public class MyProgram {


public static void main(String[] args) {
// Check if arguments are passed
if ([Link] > 0) {
[Link]("Arguments passed:");
for (String arg : args) {
[Link](arg);
}
} else {
[Link]("No arguments passed.");
}
}
}

8. Example Usage:
Let's say you run the program like this:
9. java MyProgram Hello World 123

The output will be:

Arguments passed:
Hello
World
123

Each word is treated as a separate argument, and they are stored in the
args array.

1. Arguments are always strings: Even if you pass numbers or other types,
they will be treated as strings. You will need to convert them using
methods like [Link]() or [Link]().
2. Argument Length: The [Link] gives you the number of arguments
passed. So you can check if the user provided the right number of
arguments.
3. Error Handling: Always validate inputs. It’s good practice to check if the
arguments passed are valid and handle any errors (e.g., using try-catch
blocks).
String
In Java, a String is the type of object that can store a sequence of
characters enclosed by double quotes. A string acts the same as an array of
characters. Java provides a robust and flexible API for handling strings, allowing
for various operations such as concatenation,
1. length()

 Purpose: Returns the number of characters in the string.


 Usage:
 String str = "Hello, World!";
 int length = [Link](); // Returns 13
2. charAt(int index)

 Purpose: Returns the character at the specified index.


 Usage:
 String str = "Hello";
 char c = [Link](1); // Returns 'e'
3. substring(int beginIndex)

 Purpose: Returns a new string that is a substring from the given beginIndex
to the end of the string.
 Usage:
 String str = "Hello, World!";
 String sub = [Link](7); // Returns "World!"
4. substring(int beginIndex, int endIndex)

 Purpose: Returns a new string that is a substring from beginIndex to


endIndex - 1.
 Usage:
 String str = "Hello, World!";
 String sub = [Link](0, 5); // Returns "Hello"
5. toLowerCase()

 Purpose: Converts the entire string to lowercase.


 Usage:
 String str = "Hello World!";
 String lower = [Link](); // Returns "hello world!"
6. toUpperCase()

 Purpose: Converts the entire string to uppercase.


 Usage:
 String str = "Hello World!";
 String upper = [Link](); // Returns "HELLO WORLD!"
7. trim()

 Purpose: Removes leading and trailing whitespace from the string.


 Usage:
 String str = " Hello World! ";
 String trimmed = [Link](); // Returns "Hello World!"
8. replace(char oldChar, char newChar)

 Purpose: Replaces all occurrences of a character in the string with another


character.
 Usage:
 String str = "Hello World!";
 String replaced = [Link]('o', '0'); // Returns "Hell0 W0rld!"
9. replaceAll(String regex, String replacement)

 Purpose: Replaces all substrings matching the regex with the replacement
string.
 Usage:
 String str = "Hello 123 World 456";
 String replaced = [Link]("\\d", "#"); // Returns "Hello ### World
###"
10. split(String regex)

 Purpose: Splits the string into an array of substrings based on a delimiter


(regex).
 Usage:
 String str = "apple,banana,orange";
 String[] fruits = [Link](","); // Returns ["apple", "banana", "orange"]
11. contains(CharSequence sequence)

 Purpose: Checks if the string contains a particular sequence of characters.


 Usage:
 String str = "Hello, World!";
 boolean contains = [Link]("World"); // Returns true
121. endsWith(String suffix)

 Purpose: Checks if the string ends with the specified suffix.


 Usage:
 String str = "Hello World!";
 boolean endsWith = [Link]("World!"); // Returns true
14. indexOf(String str)

 Purpose: Returns the index of the first occurrence of the specified


substring.
 Usage:
 String str = "Hello, World!";
 int index = [Link]("World"); // Returns 7
15. lastIndexOf(String str)

 Purpose: Returns the index of the last occurrence of the specified


substring.
 Usage:
 String str = "Hello, World! World!";
 int lastIndex = [Link]("World"); // Returns 14
16. equals(Object obj)

 Purpose: Compares the string to another string for equality (case-


sensitive).
 Usage:
 String str1 = "Hello";
 String str2 = "Hello";
 boolean isEqual = [Link](str2); // Returns true
17. equalsIgnoreCase(String anotherString)

 Purpose: Compares two strings for equality, ignoring case differences.


 Usage:
 String str1 = "Hello";
 String str2 = "hello";
 boolean isEqual = [Link](str2); // Returns true
20. compareTo(String anotherString)

 Purpose: Compares two strings lexicographically.


 Usage:
 String str1 = "apple";
 String str2 = "banana";
 int comparison = [Link](str2); // Returns a negative number
because "apple" < "banana"

Creating Classes in Java


A class is a blueprint or template for creating objects. It defines the properties
(data/variables) and behaviors (methods/functions) that an object can have.

In Java, everything revolves around classes and objects, making it a purely


object-oriented programming language. Syntax of a Class

class ClassName {
// Fields (Variables)
dataTypevariableName;

// Methods (Functions)
returnTypemethodName(parameters) {
// code
}
}

Example: Creating a Simple Class


// Define a class class
Student { // Fields
(properties) String
name;
int age;

// Method (behavior)
void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}}

Declaring Objects in Java


An object is a real-world entity that has:

• State (attributes/fields/variables)
• Behavior (methods/functions)

In Java, an object is an instance of a class.

Syntax to Declare and Create an Object

ClassNameobjectName = new ClassName();

• ClassName → Name of the class (like a data type).


• objectName → The name you choose for the object (like a variable).
• new → Keyword that allocates memory.
• ClassName() → Calls the constructor of the class.

Example: Declaring and Using an Object

class Car
{ String
color; void
start() {
[Link]("Car is starting...");
}
}

public class Main {


public static void main(String[] args) {
// Object declaration and creation
Car myCar = new Car();

// Accessing fields
[Link] = "Red";

// Calling method
[Link]();

[Link]("Car color: " + [Link]);


}
}

Output:
Car is starting...
Car color: Red

Methods in Java
A methodin Java is a block of code that performs a specific task. It
helps in reusing code, improves readability, and promotes modular
programming. Syntax of a Method

returnTypemethodName(parameterList) {
// method body (statements)
}

• returnType – The type of value the method returns (e.g., int, void, String)
• methodName – The name of the method (e.g., addNumbers)
• parameterList – List of input values (optional)

Types of Methods

1. Predefined Methods – Already defined in Java (e.g.,


[Link]())
2. User-defined Methods – Defined by the programmer Example of a

Method (No Return Type, No Parameters)

void greet() {
[Link]("Hello! Welcome to Java.");
}

To call the method:

greet(); // inside same class or through object


Example with Parameters

void greetUser(String name) {


[Link]("Hello, " + name + "!");
}

Call:

greetUser("Alice");

Example with Return Type

int add(int a, int b)


{ return a + b;
}

Call:

int sum = add(5, 10);


[Link]("Sum is: " + sum);
Parameter Passing in Java
When we call a method in Java, we often need to send input values to it. These
input values are known as parameters or arguments, and the process is called
parameter passing.

Types of Parameters in Java

1. Formal Parameters – Defined in the method declaration


2. Actual Parameters – Values passed to the method during a method call

Example

// Formal parameters: a and b


int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


// Actual parameters: 5 and 10 int
result = add(5, 10);
[Link](result); // Output: 15
}

Parameter Passing Mechanism in Java

Java supports only Pass-by-Value, even for objects.

1. Pass-by-Value (for primitives)

• A copy of the variableis passed to the method.


• The original variable is not affected by changes in the method.

void modify(int x) {
x = x + 10;
}
public static void main(String[] args) {
int num = 20; modify(num);
[Link](num); // Output: 20 (not changed)
}

2. Pass-by-Value (for objects)

• A copy of the object reference is passed.


• The method can modify the object’s contents, but not the original
reference.

class Box
{ int value;
}

void change(Box b) {
[Link] = 50; // changing object data
}

public static void main(String[] args) {


Box myBox = new Box();
[Link] = 10;

change(myBox);
[Link]([Link]); // Output: 50
}

Static Fields and Methods

In Java, the keyword static is used for members (variables or methods) that
belong to the class itself rather than instances (objects) of the class.

• Static Field (Variable): Shared by all objects of the class.


• Static Method: Can be called without creating an object.
1. Static Fields (Variables)

• Declared using the static keyword.


• Only one copy exists for the entire class.
• Can be accessed using class name or object name, but class name is
preferred.

Syntax:

class MyClass {
static int count = 0; // static field
}

Example:

class Student {
static String college = "ABC College"; // shared by all objects
String name;

Student(String n) {
name = n;
}

void display() {
[Link](name + " studies at " + college);
}
}

public class Main { public static void


main(String[] args) { Student s1 =
new Student("Ravi");
Student s2 = new Student("Meena");

[Link]();
[Link]();
}}
Output:

Ravi studies at ABC College


Meena studies at ABC College

2. Static Methods

• Declared using the static keyword.


• Can be called without creating an object.
• Cannot access non-static variables or methods directly. Often used
for utility or helper methods.

Syntax:

class MyClass {
static void showMessage() {
[Link]("Hello from a static method!");
}
}

Calling a Static Method:

public class Main {


public static void main(String[] args) {
[Link](); // Called using class name
}
}

Constructors in Java

A constructor is a special method used to initialize objects in Java. It


is automatically called when an object is created.

Features of a Constructor

• Constructor name must be same as the class name.


• It has no return type, not even void.
• It is called automatically when an object is created using new.

Types of Constructors

Type Description
No arguments, provided by compiler if not defined
Default Constructor manually
Parameterized Takes parameters to initialize object with custom
Constructor values
Copy Constructor (Not built-in like C++, but can be manually created)

1. Default Constructor

class Student {
Student() {
[Link]("Default constructor called");
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student(); // Constructor automatically called
}}

Output:

Default constructor called 2.


Parameterized Constructor
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a)
{ name = n; age = a;
}

void display() {
[Link](name + " is " + age + " years old.");
}
}

public class Main { public static void


main(String[] args) { Student s1 = new
Student("Aman", 20); [Link]();
}}

Output:

Aman is 20 years old.

this Keyword in Java

What is this Keyword?

In Java, this is a reference variable that refers to the current object of the class.
It is used inside an instance method or constructor to refer to the calling object.

Uses of this Keyword

Use Case Purpose


1. To refer current class instance To resolve naming conflict between local and
variables instance variables
2. To invoke current class Call a method from another method of the same
methods class
3. To invoke current class
Using this() to call one constructor from another
constructor
4. To pass current object as Useful in method calls and constructors
argument
5. To return current class instance
Used in method chaining
1. Referring Instance Variables

When local variable and instance variable have the same name, use this to refer
to instance variable.

class Student
{ String name;

Student(String name) {
[Link] = name; // '[Link]' refers to instance variable
}

void show() {
[Link]("Name: " + name);
}
}
2. Calling Another Method of the Same Class

class A
{ void m1()
{
[Link]("Method 1");
this.m2(); // calling m2() using this
}

void m2() {
[Link]("Method 2");
}
}
Method Overloading 1.

Method Overloading

Definition:
Method Overloading means having more than one method with the same name
but different parameters in the same class.

Purpose:

• To perform similar operations using different input types or numbers. 


Improves readability and code reusability.

Rules for Method Overloading:

• Must differ in number of parameters, type of parameters, or order.

Example:

class Calculator { int


add(int a, int b) {
return a + b;
}

double add(double a, double b)


{ return a + b;
}

int add(int a, int b, int c)


{ return a + b + c;
}
}

public class Main { public static void


main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](2, 3)); // 5
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link](1, 2, 3)); // 6
}}

Benefits of Overloading:

 Enhances polymorphism (compile-time).


 Makes code simpler and flexible.

Access Modifiers

Definition:
Access modifiers define the visibility of classes, methods, and variables to other
classes.

Types of Access Modifiers in Java:


Access Within Same Subclass (Different Other
Modifier Package Package) Packages
Class
private ✅ Yes ❌ No ❌ No ❌ No
default✅ Yes ✅ Yes ❌ No ❌ No
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
Access Within Same Subclass (Different Other
Modifier
Class Package Package) Packages public ✅ Yes ✅ Yes ✅ Yes ✅ Yes

1. private

• Accessible only within the class.


• Used to hide internal details (encapsulation).

private int data = 10;

2. Default (no keyword)


• Accessible within the same package only.

int data = 10; // default

3. protected

• Accessible within the same package and in subclasses outside the package.

protected int value = 5;

4. public

• Accessible from anywhere in the program.

public void show() {


[Link]("This is public");
}

Inheritance Hierarchies
Inheritance is an object-oriented programming feature that allows a class
(subclass) to acquire the properties and behaviors (methods) of another class
(superclass).

It promotes code reusability, modularity, and extensibility.

Terminology

Term Meaning
Superclass (Parent) The class whose properties are inherited
Subclass (Child) The class that inherits the superclass
Syntax of Inheritance in Java:

class Superclass {
// properties and methods
}

class Subclass extends Superclass { //


additional properties and methods
}

Example:

class Animal
{ void eat() {
[Link]("This animal eats food.");
}
}

class Dog extends Animal


{ void bark() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited method
[Link](); // Subclass method
}
}
Superclass and Subclass in Java
• A Superclass is the parent class that contains common fields and methods.
• A Subclass is the child class that inherits from the superclass using the
extends keyword.

Superclass (Base Class or Parent Class):

• A class whose features (methods and variables) are inherited by another


class.
• May or may not be instantiated directly.

class Animal
{ void eat() {
[Link]("This animal eats food.");
}}

Subclass (Derived Class or Child Class):

• A class that inherits from another class using the extends keyword.
• Can access public and protected members of the superclass. Can override
superclass methods.

class Dog extends Animal


{ void bark() {
[Link]("Dog barks.");
}
}

Example:

class Animal
{ void eat() {
[Link]("Animal is eating...");
}
}
class Dog extends Animal
{ void bark() {
[Link]("Dog is barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // inherited from Animal
[Link](); // defined in Dog
}}

Output:

Animal is eating...
Dog is barking...

Member Access Rules in Java

In Java, member access rules define how fields and methods (also called
members) of a class can be accessed from other classes, including subclasses.

These rules depend on:


• Access Modifiers (private, default, protected, public)
• Whether the subclass is in the same package or different package

Access Modifiers Recap

Modifier Same Class Same Package Subclass (Different Package) Other Classes
private ✅ Yes ❌ No ❌ No ❌ No
default✅ Yes ✅ Yes ❌ No ❌ No
protected ✅ Yes ✅ Yes ✅ Yes ❌ No
public ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Access to Superclass Members from Subclass

Access in Subclass (Same Access in Subclass (Different


Modifier
Package) Package) private ❌ No ❌ No
default✅ Yes ❌ No protected ✅ Yes ✅ Yes public ✅ Yes ✅
Yes

super Keyword in Java

What is super in Java?

In Java, the super keyword is used to refer to the immediate parent class
(superclass) of the current object.

It is commonly used in inheritance to:

1. Access parent class methods or fields that are overridden or hidden.


2. Call the constructor of the superclass.
3. Avoid name conflicts between subclass and superclass variables.

Uses of super Keyword

1. Access Superclass Method

If a subclass overrides a method of the superclass, we can use


[Link]() to call the original method.

2. Access Superclass Field

If a subclass defines a field with the same name as in the superclass, super is used
to access the superclass version.

3. Call Superclass Constructor


The super() call must be the first statement in the subclass constructor. It is used
to invoke the constructor of the superclass.

final Class and Methods in Java

The final keyword in Java is used to define entities that cannot be modified after
they are defined. This is particularly useful for classes, methods, and variables to
maintain immutability and prevent further modification.

Using final with Classes

A final class is a class that cannot be extended (subclassed). When you mark a
class as final, it ensures that no other class can inherit from it, meaning that its
behavior is fixed and cannot be changed via inheritance.

Syntax:

final class ClassName {


// class body
}

Example of Final Class:

final class Animal


{ void eat() {
[Link]("This animal eats food.");
}
}
// The following code will result in a compile-time error:
class Dog extends Animal { // ❌ Cannot inherit from final class
void bark() {
[Link]("Dog barks.");
}}

In this example:
• The Animal class is final and cannot be extended by the Dog class.
• Attempting to subclass a final class will lead to a compile-time error.

Using final with Methods

A final methodis a method that cannot be overridden by any subclass. Marking a


method as final helps ensure that the method's behavior is consistent and
unchangeable.

Syntax:

class Superclass {
final void methodName() {
// method body
}}

Example of Final Method:

class Animal
{ final void sleep()
{
[Link]("Animal sleeps.");
}
}

class Dog extends Animal {


// Attempting to override the final method `sleep()` will cause a compile-time
error.
// void sleep() { // ❌ Cannot override the final method from Animal
// [Link]("Dog sleeps.");
// } }

In this example:  The sleep() method in the Animal

class is final.

The Dog class cannot override the sleep() method, ensuring that the behavior
defined in Animal is preserved.
The Object Class and Its Methods

In Java, the Object class is the root classof all classes. Every class in Java implicitly
inherits from the Object class, meaning that it is the parent class of every Java
class.

All objects, regardless of the class type, inherit the methods from the Object class.
This makes the Object class fundamental to Java’s object-oriented nature.

Commonly Used Methods of the Object Class

The Object class provides a set of methods that every object can inherit and use.
Here are the most commonly used methods:

1. toString() Method

• The toString() method is used to return a string representation of the


object. By default, it returns a string representation consisting of the class
name and the object’s memory address. However, it can be overridden to
provide a meaningful description of the object.

Syntax:
public String toString()
2. equals() Method

• The equals() method is used to compare if two objects are equal in terms of
their state (field values). By default, equals() compares object references,
meaning it checks if both objects are pointing to the same memory address.
• This method is often overridden to check the actual contents of the
objects.

Syntax:
public booleanequals(Object obj)

3. hashCode() Method
• The hashCode() method provides a hash codefor the object. It is used in
collections like HashMap and HashSet to organize objects efficiently.
• It is often overridden along with equals() to maintain the general contract
between equals() and hashCode().

Syntax:
public int hashCode()

4. getClass() Method

• The getClass() method returns a Class object that represents the class of
the object. It is used to get the runtime class type of an object.

Syntax:
public final Class<?>getClass()

5. clone() Method

• The clone() method is used to create a duplicate or copy of an object. It is


shallow cloning by default, meaning that if the object contains references
to other objects, those references are copied, not the objects themselves.
• To use clone(), the class must implement the Cloneable interface.

Syntax:
protected Object clone() throws CloneNotSupportedException

6. finalize() Method

• The finalize() method is called by the garbage collector before an object is


destroyed. It can be overridden to perform cleanup actions such as
releasing resources.

Syntax:
protected void finalize() throws Throwable
Polymorphism: Dynamic Binding
Polymorphism is a fundamental concept in object-oriented programming (OOP).
The term polymorphism comes from the Greek words "poly" (meaning many) and
"morph" (meaning form), so it literally means "many forms."

In Java, polymorphism allows objects of different classes to be treated as objects


of a common superclass. The most common use of polymorphism is when a
method in a superclass is overridden by a subclass, and the correct method is
called dynamically at runtime.

Types of Polymorphism

Polymorphism can be broadly classified into two types:

1. Compile-time Polymorphism (Static Binding)oAchieved through method


overloading or operator overloading.
oThe method call is resolved at compile time.
2. Runtime Polymorphism (Dynamic Binding)oAchieved through method
overriding. oThe method call is resolved at runtime based on the object
type that is referenced.

Dynamic Binding (Runtime Polymorphism)


Dynamic Binding (also known as late binding) is the process of linking a method
call to the method definition at runtime, rather than at compile time.
In Java, runtime polymorphism is achieved through method overriding. It occurs
when a subclass provides its specific implementation of a method that is already
defined in its superclass.

How Does Dynamic Binding Work?

When a subclass overrides a method, and the reference variable of the superclass
is used to refer to the object of the subclass, the method in the subclass is called
at runtime.
Example:
class Animal
{ void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

public class Main { public static void


main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog(); // Dog object is referred to by Animal reference
[Link](); // Output: Animal makes sound [Link](); //
Output: Dog barks
}
}
Explanation:

• In the example, both myAnimal and myDog are references of type Animal.
• However, at runtime, Java determines that myDog refers to a Dog object, so
the sound() method of the Dog class is called.
• This is dynamic method dispatch, where the method to be invoked is
resolved at runtime.

Method Overriding in Java

Method overriding is a concept in Java where a subclass provides a specific


implementation of a method that is already defined in its superclass. This allows
the subclass to change the behavior of the method according to its specific needs
while keeping the same method signature (name, parameters, and return type).
Key Points about Method Overriding:

• The method signature in the subclass must be the same as the one in the
superclass.
• The method in the superclass must not be private, final, or static because
these methods cannot be overridden.
• The method in the subclass must have the same or wideraccess level (i.e.,
cannot be more restrictive).

Syntax for Method Overriding:

In method overriding, you do not need to use any special keyword like override
(as in other languages like C#). Instead, the method in the subclass simply has the
same signature as in the superclass.

Syntax:

class Superclass { void


methodName() {
// method body
}
}

class Subclass extends Superclass {


@Override // This annotation is optional, but it's a good practice
void methodName() { // overridden method body
}
}

The @Override annotation is not required, but it helps by ensuring that the
method is correctly overriding the superclass method. If the method in the
subclass does not match the superclass method, the compiler will show an error.

Method Overriding Example:


class Animal
{ void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

class Main { public static void


main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog(); // Upcasting: Animal reference to Dog object
[Link](); // Output: Animal makes a sound
[Link](); // Output: Dog barks
}
}

Abstract Classes and Methods

An abstract class in Java is a class that cannot be instantiated on its own and is
designed to be inherited by other classes. It serves as a blueprint for other
classes. Abstract classes may contain both abstract methods (methods without
implementation) and concrete methods (methods with implementation).
Key Points about Abstract Classes:

• Cannot be instantiated directly. You cannot create an object of an abstract


class.
• An abstract class can have both abstract methods (without body) and
concrete methods (with body).
• It can have constructors, fields, and methods like regular classes.
• A class that contains at least one abstract method must be declared as
abstract.

Syntax for Declaring an Abstract Class:

abstract class Animal {


abstract void sound(); // abstract method (no body)

void sleep() { // concrete method


[Link]("Animal is sleeping");
}}

Explanation:

• The Animal class is declared as abstract because it contains an abstract


methodsound() without a body.
• The method sleep() is a concrete method with a body that provides a
default behavior.

What is an Abstract Method?

An abstract method is a method that is declared without an implementation


(without a body) in the abstract class. The actual implementation of the abstract
method must be provided by the subclass that extends the abstract class.

Key Points about Abstract Methods:

• An abstract method only has a method signature (name, parameters,


return type).
• The abstract method must be implemented by any concrete (non-abstract)
subclass.
• Abstract methods cannot have a body, and they cannot be static or final.

Syntax for Declaring an Abstract Method:


abstract class Animal {
abstract void sound(); // abstract method without a body
}

You might also like