0% found this document useful (0 votes)
7 views

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which encapsulate data and behavior. OOP enhances code readability, maintainability, and security while introducing concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. Despite its advantages, OOP can be complex and requires skilled programmers, and it may lead to larger program sizes and slower performance compared to procedural programming.

Uploaded by

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

Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which encapsulate data and behavior. OOP enhances code readability, maintainability, and security while introducing concepts such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. Despite its advantages, OOP can be complex and requires skilled programmers, and it may lead to larger program sizes and slower performance compared to procedural programming.

Uploaded by

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

Object-oriented programming

1. What is meant by the term OOPs?


It is the programming paradigm that is defined using objects. Objects can be
considered as real-world instances of entities like class, that have some
characteristics and behaviours
Example – In a banking system, a BankAccount class encapsulates account
details and operations like deposits and withdrawals. Users interact with
accounts through public methods, while internal data remains protected..

2. What is the need for OOPs?


● OOPs help users to understand the software easily, although they don’t
know the actual implementation.
● With OOPs, the readability, understandability, and maintainability of the
code increase.
● Even very big software can be easily written and managed easily using
OOPs.
● It provides better data security by restricting data access and avoiding
unnecessary exposure.

3. What is a Class?

A class is a building block of Object Oriented Programs. It is a


user-defined data type that contains the data members and member
functions that operate on the data members. It is like a blueprint or For
Example: Consider the Class of Cars. There may be many cars with
different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage range,
etc. So here, cars are the class, and wheels, speed limits, mileage are their
properties.template of objects having common properties and methods.
4. What is an Object?

An object is an instance of a class. Data members and methods of a class


cannot be used directly. We need to create an object (or instance) of the
class to use them. In simple terms, they are the actual world entities that
have a state and behaviour.
class Student {
String name;
}

class GfG {
public static void main(String args[])
{
Student student1 = new Student();
student1.name = "Rahul";

System.out.println("student1.name: " + student1.name);


}
}

5- What is the disadvantage of OOPs?

● The programmer should be well-skilled to implement OOPs concept.


● OOPs concept of OOPs is not suitable for all kinds of problemProper
planning is required because OOPs are a little bit tricky.
● The length of the programs is much larger in comparison to the
procedural approach.
● Slower Performance: OOP often requires more memory and processing
time
6 - What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them
into a single unit such that the sensitive data is hidden from the users

Real-World Example of Encapsulation: Bank Account

Consider a bank account system. In the real world, a bank account has sensitive
information like the account balance, account number, and personal details. To
manage this information securely, banks use encapsulation.
// Java Program to demonstrate Java Encapsulation

class Person {

private String name;

private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; } }

// Driver Class

public class Main {

public static void main(String[] args){

Person person = new Person();

person.setName("John");

person.setAge(30);

System.out.println("Name: " + person.getName());

System.out.println("Age: " + person.getAge()); }

7 - What is Abstraction?

Abstraction is similar to data encapsulation and is very important in OOP. It


means showing only the necessary information and hiding the other irrelevant
information from the user. Abstraction is Achieved by interfaces and abstract
classes.

Real-World Example: Driving a Car– When you drive a car, you interact with
the vehicle through its steering wheel, accelerator, brakes, and gear shift. You
don’t need to understand the complex mechanical and electronic systems inside
the car
- Abstract Class:

An abstract class is a class that cannot be instantiated directly. It can have both
abstract methods (methods without a body) and concrete methods (methods
with a body). An abstract class is typically used to provide a common base for
subclasses.

● It is declared using the abstract keyword.


● It can contain constructors, fields, methods (both abstract and
non-abstract), and static methods.
● You must extend an abstract class in a subclass and provide
implementations for all its abstract methods.

Abstract Method:

An abstract method is a method declared without an implementation. It is used


to enforce that subclasses must provide a concrete implementation for the
method. An abstract method can only exist within an abstract class.

● It is declared using the abstract keyword.


● It does not have a body (implementation).

Example
abstract class Animal {
private String name;

public Animal(String name)


{ this.name = name; }

public abstract void makeSound();

public String getName() { return name; }


}

// Abstracted class
class Dog extends Animal {
public Dog(String name) { super(name); }

public void makeSound()


{
System.out.println(getName() + " barks"); } }
// Abstracted class
class Cat extends Animal {
public Cat(String name) { super(name); }

public void makeSound()


{
System.out.println(getName() + " meows");
}
}
public class AbstractionExample {
public static void main(String[] args)
{
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Fluffy");

myDog.makeSound();
myCat.makeSound();
} }
Output
Buddy barks
Fluffy meows

Explanation of the above Java program:


This code defines an Animal abstract class with an abstract method makeSound().
The Dog and Cat classes extend Animal and implement the makeSound() method.
The main() method creates instances of Dog and Cat and calls the makeSound()
method on them. This demonstrates the abstraction concept in Java, where we
define a template for a class (in this case Animal), but leave the implementation of
certain methods to be defined by subclasses (in this case makeSound()).

Interface-Interfaces provide a way to achieve abstraction and multiple


inheritance in Java. interfaces include both methods and variables but lack a
method body.
Example- interface Animal {
void sound();
default void eat() {
System.out.println("This animal is eating.");
} }
// Implementing the interface in a class
class Dog implements Animal {
// Providing implementation for the abstract method
public void sound() {
System.out.println("Dog barks.");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Calls the implemented method in the Dog class
myDog.eat(); // Calls the default method from the interface
}
}

Explanation:

1. The Animal interface defines one abstract method sound() and one default
method eat().
2. The Dog class implements the Animal interface and provides an
implementation for the sound() method.
3. In the main method, we create an object of Dog and call both the sound()
(implemented in Dog) and eat() (inherited from the Animal interface)
methods.

Difference between abstract class and interface-


Abstract Class Interfaces

Abstract classes support Interfaces in Java can have


abstract and Non-abstract abstract methods, default
methods. methods, and static methods.

Doesn’t support Multiple


Supports Multiple Inheritance.
Inheritance.

Abstract classes can be


The interface can be extended by
extended by Java classes and
Java interface only.
multiple interfaces

Abstract class members in Java


Interfaces are public by default.
can be private, protected, etc.

Example: Example:
public abstract class Vehicle{ public interface Animal{
public abstract void drive() void speak();
} }

8. Inheritance in Java- It is the mechanism by which one class is


allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing ones.
A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your
current class as well.

Java Inheritance Types


1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

4. Multiple Inheritance

5. Hybrid Inheritance

1. Single Inheritance- In single inheritance, a subclass is derived from


only one super class. It inherits the properties and behaviour of a
single-parent class.

Example- import java.util.*;

class One {
public void print_geek()
{ System.out.println("Geeks") ; } }

class Two extends One {


public void print_for() { System.out.println("for"); }
}
public class Main {
public static void main(String[] args) {
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks

2. Multilevel Inheritance - a derived class will be inheriting a base class,


and the derived class also acts as the base class for other classes thus
forming a chain. In Java, a class cannot directly access the grandparent’s
members.

class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}
// Child class Three inherits from class Two
class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
System.out.println("Geeks");
}
}
public class Main {
public static void main(String[] args) {
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print lastgeek();
}
}

Output
Geeks
for
Geeks

3. Hierarchical Inheritance– one class serves as a superclass (base class)


for more than one subclass. In the below image, class A serves as a base
class for the derived classes B, C, and D.

class A {
public void print_A() { System.out.println("Class A"); } }

class B extends A {
public void print_B() { System.out.println("Class B"); } }

class C extends A {
public void print_C() { System.out.println("Class C"); } }

class D extends A {
public void print_D() { System.out.println("Class D"); } }

public class Test {


public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces)

In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not
support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C
is derived from interfaces A and B.
interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Derived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

9. why java does not support multiple inheritance


Java does not support multiple inheritance through classes to avoid ambiguity
and complexity in the inheritance structure. Multiple inheritance occurs when a
class inherits from more than one class. This feature can lead to problems,
such as the "Diamond Problem.

The Diamond Problem:

Consider the following scenario in a language that supports multiple inheritance:

● Class A defines a method called display().


● Class B and Class C both inherit from Class A and may override
display().
● Class D inherits from both Class B and Class C.

Now, if Class D calls the display() method, the question arises: Should it use the
version from Class B or Class C? This creates ambiguity

If both B and C override a method from A, and D inherits from both, the compiler
can't decide which method to call.

10. What is Polymorphism in Java?


Polymorphism allows us to perform a single action in different ways.
It allows you to define one interface and have multiple implementations.
The word “poly” means many and “morphs” means forms, So it means
many forms.

Real-life Illustration of Polymorphism in Java: A person can have


different characteristics at the same time. Like a man at the same time is a
father, a husband, and an employee. So the same person possesses
different behaviours in different situations. This is called polymorphism.

Types of Java Polymorphism


● Compile-time Polymorphism - It is also known as static

polymorphism. This type of polymorphism is achieved by function

overloading and operator overloading.

Note: But Java doesn’t support the Operator Overloading.


1. Compile-time polymorphism (Method Overloading):

In method overloading, multiple methods have the same name but different
parameter lists.

Example :

class Calculator {

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

// Overloaded method to add three integers

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

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println("Sum of 2 numbers: " + calc.add(5, 10));

System.out.println("Sum of 3 numbers: " + calc.add(5, 10, 15)); }

● Runtime Polymorphism - It is also known as Dynamic Method

Dispatch. It is a process in which a function call to the overridden


method is resolved at Runtime. This type of polymorphism is achieved
by Method Overriding. Method overriding, on the other hand, occurs
when a derived class has a definition for one of the member functions
of the base class. That base function is said to be overridden.
class Parent {

void Print() { System.out.println("parent class"); } }

class subclass1 extends Parent {

void Print() { System.out.println("subclass1"); } }

class subclass2 extends Parent {

void Print() { System.out.println("subclass2");}}

class GFG {

public static void main(String[] args){

Parent a;

a = new subclass1();

a.Print();

a = new subclass2();

a.Print(); }}

Output
subclass1

subclass2

Here in this program, When an object of a child class is created, then the
method inside the child class is called. This is because The method in the
parent class is overridden by the child class. Since The method is
overridden, This method has more priority than the parent method inside
the child class. So, the body inside the child class is executed.

Virtual functions-
It allows an object of a derived class to behave as if it were an object of the
base class. The derived class can override the virtual function of the base
class to provide its own implementation. The function call is resolved at
runtime, depending on the actual type of the object.

11. Why is Java not a Pure Object Oriented Language?

A pure object-oriented language would have no concept of primitives, static

methods, or anything outside the scope of objects and classes. Since Java allows

primitives and static methods, it is not purely object-oriented but is considered

an object-oriented programming language that incorporates procedural

elements for efficiency and simplicity.

12. Access modifiers in java- access modifiers control the visibility


and accessibility of classes, methods, constructors, and variables. They
determine what other classes and objects can access a particular class
member. Java provides four main access modifiers:

● public: Accessible from anywhere.


● private: Accessible only within the same class.
● protected: Accessible within the same package and subclasses.
● Default (no modifier): Accessible only within the same package.

13 . What are Constructors in Java?

It is a special type of method that is used to initialise the object. Constructor is a


block of code similar to the method. It is called when an instance of the class is
created. At the time of calling the constructor, memory for the object is allocated.
Every time an object is created using the new() keyword, at least one constructor is
called.

Types of Constructors in Java

1. Default Constructor in Java

A constructor that has no parameters is known as the default constructor. A default


constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor.

class GFG {

GFG() { System.out.println("Default constructor"); }

public static void main(String[] args) {

GFG hello = new GFG(); }

}
Output
Default constructor

2. Parameterized Constructor in Java

A constructor having parameters is known as a parameterized constructor. If we


want to initialise fields of the class with our own values, then use a parameterized
constructor.

Example:
Java
import java.io.*;

class Geek {

String name;

int id;

Geek(String name, int id) {

this.name = name;

this.id = id; } }

class GFG {

public static void main(String[] args) {

Geek geek1 = new Geek("Avinash", 68);

System.out.println("GeekName :" + geek1.name + " and GeekId :" + geek1.id);

} }

Output
GeekName :Avinash and GeekId :68

3. Copy Constructor in Java

copy constructor is passed with another object which copies the data
available from the passed object to the newly created object.
Note: In Java,there is no such inbuilt copy constructor available like in
other programming languages such as C++, instead we can create our
own copy constructor by passing the object of the same class to the other
instance(object) of the class.

Example:
Java
// Java Program for Copy Constructor

import java.io.*;

class Geek {

String name;

int id;

Geek(String name, int id) {

this.name = name;

this.id = id; }

Geek(Geek obj2) {

this.name = obj2.name;

this.id = obj2.id; } }

class GFG {

public static void main(String[] args) {

System.out.println("First Object");

Geek geek1 = new Geek("Avinash", 68);

System.out.println("GeekName :" + geek1.name + " and GeekId :" + geek1.id);

Geek geek2 = new Geek(geek1);

System.out.println("Copy Constructor used Second Object");


System.out.println("GeekName :" + geek2.name + " and GeekId :" + geek2.id);

}}

Output
First Object

GeekName :Avinash and GeekId :68

Copy Constructor used Second Object

GeekName :Avinash and GeekId :68

14. Why are Java Strings immutable in nature?

Java Strings are immutable because once a String object is created, its value
cannot be changed. This design provides several benefits:

1. Security: Since Strings are used in sensitive operations (e.g., for storing
passwords, class names, or network connections), immutability prevents
accidental or malicious modifications.

2. Memory optimization : java uses string pooling to optimise memory by


storing identical string literals as a single reference. Since strings are
immutable, multiple references can safely share the same string without risk
of modification. If strings are mutable, changing one reference would alter all
others, causing unpredictable behaviour.

3. Thread Safety: Immutable objects can be shared across multiple threads


without synchronisation, making Strings inherently thread-safe.

Overall, immutability ensures that Java Strings are efficient, secure, and reliable.

15. StringBuilder and StringBuffer in Java

In Java, both StringBuilder and StringBuffer are used to create mutable


sequences of characters, meaning they allow you to modify the contents without
creating a new object.

1. StringBuilder
● Introduced in: Java 5.
● Thread Safety: Not thread-safe. If multiple threads access a
StringBuilder instance concurrently, and at least one thread
modifies it, you need to synchronise externally.
● Performance: Faster than StringBuffer because it does not have to
deal with thread synchronisation.
● Use Case: Use StringBuilder when you don't need synchronisation,
such as when only a single thread is modifying the content.

2. StringBuffer

● Introduced in: Java 1.0.


● Thread Safety: Thread-safe. Every method in StringBuffer is
synchronised, meaning multiple threads can use it safely, but this
comes with a performance cost.
● Performance: Slower than StringBuilder because of the overhead
of synchronisation.
● Use Case: Use StringBuffer when you need synchronisation, for
example in a multithreaded environment.

Difference

StringBuffer Class StringBuilder Class

StringBuilder was introduced in


StringBuffer is present in Java.
Java 5.

StringBuffer is synchronised. This StringBuilder is synchronised. This


means that multiple threads means that multiple threads can
cannot call the methods of call the methods of StringBuilder
StringBuffer simultaneously. simultaneously.
Due to synchronisation, Due to its asynchronous nature,
StringBuffer is called a thread safe StringBuilder is not a thread safe
class. class.

Due to synchronisation, Since there is no preliminary check


StringBuffer is a lot slower than for multiple threads, StringBuilder
StringBuilder. is a lot faster than StringBuffer.

16 . Interfaces in Java

Class Interface

In an interface, you must initialize


In class, you can instantiate
variables as they are final but you
variables and create an object.
can’t create an object.

The interface cannot contain


A class can contain concrete (with
concrete (with implementation)
implementation) methods
methods.
The access specifiers used with
In Interface only one specifier is
classes are private, protected, and
used- Public.
public.

Important Points in Java Interfaces-

● We can’t create an instance of the interface but we can make a reference


of it that refers to the Object of its implementing class.
● A class can implement more than one interface.
● An interface can extend to another interface
● A class that implements the interface must implement all the methods in
the interface.
● All the methods are public and abstract. And all the fields are public, static,
and final.
● It is used to achieve multiple inheritances.
● It is used to achieve loose coupling.
● Inside the Interface it is not possible to declare instance variables because
by default variables are public static final.
● Inside the Interface, constructors are not allowed.
● Inside the interface the main method is not allowed.
● Inside the interface, static, final, and private methods declaration are not
possible.

17. ‘this’ reference in Java– this is a reference variable that refers to the
current object on which the method or constructor is being invoked. It can
be used to access instance variables and methods of the current object.

Example - class Test {

int a, int b;
Test(int a, int b) {
this.a = a;
this.b = b;
}

void display()
{
System.out.println("a = " + a + " b = " + b); }

public static void main(String[] args)


{
Test object = new Test(10, 20);
object.display();
}
}

Advantages of using ‘this’ reference

1. It helps to distinguish between instance variables and local variables


with the same name.
2. It can be used to pass the current object as an argument to another
method.
3. It can be used to return the current object from a method.
4. It can be used to invoke a constructor from another overloaded
constructor in the same class.

Disadvantages of using ‘this’ reference

1. Overuse of this can make the code harder to read and understand.
2. Using this unnecessarily can add unnecessary overhead to the
program.
3. Using this in a static context results in a compile-time error.
4. Overall, this keyword is a useful tool for working with objects in Java,
but it should be used judiciously and only when necessary.

18 . Characteristics of Java Abstract Keyword


In Java, the abstract keyword is used to define abstract classes and methods.
Here are some of its key characteristics:
● Abstract classes cannot be instantiated:
● Abstract methods do not have a body
● Abstract classes can have both abstract and concrete methods:
● Abstract classes can have constructors:
● Abstract classes can contain instance variables:
● Abstract classes can implement interfaces:
Abstract Methods in Java
These methods have no implementation specified in the super-class. Thus,
a subclass must override them to provide a method definition. To declare
an abstract method, use the abstract keyword.
Example- abstract class A {

abstract void m1();


void m2() {
System.out.println("This is a concrete method."); } }
class B extends A {
void m1() {
System.out.println("B's implementation of m1."); }}

public class AbstractDemo {

public static void main(String args[]) {


B b = new B();
b.m1();
b.m2(); }}
Output
B's implementation of m1.
This is a concrete method.

19. Difference between Compile-time and Run-time Polymorphism


in Java

Compile Time Polymorphism Runtime Polymorphism


In Compile time Polymorphism,
In Run time Polymorphism, the call
the call is resolved by the
is not resolved by the compiler.
compiler.

It is also known as Static It is also known as Dynamic


binding, Early binding and binding, Late binding and
overloading as well. overriding as well.

It is achieved by method It is achieved by virtual functions


overloading and pointers.

It provides fast execution It provides slow execution as


because the method that needs compare to early binding because
to be executed is known early the method that needs to be
at the compile time. executed is known at the runtime.

Compile time polymorphism is Run time polymorphism is more


less flexible as all things flexible as all things execute at run
execute at compile time. time.

Inheritance is not involved. Inheritance is involved.

20. Constructor Overloading in Java


Constructor overloading in Java is a technique where a class can have multiple
constructors with different parameter lists. This allows you to create objects in
different ways depending on the provided arguments. Each constructor must
have a unique signature (i.e., the number and/or type of parameters must be
different).

21. What is a Singleton class?


As the name implies, a class is said to be singleton if it limits the number of objects
of that class to one.

We can’t have more than a single object for such classes.

Singleton classes are employed extensively in concepts like Networking and


Database Connectivity.

22. Java Static Methods

Static methods are the methods in Java that can be called without creating
an object of class. They are referenced by the class name itself or
reference to the Object of that class.

23. Difference Between Method Overloading and Method Overriding


in Java

Method Overloading Method Overriding

Method overloading is a Method overriding is a run-time


compile-time polymorphism. polymorphism.
Method overriding is used to grant
Method overloading helps to
the specific implementation of the
increase the readability of the
method which is already provided by
program.
its parent class or superclass.

It is performed in two classes with


It occurs within the class.
inheritance relationships.

Method overloading may or Method overriding always needs


may not require inheritance. inheritance.

In method overloading, In method overriding, methods must


methods must have the same have the same name and same
name and different signatures. signature.

In method overloading, the


return type can or can not be In method overriding, the return type
the same, but we just have to must be the same or co-variant.
change the parameter.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can Private and final methods can’t be
be overloaded. overridden.

The argument list should be


The argument list should be the
different while doing method
same in method overriding.
overloading.

24. Super Keyword in Java

The super keyword in Java is used to refer to the immediate parent class
(superclass) of an object. It serves several important functions in the context of
inheritance, enabling interaction with the superclass's methods, constructors,
and instance variables.

Example - class Parent {

void display() {

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

class Child extends Parent {

void display() {

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

void show() {

super.display(); }}

public class Main {

public static void main(String[] args) {

Child obj = new Child();

obj.show(); // Output: Parent class method

}}
25. final Keyword in Java

final keyword can be used in several contexts—variables, methods, and


classes—each with specific behaviour and implications.

1. final with Variables

● Meaning: A final variable is a constant, meaning once it is assigned a


value, that value cannot be changed.

Eg- final int x = 10;

2. final with Methods

● Meaning: A final method cannot be overridden by subclasses. This


ensures that the behaviour of the method remains unchanged across
inheritance.

Eg - class Parent {

public final void display() {

System.out.println("Final method"); } }

class Child extends Parent {

public void display() {

System.out.println("Child method"); }}

3. final with Classes

● Meaning: A final class cannot be subclassed, i.e., no other class can

extend it.

Example - final class FinalClass {

// Class implementation

}
class SubClass extends FinalClass { // Compilation error, cannot extend final class

// Subclass implementation

26. The static keyword in Java is mainly used for memory management.

The static keyword in Java is used to share the same variable or method of

a given class. The users can apply static keywords with variables,

methods, blocks, and nested classes. The static keyword belongs to the

class rather than an instance of the class. The static keyword is used for a

constant variable or a method that is the same for every instance of a

class.

class Test
{ static int a = 10;
static int b;
static {
System.out.println("Static block initialized.");
b = a * 4; }

public static void main(String[] args) {


System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}}
Static block initialized.
from main
Value of a : 10
Value of b : 40
27 . final, finally and finalize in Java

● Final - Refer question number 25


● finally - keyword is used in association with a try/catch block and

guarantees that a section of code will be executed, even if an

exception is thrown. The final block will be executed after the try

and catch blocks, but before control transfers back to its origin.

finally is executed even if try block has return statement.

● Finalize method - It is a method that the Garbage Collector

always calls just before the deletion/destroying of the object which

is eligible for Garbage Collection, so as to perform clean-up activity.

Clean-up activity means closing the resources associated with that

object like Database Connection, Network Connection, or we can say

resource de-allocation.

Package - in Java is a mechanism to encapsulate a group of classes,


sub packages and interfaces. Packages are used for:
● Preventing naming conflicts. For example there can be two
classes with the name Employee in two packages,
college.staff.cse.
● Used for searching/locating and making usage of classes,
interfaces, enumerations and annotations easier
● Providing controlled access: protected and default have
package level access control. A protected member is
accessible by classes in the same package and its subclasses.
A default member (without any access specifier) is accessible
by classes in the same package only.
● Packages can be considered as data encapsulation (or
data-hiding).
Built-in Packages

These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:

1. java.lang: Contains language support classes(e.g classes which

defines primitive data types, math operations). This package is


automatically imported.
2. java.io: Contains classes for supporting input / output operations.

3. java.util: Contains utility classes which implement data structures like

Linked List, Dictionary and support ; for Date / Time operations.


4. java.applet: Contains classes for creating Applets.

5. java.awt: Contain classes for implementing the components for

graphical user interfaces (like button , ;menus etc). 6)


6. java.net: Contain classes for supporting networking operations.

User-defined packages: These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of
the package). Then create the MyClass inside the directory with the first
statement being the package names.

28. enum (short for enumeration)- In Java, enum is a special data type
that represents a collection of constants. Enums are useful when you have a
fixed set of values that represent predefined options or categories, such as
days of the week, directions, or status codes.

Example - public class EnumExample {

enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY; }

public static void main(String[] args) {

Day today = Day.WEDNESDAY;


switch (today) {

case MONDAY: System.out.println("Start of the work week!");

break;

case FRIDAY: System.out.println("End of the work week!");

break;

case SUNDAY: System.out.println("It's a holiday!");

break;

Default: System.out.println("Midweek!");

Break; }}}

29. What is a Framework?

A framework is a set of classes and interfaces which provide a


ready-made architecture to implement a new feature or a class, there is no
need to define a framework itself.
Collection Framework: To represent a group of objects as a single entity
in the Java we need classes and interfaces defined by the Collection
Framework
Collection Interface - contains all the basic methods which every collection
has like adding the data into the collection, removing the data, clearing the
data, etc. All these methods are implemented in this interface because these
methods are implemented by all the classes irrespective of their style of
implementation.

List interface- It is a child interface of Collection. It is an ordered collection


of objects in which duplicate values can be stored. Since List preserves the
insertion order, it allows positional access and insertion of elements.
1. ArrayList - provides us with dynamic arrays in Java. The size of an
ArrayList is increased automatically if the collection grows or shrinks if the
objects are removed from the collection.
2. LinkedList- is an implementation of a doubly-linked list data structure.
3. Vector provides us with dynamic arrays in Java. This is a legacy class
and a thread-safe class. This is not recommended being used in a
single-threaded environment as it might cause extra overheads. However,
to overcome this in Vectors place one can readily use ArrayList.
4. Stack is a class based on the basic principle of last-in-first-out. This is a
legacy class. This inherits from a Vector class. It is also a thread-safe class.
This is not recommended being used in a single-threaded environment as
it might cause extra overheads. However, to overcome this use
ArrayDeque.
5. ArrayDeque - provides a way to apply the Deque interface. also
known as Double Ended Queue. This is a special kind of array that grows
and allows users to add or remove an element from both sides of the
queue.
The ArrayDeque class in Java is an implementation of the Deque interface
that uses a resizable array to store its elements. This class provides a more
efficient alternative to the traditional Stack class, The ArrayDeque class
provides constant-time performance for inserting and removing elements
from both ends of the queue, making it a good choice for scenarios where
you need to perform many add and remove operations.

Set Interface

It is an unordered collection of objects in which duplicate values cannot be


stored. This set interface is implemented by various classes like HashSet,
TreeSet, LinkedHashSet, etc.

1. HashSet is an inherent implementation of the hash table data


structure or Hashing. The objects that we insert into the HashSet do
not guarantee to be inserted in the same order. The objects are
inserted based on their hash code.
2. LinkedHashSet is very similar to a HashSet. The difference is that
this uses a doubly linked list to store the data and retains the
ordering of the elements.
3. . TreeSet class is an implementation of the Self-balancing binary
tree-like a red-black tree. The ordering of the elements is
maintained by a set using their natural ordering.

Map Interface

Map is a data structure that supports the key-value pair mapping for the
data. It is mainly used in item-frequency scenarios where items are stored
along with their frequencies.
1. HashTable class implements a hash table, which maps keys to
values. Any non-null object can be used as a key or as a value. To
successfully store and retrieve objects from a hash table, the objects
used as keys must implement the hashCode method and the equals
method.
2. HashMap uses a technique called Hashing. It provides the basic
implementation of the Map interface of Java. It stores the data in
(Key, Value) pairs. To access a value in a HashMap, we must know its
key.
3. LinkedHashMap is very similar to a HashSet because the primary
difference is that this uses a doubly linked list to store the data and
retains the ordering of the elements.

Queue Interface

Queue maintains the FIFO(First In First Out) order similar to a real-world


queue line. This interface is dedicated to storing all the elements where
the order of the elements matter consisting of the PriorityQueue,
LinkedList, and ArrayDeque.
PriorityQueue is based on the priority heap. It is used when the objects
are supposed to be processed based on priority. It is known that a queue
follows the First-In-First-Out algorithm, but sometimes the elements of
the queue are needed to be processed according to the priority and this
class is used in these cases.
30. What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs
during the execution of a program, i.e. at run time, that disrupts the normal
flow of the program’s instructions. Exceptions can be caught and handled
by the program. When an exception occurs within a method, it creates an
object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception
and the state of the program when the exception occurred.
Exception Handling in Java is one of the effective means to handle
runtime errors so that the regular flow of the application can be preserved.
Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Types of Exception in Java

Built-in Exceptions: Built-in exceptions are the exceptions that are


available in Java libraries. These exceptions are suitable to explain certain
error situations. Below is the list of important built-in exceptions in Java.

1. ArithmeticException: It is thrown when an exceptional condition

has occurred in an arithmetic operation.

2. ArrayIndexOutOfBoundsException: It is thrown to indicate that

an array has been accessed with an illegal index. The index is

either negative or greater than or equal to the size of the array.

3. ClassNotFoundException: This Exception is raised when we try

to access a class whose definition is not found

4. FileNotFoundException: This Exception is raised when a file is

not accessible or does not open.

5. IOException: It is thrown when an input-output operation failed

or interrupted

Example - class ArithmeticException_Demo


{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}

User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a


certain situation. In such cases, the user can also create exceptions which
are called ‘user-defined Exceptions’.

Checked Exceptions in Java


These are the exceptions that are checked at compile time. If some code
within a method throws a checked exception, then the method must either
handle the exception or it must specify the exception using the throws
keyword.
What is an Unchecked Exception in Java ?
It occurs at the time of execution and is known as a run time exception. It includes
bugs, improper usage of API, and syntax or logical error in programming.

In Java, exceptions that are under Error and , Runtime exception classes are
unchecked exceptions.

Types of Unchecked Exceptions


● ArithmeticException
● NullPointerException
● ArrayIndexOutOfBoundsException

Java Try Catch Block


1. try in Java- The try block contains a set of statements where an
exception can occur.

2. catch in Java- The catch block is used to handle the uncertain condition
of a try block. A try block is always followed by a catch block, which
handles the exception that occurs in the associated try block.

3. throw in Java- The throw keyword is used to transfer control from the
try block to the catch block.

4. throws in Java- The throws keyword is used for exception handling


without try & catch block. It specifies the exceptions that a method can
throw to the caller and does not handle itself.

5. finally in Java- It is executed after the catch block. We use it to put


some common code (to be executed irrespective of whether an exception
has occurred or not ) when there are multiple catch blocks.

public class ExceptionHandlingExample {


// This method throws an exception
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed."); }
return a / b; }
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;

try {
// Attempting to divide by zero
int result = divide(num1, num2);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling the exception
System.out.println("Caught an exception: " + e.getMessage());
} finally {
// This block will always execute
System.out.println("This is the finally block, which runs whether an exception
occurs or not.");
}

System.out.println("Program continues...");
}
}

Multithreading in Java - Multithreading is a Java feature that allows


concurrent execution of two or more parts of a program for maximum
utilisation of CPU. Each part of such a program is called a thread. So,
threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

1. Extending the Thread class


2. Implementing the Runnable Interface

Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread begins
its life inside run() method. We create an object of our new class and call
start() method to start the execution of a thread. Start() invokes the run()
method on the Thread object.
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface
and override run() method. Then we instantiate a Thread object and call
start() method on this object
Thread - is a lightweight process that allows a program to perform multiple
tasks concurrently. Threads enable parallel execution of code, making it possible
to execute different parts of a program simultaneously. This is particularly useful
in applications that require multitasking or handling of asynchronous events
Synchronization - is a technique used to control access to shared
resources by multiple threads. It helps prevent thread interference and
ensures that only one thread can execute a block of code or access a
critical section at a time. Synchronisation is essential when multiple
threads are accessing or modifying shared data, as it prevents race
conditions and ensures data consistency.

Race Condition:

● A race condition occurs when the outcome of a program depends on the


sequence or timing of the execution of threads, leading to unpredictable
results.

Critical Section:

● A critical section is a block of code that accesses shared resources (such


as variables, objects, files). To avoid interference, only one thread should
be allowed to execute the critical section at a time.

JDBC(Java Database Connectivity)


JDBC is an API(Application programming interface) used in Java
programming to interact with databases. The classes and interfaces of
JDBC allow the application to send requests made by users to the
specified database.

What is API

API stands for Application Programming Interface. It is essentially a set


of rules and protocols which transfers data between different software
applications and allows different software applications to communicate
with each other. Through an API one application can request information
or perform a function from another application without having direct
access to its underlying code or the application data. JDBC API uses JDBC
Drivers to connect with the database.

file handling in java -

In Java, file handling is done using classes from the java.io and java.nio
packages. These classes allow you to read from and write to files, handle
different file types, manage directories, and handle exceptions. Some commonly
used classes for file handling include File, FileReader, FileWriter,
BufferedReader, BufferedWriter, and Scanner.

Basic File Operations in Java:

1. Creating a File
2. Writing to a File
3. Reading from a File
4. Appending to a File
5. Deleting a File

Shallow Copy and Deep Copy in Java

Both Shallow Copy and Deep Copy are techniques used to copy an object in Java,
but they differ in how they handle references to other objects inside the copied
object.

1. Shallow Copy:

● In a shallow copy, the fields of the original object are copied as it is.
● If the original object contains references to other objects (like arrays or other
class instances), only the references are copied, not the actual objects.
● As a result, both the original and copied objects share the same referenced
objects. If you modify the referenced objects through one copy, the changes
will be reflected in the other copy.

2. Deep Copy:
When we do a copy of some entity to create two or more than two entities
such that changes in one entity are not reflected in the other entities, then we
can say we have done a deep copy. In the deep copy, a new memory
allocation happens for the other entities, and reference is not copied to the
other entities. Each entity has its own independent reference.

Differences Between Shallow Copy and Deep Copy


After learning about shallow and deep copy, let's see the differences
between shallow and deep copy.

Shallow Copy Deep Copy


It is fast as no new memory is It is slow as new memory is
allocated. allocated.

Changes in one entity is reflected Changes in one entity are not


in other entity. reflected in changes in another
identity.

The default version of the clone() In order to make the clone()


method supports shallow copy. method support the deep copy,
one has to override the clone()
method.

A shallow copy is less expensive. Deep copy is highly expensive.

Cloned object and the original Cloned object and the original
object are not disjoint. object are disjoint.

You might also like