0% found this document useful (0 votes)
31 views84 pages

Java All 36

Uploaded by

r1ujm3ik68
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
31 views84 pages

Java All 36

Uploaded by

r1ujm3ik68
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 84

1)What is Object Oriented Programming?

Explain
concepts of OOP.

Ans: Object Oriented Programming(OOP)


► Object-oriented programming (OOPs) is a
methodology that simplifies software
development and maintenance by providing some
rules.
► Basic concepts of OOPs are:
► Object
► Class
► Encapsulation
► Abstraction
► Inheritance
► Polymorphism
► Message passing
► Dynamic binding

Object:-
► Any entity that has state and behavior is known
as an object.
► Object take up space in memory and have an
associated address like a record.
► Objects are instance of a class.
Class:-
► Collection of objects is called class. It is a logical
entity.
► A class can also be defined as a blueprint from
which you can create an individual object. Class
doesn't consume any space.

Encapsulation:-
► Binding (or wrapping) code and data together
into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different
medicines.
► A java class is the example of encapsulation.
Abstraction:-
► Hiding internal details and showing
functionality is known as abstraction. For example
phone call, we don't know the internal processing.
► In Java, we use abstract class and interface to
achieve abstraction.

Inheritance:-
► When one object acquires all the properties
and behaviors of a parent object, it is known as
inheritance.
► It provides code reusability.
Polymorphism:-
► If one task is performed in different ways, it is
known as polymorphism.
► In Java, we use method overloading and
method overriding to achieve polymorphism.

2)What is an Object?
Ans : An object is an instance of a class,
representing a real-world entity or concept. It has
its own set of attributes (data) and methods
(functions) that describe and define its behavior.

Example:

Consider a car as an object.

➢Attributes:

- Color

- Model

- Year

- Speed

➢Methods:

- Start engine

- Accelerate
- Brake
- Turn

In this example, the car object has attributes like


color, model, year, and speed, and methods like
start engine, accelerate, brake, and turn, which
describe its behavior.

3)What is a Class?

Ans : A class is a blueprint or template that


defines the properties and behavior of an object.
It's a design pattern or a template that defines the
characteristics and actions of an object.

Syntax:

In most programming languages, a class is defined


using the following syntax:
class ClassName {
// Attributes (data members)
attributeName;
attributeName;

// Methods (functions) returnType


methodName(parameters) {
// Method implementation
}
}

Example:

class Car { // Attributes


String color;
String model;
int year;
int speed;

// Methods void startEngine()


{
// Implementation
}

void accelerate() { //
Implementation
}

void brake() { // Implementation


}

void turn(String direction) {


// Implementation
}
}

In this example, the Car class defines the


attributes and methods that describe the behavior
of a car object.

4)What is encapsulation ?

Ans : Encapsulation:-
►Encapsulation is a fundamental concept in
object-oriented programming (OOP) that refers to
the binding of data (variables) and methods
(functions) that operate on the data into a single
unit, or class. It restricts direct access to some of
the object's components, which is a means of
preventing accidental or unauthorized
modification of data.
► A java class is the example of encapsulation.
5) what is abstraction ?
Ans:
Abstraction:-
► Abstraction is the concept of hiding the
internal details and complexities of a system while
exposing only the essential features, allowing you
to focus on what an object does.
► In Java, we use abstract class and interface to
achieve abstraction.

6)What is java? why Java is more popular than C?


Ans : Java is a high-level, object-oriented
programming language that is designed to be
platform-independent, allowing Java code to run
on any device that has a Java Virtual Machine
(JVM) installed.
Java is more popular than C because:

1. Easy to use: Java is simpler to learn and use,


especially for beginners.
2. Works everywhere: Java code can run on any
device with a Java Virtual Machine (JVM).
3. Secure: Java has built-in security features to
protect against bugs and attacks.

4. Large community: Java has a huge community


of developers, making it easy to find help and
resources.

5. Many libraries: Java has a vast collection of


libraries and frameworks that make development
faster and easier.

6. Android apps: Java is used to develop Android


apps, which is a huge market.

7. Enterprise-friendly: Java is widely used in


largescale enterprise applications due to its
robustness and scalability.

7)What is java and explains Java magic.

Ans: Java is a high-level, object-oriented


programming language that is designed to be
platform-independent, allowing Java code to run
on any device that has a Java Virtual Machine
(JVM) installed.
 Java Magic :
•Bytecode is the intermediate representation
of a Java program, allowing a JVM to translate
a program into machine-level assembly
instructions.

• Bytecode in Java is the reason java is


platformindependent, as soon as a Java
program is compiled bytecode is generated.

• To be more precise a Java bytecode is the


machine code in the form of a .class file.

• We can run this bytecode on any other


platform as well. But the bytecode is a
nonrunnable code that requires or relies on
an interpreter (JVM).
8)Explain Features of JAVA.
Ans:
1. Simple

2. Secure

3. Portable

4. Object-oriented
5. Robust (strong memory management.
automatic garbage collection) 6.
Multithreaded(many tasks at once )
7. Architecture-neutral(no implementation
dependent features)
8. Interpreted

9. High performance(Java bytecode is "close" to


native code)

10. Distributed(access files from any machine on


the internet)

11. Dynamic(adapt to an evolving environment)

12. Platform Independent


1)Simple: Java is designed to be easy to learn and
use, with a clean syntax that avoids complex
features from other languages like C++ (e.g.,
pointers, operator overloading).
2)Secure: Java provides a secure environment for
developing and running applications, with built-in
security features like bytecode verification,
memory management, and a security manager to
control access to system resources.
3)Portable: Java programs are
platformindependent, meaning they can run on
any device with a Java Virtual Machine (JVM)
without modification, thanks to the use of
bytecode.
4)Object-oriented: Java follows the
objectoriented programming (OOP) paradigm,
which allows developers to create modular,
reusable code by organizing it into classes and
objects.
5)Interpreted: Java code is compiled into
bytecode, which is interpreted by the JVM. This
allows for platform independence and easier
debugging.
6)Platform Independent: Java achieves platform
independence by compiling code into
platformneutral bytecode, which can be executed
on any system with a JVM, making Java programs
"write once, run anywhere."
9)Explain Java Architecture with its figure. Also
explain its component.
Ans: Java architecture is designed to allow Java
programs to be platform-independent and highly
efficient. The architecture is mainly around the
concept of the Java Virtual Machine (JVM), which
compiled Java bytecode.

Componets :
1)Java Source Code (.java file):
• Written by developers in Java, these files
contain the source code.
2)Java Compiler (javac):
• Compiles .java files into platform-independent
bytecode stored in .class files.
3)Java Bytecode (.class file):
• Intermediate code that can run on any
platform with a JVM.
4)Java Virtual Machine (JVM):
• Executes Java bytecode. It loads classes,
verifies bytecode, interprets it, or compiles it
to native code using the JIT compiler.
5)Java Runtime Environment (JRE):
• Includes the JVM and core libraries required
to run Java applications.
6)Java Development Kit (JDK):
• A superset of the JRE that includes
development tools like the compiler (javac)
and debugger, used for writing and compiling
Java programs.

10)Explain structure of java program with


example.
Ans: A basic Java program consists of various
components that together form the structure of
the program.
Structure of a Java Program:

1. Import Statements (Optional):


o Used to import other Java classes or
entire packages.
o Syntax: import java.util.Scanner;

2. Class Declaration:
o Every Java program must have at least
one
class declaration.

o Syntax: class Employee { ... }


3. Main Method:
o The entry point of any Java program. The
JVM starts execution from the main
method.

Syntax: public static void main(String[]


o

args) { ... }

4. Method Declarations (Optional):


o Define the behaviors or actions that
objects of the class can perform.
o Syntax: void/int PrintID(int id) { ... }
5. Variables and Statements:
o Variables store data, and statements
represent the logic or actions in the
program.
o Syntax: int id = 1;

11)Explain JDK,JRE AND JVM in detail.


Ans:
1) Java Virtual Machine (JVM):
► It is a specification that provides a runtime
environment in which Java bytecode can be
executed.
► The JVM performs the following main tasks:

• Loads code
• Verifies code
• Executes code
• Provides runtime environment

2) Java Runtime Environment(JRE)


► The Java Runtime Environment is a set of
software tools which are used for developing Java
applications.
► It is used to provide the runtime environment.
► It is the implementation of JVM.
► It contains a set of libraries + other files that
JVM uses at runtime.
3) Java Development Kit(JDK)
► The Java Development Kit (JDK) is a software
development environment which is used to
develop Java applications and applets.
► The JDK contains a private Java Virtual Machine
(JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a
Java Application.

12) What is Constructor? When it is invoked?


Explain with its syntax.

Ans:A constructor in Java is a special method that


is used to initialize objects when they are created.
It has the same name as the class and no return
type, not even void.

Syntax: public class ClassName { //


Constructor public
ClassName(parameter-list) {
// Initialization code
}
}

Example:

public class Person {


private String name;
private int age;
//Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
When is it invoked?
A constructor is invoked when an object of the
class is created. It is called automatically when the
object is instantiated.
Example:
public class Main {
public static void main(String[] args) {
// Create an object of the Person class
Person person = new Person("John", 30);
}
}
In this example, the Person constructor is invoked
when the person object is created, and it
initializes the name and age fields with the values
"John" and 30, respectively.
Types of Constructors:
1. Default Constructor: A constructor with no
parameters.
2. Parameterized Constructor: A constructor
with parameters.
3. Copy Constructor: A constructor that creates a
copy of an existing object.

13)Explain types of constructor.

Ans: There are three types of constructors in Java:

(i)Default Constructor: A constructor with no


parameters.
Example:
class Person {

private String name;


private int age;

// Default Constructor
Person() {
this.name = "Unknown";
this.age = 0;
}
}
(ii)Parameterized Constructor: A constructor with
parameters.
Example:
class Person {
private String name;
private int age;

// Parameterized Constructor
Person(String name, int age) {
this.name = name;

this.age = age;

}
}
(iii) Copy Constructor: A constructor that creates
a copy of an object.
Example:
class Person {
private String name;
private int age;

// Copy Constructor
Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}

14) Explain how to overload constructors in class


with appropriate example.
Ans : The Constructor Overloading can be defined
as the concept of having more than one
constructor with different parameters so that
every constructor can perform a different task(or
having same name of constructor with different
parameters.)
• Example :
class Students
{
int id;
String name;
int age;
Students() //Default Constructor
{
id = 0;
name = null;
}
Students(int i,String n) //Two Parameterized Constructor
{
id=i;
name=n;
System.out.println("ID : "+id+" "+"Name : "+name);
}
//Three Parameterized Constructor
Students(int i,String n,int a)
{
id=i;
name=n;
age = a;
System.out.println("ID : "+id+" "+"Name : "+name+" "+"Age :
"+age);
}
}
class Constructor {
public static void main(String args[])
{
System.out.println("This is default constructor");
Students s = new Students();
System.out.println("ID : "+s.id+" "+"Name : "+s.name);

System.out.println("This is parameterized constructor");


Students s1 = new Students(1,"Sahil");
Students s2 = new Students(1,"Sahil",19);
}
}

15) Explain garbage collector.


Ans :
- Garbage collection is process of reclaiming
the runtime unused memory automatically. In
other words, it is a way to destroy the unused
object.
- It makes java memory efficient because
garbage collector removes the unreferenced
objects from heap memory.
- It is automatically done by the garbage
collector(a part of JVM) so we don’t need to
make extra efforts.
Example :
class MyObject{
}
class Garbage {
public static void main(String[] args) {
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
// Both objects are reachable at this point

// Nullify references
obj1 = null; // obj1 is no longer reachable
obj2 = null; // obj2 is no longerreachable

// Suggest garbage collection


System.gc();

// At this point, obj1 and obj2 are eligible for garbage


collection
}
}

16) Explain this keyword.


Ans : In Java, the this keyword is a reference
variable that refers to the current object instance
of a class. It is used to distinguish between
instance variables and parameters or local
variables with the same name.
Example :
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name; // Refers to the instance variable
this.age = age; // Refers to the instance variable
}
void display() {
System.out.println("Name: " + this.name); // Refers to the
instance variable
System.out.println("Age: " + this.age); // Refers to the
instance variable
}
}

17) Differentiate static block and initializer block.


Ans :
Static Block Initializer Block
1) Static keyword with a 1)The purpose of the
block of code that is known instance initializer block is to
as Static Block. initialize the instance data
members.
2) Syntax : 2) The instance initializer
static block looks just like the static
{ initializer block, but without
//body of static block the static keyword.
} Syntax :
{
//body of initializer block
}
3) Static block code executes 4) The instance block runs at
only once during the class the time of instance creation.
loading. The static block
always execute first before
the main() method in Java.

18) What is method overloading? Explain with


example.
Ans : If a class has multiple methods having same
name but different in parameters, it is known as
method overloading.
Two ways to overload the method :
1. By changing number of arguments.
Ex :
class Method{
void add(int a1,int
b1)

{
int c;
c = a1 + b1;
System.out.println(“Sum of a and b is : ”+c);
}
void add(int a1,int b1,int c1)
{

int d;

d = a1 + b1 + c1;
System.out.println(“Sum of a, b and c is : ”+d);
}
public static void main(String
args[]) {
Method m = new Method();
m.add(10,20);
m.add(10,20,30);
}
}

2. By changing the data type Ex:


class Method
{
int add(int a1,int
b1)
{
int c;
c = a1 + b1;
System.out.println("Sum of a and b is : "+c);
return c;
}
void add(int a1,int b1,int c1)
{
int d;
d = a1 + b1 + c1;
System.out.println("Sum of a, b and c is : "+d);
}
public static void main(String args[])
{
Method m = new Method();
m.add(10,20);
m.add(10,20,30);
}
}

19) What are the rules of method overloading?


Can you overload main method?
Ans : The key rules for method overloading:

1. Different Parameter Lists:


➢Number of Parameters: The methods must
differ in the number of parameters.
o Ex :
void print(int a) {}
void print(int a, int b) {}

➢Type of Parameters: The methods can have


parameters of different types.

Ex:
void print(int a) {}
void print(double a) {}
➢Order of Parameters: The order of parameters
can be different.

Ex:
void print(int a, double b) {}
void print(double a, int b) {}

2. Same Method Name:


• All overloaded methods must have the same
name.
3. Same or Different Return Type:
• The return type of overloaded methods can be
the same or different, but it is not a factor in
differentiating overloaded methods.
Ex :
int add(int a, int b) {
return a + b;

double add(double a, double b)


{

return a + b;

Yes, you can overload the main method in Java.


However, only the standard main method with the
signature public static void main(String args[]) is
used as the entry point for the program when it is
executed.

Ex :
class MainMethodOverload1
{
// Overloaded main() method 1
//invoked when an int value is passed
public static void main(Integer args)
{
System.out.println("Overloaded main() method invoked that
passes an integer argument");
}
// Overloaded main() method 2
//invoked when a char is passed public
static void main(char args)
{
System.out.println("Overloaded main() method invoked that
passes a char argument");
}
//Original main() method public
static void main(String args[]) {

System.out.println("Original main() method invoked");


}
}

20)What is static variable?

Ans:
Static variable: If you declare any variable as
static, it is known as a static variable.

1. The static variable can be used to


refer to the common property of all
objects (which is not unique for
each object), for example, the
company name of employees,
college name of students, etc.
2. The static variable gets memory only
once in the class area at the time of
class loading.

3. Syntax:
static String college='LJ';

Here is an example of a static variable in


Java

class Employee
{
static int numberOfEmployee = 0;
}
Employee()

numberOfEmployee++;
}

int getNumberOfEmployee()

return numberOfEmployee;
}

public static void main(String args[]) {


Employee empl = new Employee();

System.out.println(emp1.getNumberOfEmployee
());
System.out.println(emp1.getNumberOfEmployee
());

Output :
1
1

21)Differentiate static method and class method.


Ans:

➢Static Method:

- Belongs to the class, not instances.


- Can be called without creating an
object.
- Can only access static variables and
other static methods.
- Cannot access instance variables or
instance methods.
- Typically used for utility or helper
methods.

➢Class Method (Instance Method):


- Belongs to instances of the
class.
- Must be called on an object instance
- Can access both static and instance
variables and methods .
- Typically used for methods that operate
on instance data.

Here's a simple example in Java to illustrate the


difference:
class New1
{

static void staticMethod() // static method


{
System.out.println("Static method");
}

void instanceMethod() // instance method


{

System.out.println("Instance method");
}
public static void main(String
args[])
{
// Calling static method without
object
New1.staticMethod();

// Calling instance method with


object New1 obj = new New1();
obj.instanceMethod();
}
}
22)Explain local class.

Ans:

A local class in Java is a class that is defined


inside a method or a block. It is a nested class
that has access to the enclosing method's
variables and can be used to encapsulate
functionality that is only relevant within that
method.

Here are the key characteristics of local classes:

1. Defined inside a method or block.

2. Has access to the enclosing method's


variables.
3. Can only be accessed within the
enclosing method or block
4. Cannot be declared public, private,
protected, or static

5. Can extend another class or implement


interfaces.

Example:

class Outer

{
private int data =

100;

void display()

class Inner

void display1()

{
System.out.println(data);

}
}

Inner inn = new Inner();

inn.display1();

public static void main(String

args[])

Outer out = new Outer();

out.display();
}

In this example, 'Inner' is a local class defined


inside the 'display()' method of Outer.

Local classes are useful for:

- Encapsulating functionality that is


only relevant within a specific method
or block.
- Creating small, helper classes that
are not needed elsewhere in the
program.
-Improving code organization and
readability.

23)Explain bytecode in java.

Ans) Bytecode is the intermediate


representation of a Java program, allowing a
JVM to translate a program into machine level
assembly instructions.
- Bytecode in Java is the reason java
is platform-independent, as soon as a
Java program is compiled bytecode is
generated.
- To be more precise a Java bytecode
is the machine code in the form of
a (.class) file.
- We can run this bytecode on any
other platform as well. But the
bytecode is a nonrunnable code that
requires or relies on an interpreter
(JVM).

24)what is Unicode?
Ans: A unicode is a computing industry
standard designed to consistently and
uniquely encode character used in written
languages throughout the world, the unicode
standard uses hexa-decimal to express a
character
(Note:-unicode has a 16bit)
25) What is Inheritance? Explain its types.
Ans: Inheritance is one of the key features of
Object Oriented Programming.
• Inheritance provided mechanism
that allowed a class to inherit
property of another class.
• Inheritance represents the
relationship, that also known as
parent-child relationship.
• When a Class extends another
class it inherits all non-private
members including fields and
methods.
• It's having one class as a parent
class (called a super class) and
another class as a child of the
parent (the sub class). The child
class is said to be derived from the
parent class.

Types of Inheritance :
1)Single Inheritance : There is only
one Super class and only one Sub class ,
means they have one to one communication.
Super Class

Sub Class

2) Multi-level Inheritance : When a


sub class is created from another sub
class,then that inheritance is called
multi-level inheritance.
Super Class

Sub Class

Sub Class

3) Hierarchical Inheritance : A class in


which a super class has many sub
classes or when a super class is used or
inherited by many sub classes.
Super Class

Super Class Super Class Super Class

4) Hybrid Inheritance : This is a


mixture of two or more inheritance
and in this inheritance a code may
contain two or more three types of
inheritance in Single code.
Super Class

Super Class Super Class Super Class

Super Class Super Class

Super Class

5) Multiple Inheritance : Multiple


Inheritance is a feature of an
objectoriented programming where a class
can inherit properties of more than one
parent class.
Super Class1 Super Class2

Super Class

26)What is inner class?Explain types of inner


classes in java.
Ans: Java inner class or nested class is a class
that is declared inside the class or interface.
Syntax :
class Outer
{
Class Inner
{
}
}
1) Member Inner Class: This is a non-static class
that is defined within another class.
class Outer
{
private int o = 100;
class Inner
{
void getdata()
{
System.out.println(o);
}
}
void getInner()
{
Inner in = new Inner();
in.getdata();
}

public static void main(String


args[])
{
Outer out = new Outer();
out.getInner();
}
}

2) Static Nested Class: This is a static class that is


defined within another class.
class Outer
{
static String name = "Bruce";
static class Inner
{
void getdata()
{
System.out.println(name);
}
}

public static void main(String


args[])
{
Outer.Inner out = new
Outer.Inner();
out.getdata();
}
}

3) Local Inner Class: This is a class defined


within a method or a block.

class Outer
{
private int data = 100;
void display()
{
class Inner
{
void print()
{
System.out.println(data);
}
}

Inner i = new Inner();


i.print();
}

public static void main(String args[])


{
Outer out = new Outer();
out.display();
}
}

27) Explain how constructors work in


inheritance with appropriate example.
(constructor chaining)

Ans:
ln inheritance, constructors work in a specific
order, known as constructor chaining. Here's how
it works:

1. When an object of a subclass is


created, the constructor of the subclass
is called.
2. The first line of the subclass
constructor is implicitly 'super()', which
calls the constructor of the superclass.
3. If the superclass has a constructor
with parameters, the subclass
constructor must call it explicitly using
'super(parameters)'.
4. The superclass constructor initializes
its own state and then returns control
to the subclass constructor.

5. The subclass constructor can then

initialize its own state. Here's an

example:
class Animal {

Animal(String name) {

System.out.println("Animal
constructor called for: " + name);

class Dog extends Animal {


Dog(String name) {

super(name);

System.out.println("Dog constructor called


for: " + name);
}

class Main1 {

public static void main(String args[]) {

Dog d = new Dog("Buddy");

}
Output:
Animal constructor called for: Buddy

Dog constructor called for: Buddy

In this example:
- The 'Dog' class constructor calls the
‘Animal' class constructor using super(name). -
The 'Animal' class constructor initializes the
'name' field and prints a message. - The 'Dog'
class constructor initializes the ‘name’ field
and prints a message.

28)What is the use of super keyword with


example?
Ans: The super keyword in Java is used in a
subclass to refer to the superclass. It serves
several purposes:
1. Calling the Superclass Constructor:

- The super keyword is used to


explicitly invoke a constructor of the
superclass from within the
constructor of a subclass.
2. Accessing Superclass Methods:

- If a subclass overrides a method from


the superclass, the super keyword can
be used to call the overridden method
from the superclass.

3. Accessing Superclass Fields:

- The super keyword can also be used


to access fields in the superclass if
they are hidden by fields in the
subclass.

Here's an example:
class Animal {
String name;
String color = "White";
Animal(String name) {
this.name = name;
System.out.println("Animal constructor called
for: " + name);
}
void sound()
{
System.out.println("The animal makes a
sound");
}

void display()
{
System.out.println("Color in animal is :
"+color);
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // Calls the constructor of the
superclass (Animal)

System.out.println("Dog constructor called


for: " + name);

super.sound(); //Calls the method of


superclass

}
void display()
{
System.out.println("Color in dog is : "+color);
System.out.println("Color in animal is :
"+super.color); //Accessing superclass field
}
}

public class Main1 {


public static void main(String[] args) {
Dog d = new Dog("Buddy");
d.display();
}
}

29)Give a detail explanation on method overriding


with example.

Ans: If subclass has the same method as


declared in the parent class it is known as
method overridng in Java

Example: class A
{
void disp()
{
System.out.println("Hello");
}
}
class B extends A
{
void disp()
{
System.out.println("Hi");
}

public static void main(String args[])


{
B bh = new B(); bh.disp();
}
}

30) What are the rules to be followed while


overriding a method?

Ans:
 Method must be same name as in the
parent class.
 Method must have the same
parameter as in the parent class.
 There must be an IS-A relationship
(inheritance).
 Static or final methods can not be
override.

31)What is polymorphism? Explain types of


polymorphism in java.

Ans :

Polymorphism allows us to perform a single


action in different ways. The word “poly”
means many and “morphs” means forms so it
means many form.
Types of Java Polymorphism :
1) Compile time Polymorphism : Method
Overloading.
2) Runtime Polymorphism : 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.

Here are two examples of polymorphism in Java:


Method Overloading Example :

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

{
return a + b;

Method Overriding Example :


class Animal
{
void sound()
{
System.out.println("Animal makes a sound");

}
class Dog extends Animal { void
sound() {
System.out.println("Dog barks");
}
}

In the first example, the 'Calculator' class has


two 'add' methods with different parameters,
demonstrating method overloading.

In the second example, the 'Dog' class


overrides the 'sound' method of the 'Animal'
class, demonstrating method overriding.

32)What is abstract class? Explain with


example.
Ans) A class which is declared with abstract
keyword is known as an abstract class. In Java it
can have abstract and non abstract method
(Method within the body).

There are 2 ways to achieve abstraction :


(i)Abstract class (0 to 100%)

(ii)Interface (100%)

 Rules of abstract class :


• Abstract class must be declared
with an abstract keyboard.
• It can have abstract and non -
abstract method.
• It cannot be instantiated.

• It can have constructors and static


method.
• It can have final methods which
will force the subclass not to
change the body of the method.

Syntax :
abstract class A{}

Example :
abstract class A

{
abstract void display();

void print();

System.out.println("I will print my details");

class B extends A

void display()

{
System.out.println("I will print your

details");

}
}

class Main1{
public static void main(String args[])

B bh = new B();

bh.display();

bh.print();

33)What is the use of final keyword? Explain


with example.
Ans : The 'final' keyword in Java has three
uses:

1) Final Variables: A variable


declared as final, we cannot change
the value of it.

Example:
final int MAX SIZE = 10;
MAX_SIZE = 20; // Compile-time error

2) Final Methods : A method


declared as final cannot be
overridden in subclasses.

Example:

class Animal {
final void sound() {
System.out.println("Animal makes a sound”);
}
}

class Dog extends Animal {

void sound() { // Compile-time error


System.out.println("Dog barks");
}

}
3. Final Classes : A class declared as
'final' cannot be subclassed.

Example:
final class Animal {}

class Dog extends Animal { }// Compile-time error

In summary, 'final' ensures that a variable,


method, or class cannot be modified or extended,
providing a way to restrict access and ensure
immutability.

35)How multiple inheritance can be achieved


in java?
Ans : Java does not support multiple
inheritance of state (fields) in classes,
because it can lead to diamond program.
Super Class

Class A Class B

Class C

But it does support multiple inheritance of


behavior (methods) through interfaces.

1. Achieving Multiple Inheritance in Java


Through Interfaces :

interface Animal {

void eat();
}
interface Pet {

void play();

class Dog implements Animal, Pet {

public void eat() {

System.out.println("The dog is eating.");

public void play() {

System.out.println("The dog is playing.");

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
interface myDog.play(); // Inherited from
Pet interface

2. Multiple Inheritance with Default Methods

interface Animal {

default void sound() {

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

interface Pet {

default void
sound() {

System.out.pr

intln("Pet

makes a

sound");

class Dog implements Animal, Pet {

public void sound() {

Animal.super.sound(); // Calling Animal's


default method

Pet.super.sound(); // Calling Pet's default


method

System.out.println("The dog barks");

}
}

public class Main {


public static void main(String[] args) {

Dog myDog = new Dog();

myDog.sound();

36. Explain wrapper classes in java.


Ans : Wrapper classes in Java are classes that
encapsulate primitive data types, providing a
way to use them as objects. They are part of
the java.lang package and include:

1. Byte
2. Short
3. Integer
4. Long
5. Float
6. Double
7. Character
8. Boolean

These classes provide methods to:

- Convert primitive types to objects and


vice versa.

- Perform operations on the


wrapped value.

- Compare wrapped values.

 Benefits of wrapper classes:

- Enable null values for primitive


types.
- Allow primitive types to be
used as objects. - Provide
utility methods for operations
and conversions.

public class WrapperExample {


public static void main(String[] args) {

// Primitive data types

int primitiveInt = 5;

char primitiveChar = 'a';

// Converting primitives to wrapper objects (Autoboxing)


Integer wrappedInt = primitiveInt;

Character wrappedChar = primitiveChar;

// Converting wrapper objects back to primitives (Unboxing)

int unboxedInt = wrappedInt;

char unboxedChar = wrappedChar;

// Using utility methods of wrapper classes

String intAsString = wrappedInt.toString();


// "5" int parsedInt = Integer.parseInt("123"); //

123 System.out.println("Primitive int: " +

primitiveInt); System.out.println("Wrapped int: "

+ wrappedInt);

System.out.println("Unboxed int: " + unboxedInt);

System.out.println("Int as string: " + intAsString);

System.out.println("Parsed int: " + parsedInt);

}
34) What is Interface? Explain working of
interface in class with proper example.
Ans : The interface in Java is a mechanism to
achieve abstraction. There can be only
abstract methods in the Java interface, not
method body. It is used to achieve abstraction
and multiple inheritance in Java.

➢Working of Interface in a Class


1. Define the interface with the interface
keyword.
2. A class implements the interface using
the implements keyword.
3. The implementing class must provide
concrete implementations for all
abstract methods declared in the
interface.

Example :

(1) Single Inheritance :

interface First
{
void display(); //public abstract by default
}

class Second implements First


{
public void display()
{
System.out.print(“Hello”);
}
public static void main(String args[])
{
Second s = new Second();
s.display();
}
}

(2) Multiple Inheritance :

interface First
{
void display();
}
interface Second
{
void display1();
}

class Third implements First


{
public void display()
{
System.out.print(“Hello from first”);
}

public void display1()


{
System.out.print(“Hello from second”);
}
public static void main(String args[])
{
Third t = new Third();
t.display1();
}
}

You might also like