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

Java Theory

Garbage collection in Java is an automatic memory management process that identifies and deletes unused objects to free up heap memory. Java uses classes as templates to create objects, which consist of state, behavior, and identity. The document also covers various Java concepts including static and non-static methods, memory management differences between stack and heap, variable types, constructors, inheritance, and method overloading.

Uploaded by

toor78008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Theory

Garbage collection in Java is an automatic memory management process that identifies and deletes unused objects to free up heap memory. Java uses classes as templates to create objects, which consist of state, behavior, and identity. The document also covers various Java concepts including static and non-static methods, memory management differences between stack and heap, variable types, constructors, inheritance, and method overloading.

Uploaded by

toor78008
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Garbage Collection in Java

Garbage collection in Java is the process by which Java programs


perform automatic memory management.
Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short.
When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up
memory.
the programmer need not care for all those objects which are no
longer in use. Garbage collector destroys these objects. The main
objective of Garbage Collector is to free heap memory by
destroying unreachable objects.
How Does Garbage Collection in Java
works?
Java garbage collection is an automatic process. Automatic garbage
collection is the process of looking at heap memory, identifying
which objects are in use and which are not, and deleting the
unused objects. An in-use object, or a referenced object, means
that some part of your program still maintains a pointer to that
object. An unused or unreferenced object is no longer referenced
by any part of your program. So the memory used by an
unreferenced object can be reclaimed. The programmer does not
need to mark objects to be deleted explicitly. The garbage
collection implementation lives in the JVM.

Class
1. Class is a set of object which shares common characteristics/
behavior and common properties/ attributes.
2. Class is not a real world entity. It is just a template or blueprint
or prototype from which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and group of
methods.
-> A class in java can contain:
• data member
• method
• constructor
• nested class and
• interface
Object
It is a basic unit of Object-Oriented Programming and represents real life entities. A typical
Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by methods of an object. It also reflects the response of an object
with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other objects.

Static method Non-static method


It is a method that belongs to a class instead of an The default methods in java are non-static methods.
instance of the class. The static method can be Does not include the ‘static’ keyword before the
called without the object or class instance. The method’s name. Non-static methods can access any
word ‘static’ is to be mentioned before the name of static method or variable even without using the
a method. object of a class.
In this, the methods can be accessed only by static
Non-static methods can access static as well as non-
members or static methods of other classes or the
static members and static data members of other or
same class. It cannot access non-static variables or
the same class.
methods.
Non-static methods use runtime binding and hence
It uses early binding or compile-time.
can be overridden.
Less memory is used for execution in static
methods because allocation happens only once More memory is used for execution because
due to the static keyword which fixes a of allocation happens every time the method is invoked.
particular memory in the RAM.
Difference Between Stack and Heap Memory

Parameter Stack Memory Heap Space

Application It stores items that have a It stores objects and Java


very short life such Runtime Environment (JRE)
as methods, classes.
variables, and reference
variables of the objects.

Ordering It follows the LIFO order. It does not follow any order
because it is a dynamic
memory allocation and
does not have any fixed
pattern for allocation and
deallocation of memory
blocks.

Flexibility It is not flexible because It is flexible because we


we cannot alter the can alter the allocated
allocated memory. memory.

Efficiency It has faster access, It has slower access,


allocation, and deallocation. allocation, and deallocation.

Memory It is smaller in size. It is larger in size.


Size

Java We can increase the stack We can increase or


Options size by using the JVM option decrease the heap memory
Used -Xss. size by using the -Xmx and
-Xms JVM options.

Visibility or The variables are visible It is visible to all threads.


Scope only to the owner thread.

Generation When a thread is created, To create the heap space


of Space the operating system for the application, the
automatically allocates the language first calls the
stack. operating system at run
time.

Distributio Separate stack is created It is shared among all the


n for each object. threads.

Exception JVM throws JVM throws


Throws the java.lang.StackOverF the java.lang.OutOfMem
lowError if the stack size is oryError if the JVM is
greater than the limit. To unable to create a new
avoid this error, increase native method.
the stack size.

Allocation/ It is done automatically by It is done manually by


Deallocatio the compiler. the programmer.
n

Cost Its cost is less. Its cost is more in


comparison to stack.

Implement Its implementation is hard. Its implementation is easy.


ation

Order of Memory allocation Memory allocated


allocation is continuous. in random order.

Thread- It is thread-safe because It is not thread-safe, so


Safety each thread has its own properly synchronization of
stack. code is required.

1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
These variables are created when the block is entered, or the function is called
and destroyed after exiting from the block or when the call returns from the
function.
The scope of these variables exists only within the block in which the variables
are declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined
scope.

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be
used.
Initialization of an instance variable is not mandatory. Its default value is 0.
Instance variables can be accessed only by creating objects.

3. Static Variables
Static variables are also known as class variables.
These variables are declared similarly as instance variables. The difference is
that static variables are declared using the static keyword within a class outside
of any method, constructor or block.
Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of a static variable is not mandatory. Its default value is 0.
If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won’t halt the program. The
compiler will replace the object name with the class name automatically.
If we access a static variable without the class name, the compiler will
automatically append the class name.
Differences between the Instance variables and the
Static variables
Now let us discuss the differences between the Instance variables and the Static
variables:

Each object will have its own copy of an instance variable, whereas we can only have
one copy of a static variable per class, irrespective of how many objects we create.

Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of the instance variable. In the case of a static
variable, changes will be reflected in other objects as static variables are common to
all objects of a class.

We can access instance variables through object references, and static variables can
be accessed directly using the class name .

Reference Variable in Java

1. When we create an object (instance) of class then space is reserved in heap


memory. Let’s understand with the help of an example.

Demo D1 = new Demo();

Now, The space in the heap Memory is created but the question is how to access that
space?.
Then, We create a Pointing element or simply called Reference variable which simply points
out the Object(the created space in a Heap Memory).

Understanding Reference variable


 Reference variable is used to point object/values.
 Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java.
Reference variables hold the objects/values of reference types in Java.
 Reference variable can also store value. By default, if no object is passed to a reference
variable then it will store a null value.
 4. You can access object members using a reference variable using dot syntax.

Constructors in Java
 In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.

 It is a special type of method which is used to initialize the object.


 Every time an object is created using the new() keyword, at least one
constructor is called.

 It calls a default constructor if there is no constructor available in the


class. In such case, Java compiler provides a default constructor by
default.
There are two types of constructors in Java: no-arg constructor,
and parameterized constructor.

Note: It is called constructor because it constructs the values at the time


of object creation. It is not necessary to write a constructor for a class. It is
because java compiler creates a default constructor if your class doesn't
have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any
parameter.

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.
Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a
parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to


distinct objects. However, you can provide the same values also.

Constructor Overloading in Java


 In Java, a constructor is just like a method but without return type. It
can also be overloaded like Java methods.

 Constructor overloading in Java is a technique of having more than


one constructor with different parameter lists. They are arranged in a
way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list
and their types.

Difference between constructor and method in


Java
There are many differences between constructors and methods. They are
given below.
Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class The method name may or may not
name. be same as the class name.

Java static keyword

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


We can apply static keyword with variables, methods, blocks
and nested classes. The static keyword belongs to the class than an
instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.
o 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.
o The static variable gets memory only once in the class area at the time of
class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

2) Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value
of it.

o There are two main restrictions for the static


method. They are:
o The static method can not use non static data member or call non-
static method directly.
o this and super cannot be used in static context.

Q) Why is the Java main method static?


Ans) It is because the object is not required to call a static method. If it
were a non-static method, JVM creates an object first then call main()
method that will lead the problem of extra memory allocation.

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Q) Can we execute a program without main() method?


Ans) No, one of the ways was the static block, it is not possible to execute a Java
class without the main method.

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is
a reference variable that refers to the current object.
Inheritance in Java
 Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object. It is an important part
of OOPs (Object Oriented programming system).

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
In the terminology of Java, a class which is inherited is called a parent or
superclass, and the new class is called child or subclass.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java:

 single,

 multilevel and

 hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance.


Method Overloading in Java
 If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the
method only.

Q) Why Method Overloading is not possible by changing


the return type of method only?
In java, method overloading is not possible by changing the return type of
the method only because of ambiguity.

Can we overload java main() method?

 Yes, by method overloading. You can have any number of main


methods in a class by method overloading. But JVM calls main()
method which receives string array as arguments only. Let's see the
simple example:
1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with Stri
ng[]");}
3. public static void main(String args){System.out.println("main with
String");}
4. public static void main(){System.out.println("main without args");}
5. }
Output
main with String[]

Method Overriding in Java


 If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the


method that has been declared by one of its parent class, it is known as
method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to
get the rate of interest. However, the rate of interest varies according to
banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and
9% rate of interest.
1. //Java Program to demonstrate the real scenario of Java Method Ove
rriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest
());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfIntere
st());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfIntere
st());
27. }
28. }

Can we override static method?

 No, a static method cannot be overridden. It can be proved by


runtime polymorphism, so we will learn it later.

Why can we not override static method?

 It is because the static method is bound with class whereas instance


method is bound with an object. Static belongs to the class area, and
an instance belongs to the heap area.

Can we override java main method?

 No, because the main is a static method.

There are many differences between method overloading and method


overriding in java. A list of differences between method overloading and
method overriding are given below:

No Method Overloading Method Overriding


.

1) Method overloading is used to increase Method overriding is used to


the readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.

2) Method overloading is performed within Method overriding occurs in


class. two classes that have IS-A
(inheritance) relationship.
3) In case of method overloading, parameter In case of method
must be different. overriding, parameter must be
same.

4) Method overloading is the example Method overriding is the


of compile time polymorphism. example of run time
polymorphism.

5) In java, method overloading can't be Return type must be same or


performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.

Interfaces in Java

 An Interface in Java programming language is defined as an abstract


type used to specify the behaviour of a class. An interface in Java is a
blueprint of a behaviour.
 A Java interface contains static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not the
method body.
 It is used to achieve abstraction and multiple inheritance in Java . In
other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
 Like a class, an interface can have methods and variables, but the
methods declared in an interface are by default abstract

Why do we use an Interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritances in the case of
class, by using an interface it can achieve multiple inheritances.
 Any class can extend only 1 class but can any class implement
infinite number of interface.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction.
Question : So the question arises why use interfaces when we
have abstract classes?
 The reason is, abstract classes may contain non-final variables, whereas
variables in the interface are final, public and static.

Difference Between Class and Interface

In an interface, you can’t


In class, you can instantiate instantiate variables and create
1. variables and create an object. an object.

The interface cannot contain


Class can contain concrete(with concrete(with implementation)
2. implementation) methods methods

The access specifiers used with


classes are private, protected, and In Interface only one specifier is
3. public. used- Public.

 Implementation: To implement an interface we use the


keyword implements

Advantages of Interfaces in Java


1. Without bothering about the implementation part, we can achieve
the security of the implementation.
2. In Java, multiple inheritances is not allowed, however, you can use
an interface to make use of it as you can implement more than one
interface.

3. We can’t create an instance(interface can’t be instantiated) of the


interface but we can make the reference of it that refers to the Object
of its implementing class.
4. A class can implement more than one interface.
5. An interface can extend to another interface or interface (more than
one interface).
6. A class that implements the interface must implement all the methods
in the interface.
7. All the methods are public and abstract. And all the fields are public,
static, and final.
8. It is used to achieve multiple inheritances.
9. It is used to achieve loose coupling.

Marker interface in Java


It is an empty interface (no field or methods). Examples of marker interface
are

 Serializable,
 Cloneable
 and Remote interface. All these interfaces are empty interfaces

There are six ways to create an object in Java.


1. 1: Create Object in Java Using new Keyword.
2. 2: Create Object in Java Using newInstance() method.
3. 3: Create Object in Java Using newInstance() method of Constructor Class.
4. 4: Create Object in Java Using clone() Method.
5. 5: Create Object in Java Using Deserialization Method.

Platform Independent
Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.

Java code can be executed on multiple platforms, for example, Windows,


Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e.,

Write Once and Run Anywhere (WORA)

1) What is Java?
Java is the high-level, object-oriented, robust, secure programming
language, platform-independent, high performance, Multithreaded, and
portable programming language. It was developed by James Gosling in
June 1991. It can also be known as the platform as it provides its own JRE
and API.

. What are the concepts introduced in


OOPs?

Following are the concepts introduced in OOPs:

 Object - A real-world entity having a particular state and behavior. We


can define it as an instance of a class.

 Class - A logical entity that defines the blueprint from which an object
can be created or instantiated.

 Inheritance - A concept that refers to an object gaining all the


properties and behaviors of a parent object. It provides code reusability.

 Polymorphism - A concept that allows a task to be performed in


different ways. In Java, we use method overloading and method
overriding to achieve polymorphism.
 Abstraction - A concept that hides the internal details of an application
and only shows the functionality. In Java, we use abstract class and
interface to achieve abstraction.

 Encapsulation - A concept that refers to the wrapping of code and data


together into a single unit.

Difference between HashMap


and ConcurrentHashMap
HashMap is the Class which is under Traditional Collection and
ConcurrentHashMap is a Class which is under Concurrent
Collections, apart from this there are various differences between
them which are:

HashMap is non-Synchronized in nature i.e. HashMap is not Thread-


safe whereas ConcurrentHashMap is Thread-safe in nature.
HashMap performance is relatively high because it is non-
synchronized in nature and any number of threads can perform
simultaneously.
But ConcurrentHashMap performance is low sometimes because
sometimes Threads are required to wait on ConcurrentHashMap.
While one thread is Iterating the HashMap object, if other thread try
to add/modify the contents of Object then we will get Run-time
exception
saying ConcurrentModificationException.ConcurrentModificationExce
pti
Whereas In ConcurrentHashMap we wont get any exception while
performing any modification at the time of Iteration.

In HashMap, null values are allowed for key and values, whereas in
ConcurrentHashMap null value is not allowed for key and value,
otherwise we will get Run-time exception
saying NullPointerException.

HashMap is introduced in JDK 1.2 whereas ConcurrentHashMap is


introduced by SUN Microsystem in JDK 1.5
What is the abstraction?
Abstraction is a process of hiding the implementation details and showing
only functionality to the user. It displays just the essential things to the
user and hides the internal information, for example, sending SMS where
you type the text and send the message. You don't know the internal
processing about the message delivery. Abstraction enables you to focus
on what the object does instead of how it does it. Abstraction lets you
focus on what the object does instead of how it does it.

In Java, there are two ways to achieve the abstraction.

What is the abstract class?


A class that is declared as abstract is known as an abstract class. It needs
to be extended and its method implemented. It cannot be instantiated. It
can have abstract methods, non-abstract methods, constructors, and
static methods. It can also have the final methods which will force the
subclass not to change the body of the method.

Can there be an abstract method without an abstract


class?
No, if there is an abstract method in a class, that class must be abstract

Can you use abstract and final both with a method?


No, because we need to override the abstract method to provide its
implementation, whereas we can't override the final method.

Is it possible to instantiate the abstract class?


No, the abstract class can never be instantiated even if it contains a
constructor and all of its methods are implemented.

What is the interface?


The interface is a blueprint for a class that has static constants and
abstract methods. It can be used to achieve full abstraction and multiple
inheritance. It 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. In other words, you
can say that interfaces can have abstract methods and variables. Java
Interface also represents the IS-A relationship. It cannot be instantiated
just like the abstract class. However, we need to implement it to define its
methods. Since Java 8, we can have the default, static, and private
methods in an interface.

Can you declare an interface method static?


No, because methods of an interface are abstract by default, and we can
not use static and abstract together.

Can the Interface be final?


No, because an interface needs to be implemented by the other class and
if it is final, it can't be implemented by any class.

What is a marker interface?


A Marker interface can be defined as the interface which has no data
member and member functions. For example, Serializable, Cloneable are
marker interfaces.

What are the differences between abstract class and


interface?
Abstract class Interface

An abstract class can have a method The interface has only abstract methods.
body (non-abstract methods).

An abstract class can have instance An interface cannot have instance


variables. variables.

An abstract class can have the The interface cannot have the constructor.
constructor.

An abstract class can have static The interface cannot have static methods.
methods.

You can extend one abstract class. You can implement multiple interfaces.

The abstract class can provide the The Interface can't provide the
implementation of the interface. implementation of the abstract class.

The abstract keyword is used to The interface keyword is used to declare


declare an abstract class. an interface.

An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

An abstract class can be extended An interface class can be implemented


using keyword extends using keyword implements

A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}

Can we define private and protected modifiers for the


members in interfaces?
No, they are implicitly public.

How to make a read-only class in Java?


A class can be made read-only by making all of the fields private. The
read-only class will have only getter methods which return the private
property of the class to the main method. We cannot modify this property
because there is no setter method available in the class.
How to make a write-only class in Java?
A class can be made write-only by making all of the fields private. The
write-only class will have only setter methods which set the value passed
from the main method to the private fields. We cannot read the properties
of the class because there is no getter method in this class.

What are the advantages of Encapsulation in Java?


There are the following advantages of Encapsulation in Java?

o By providing only the setter or getter method, you can make the class
read-only or write-only. In other words, you can skip the getter or setter
methods.
o It provides you the control over the data. Suppose you want to set the
value of id which should be greater than 100 only, you can write the logic
inside the setter method. You can write the logic not to store the negative
numbers in the setter methods.
o It is a way to achieve data hiding in Java because other class will not be
able to access the data through the private data members.
o The encapsulate class is easy to test. So, it is better for unit testing.
o The standard IDE's are providing the facility to generate the getters and
setters. So, it is easy and fast to create an encapsulated class in Java.

Why are wrapper classes needed in Java?


Wrapper classes are fundamental in Java because they help a Java program be
completely object-oriented. The primitive data types in java are not objects, by default.
They need to be converted into objects using wrapper classes.

Question on oops concepts

1. What are the core OOPs concepts in Java?


Or, What are the basic principles of OOPs concept in Java?
Or, What is the main fundamental principles (main pillars) of the
OOPs concepts in Java?
Ans: There are four basic principles that make a language Object
Oriented. They are as follows:
Encapsulation: It is the mechanism of hiding data
implementation by restricting access to public methods.
Abstraction: It is a technique by which we can hide the data that
is not required to a user.
Inheritance: It is a process by which a child class acquires all the
properties and behaviors of the parent class.
Polymorphism: Polymorphism means many forms. It is the
technique by which we can perform a single task in different
ways. It is further divided into two types – static and dynamic.
Static polymorphism is achieved using method overloading and
dynamic polymorphism using method overriding.
2. What Is Object-Oriented Programming in Java?
Ans: Object-oriented programming (OOP) in Java is a
programming methodology to design a computer program using
classes and objects.
It is the most popular programming methodology and widely used
in the software industry today. It is an extension of procedural
programming.
3. What is the difference between procedural
programming and object-oriented programming?
Ans: Procedural programming means writing code without
objects.
Object-oriented programming means writing code with objects
which contain data in the form of fields (often known as
properties in java) and functionality code in the form of methods
(often known as behaviour in java).
4. What is Object-Oriented Programming System (OOPs) in
Java?
Ans: Writing a program using features like encapsulation,
abstraction, inheritance, and polymorphism is called object-
oriented programming system.

What is the basic difference between Object Oriented


Programming language and Object Based Programming
language?
Ans: Object Oriented Programming languages like Java, Python,
C++ follow concepts of OOPS like Encapsulation, Abstraction,
Polymorphism, and Inheritance, etc.
Object-Based Programming languages like JavaScript, VBScript,
etc follow some features of OOPS but they do not support
Polymorphism and Inheritance.
7. What are some important features of OOPs concept in
Java?
Ans: Some of the important striking features of OOPs concept are
as follows:
 Higher priority is focused on data rather than functions.
 Programs are divided into the number of entities known
as objects.
 Objects communicate with each other through
functions (methods).
 Methods that operate on data of an object are closely
bound together in the data structure.
 Data is hidden in the OOP and cannot be accessed by
external methods. Hence, it is safe from accidental
modification.
 Data cannot move freely out of the object.
 New data and methods can be easily added whenever
needs.
8. What are the advantages/benefits of OOPs in Java?
Ans: OOPs concept in Java offers several advantages that are not
available in procedural programming like C, Pascal, etc. Some of
the major and important benefits of object-oriented programming
are as follows:
 Security
 Reusability
 Effective communication
 Developing complex software
 Easily upgraded
 Easy partition of work
 Maintenance
 Efficiency
9. What are applications of OOPs concepts in Java?
Ans: Due to its reusability feature, it is widely used in many areas.
Some of the important application areas of OOPs are as follows:
 Real-time systems
 Object-oriented database
 Graphical in the Windows operating system.
 Artificial intelligence and expert systems
 Parallel programming
 CAD/CAM software and in many areas.
. What is Encapsulation in Java?
Ans: Encapsulation is the programming technique of making fields
in a class private and providing access to those fields via public
methods.
In other words, encapsulation is the technique of hiding
implementation details and providing methods for data access.
12. What is Data hiding?
Ans: Data hiding is the process in which the field is declared
private within the class to hide so that no one can access it from
outside the class.
13. How to implement Encapsulation in Java?
Ans: There are two key points thereby we can achieve or
implement encapsulation in Java program.
 Declaring the instance variable of the class as private
so that it cannot be accessed directly by anyone from
outside the class.
 Provide the public setter and getter methods in the
class to set/modify the value of the variable.
14. How to achieve data hiding programmatically?
Ans: By declaring data members (variables) as private, we can
achieve data hiding. If variables are declared as private in the
class, nobody can access them from outside the class.
The biggest advantage of data hiding in java is we can achieve
security in the application.

What is meant by tightly encapsulated class in Java?


Ans: If each variable is declared as private within the class, it is
called tightly encapsulated class in Java.

What are the accessor method and mutator method?


Ans: A method that is used to retrieve the value of a variable is
called getter or accessor method.
A method that is used for updating or setting the value of a
variable is called setter method or mutator method.
What would happen if we do not use encapsulation in java
program?
Ans: If we don’t use encapsulation in a program, fields will not be
private and could be accessed by anyone from outside the class.
Why do we need to use inheritance?
Ans: Inheritance is one of main pillars of OOPs concept. Some
objects share certain properties and behaviors. By using
inheritance, a child class acquires all properties and behaviors of
parent class.
There are the following reasons to use inheritance in java.
We can reuse the code from the base class.
 Using inheritance, we can increase features of class or
method by overriding.
 Inheritance is used to use the existing features of class.
 It is used to achieve runtime polymorphism i.e method
overriding.
What are super class and sub class?
 Ans: A class from where a subclass inherits features is called
superclass. It is also called base class or parent class.
 A class that inherits all the members (fields, method, and
nested classes) from another class is called subclass. It is
also called a derived class, child class, or extended class.
How is Inheritance implemented/achieved in Java?
Ans: Inheritance can be implemented or achieved by using two
keywords:
1. extends: extends is a keyword that is used for
developing the inheritance between two classes and
two interfaces.
2. implements: implements keyword is used for
developing the inheritance between a class and
interface.

What is the use of super keyword in Java?


Ans: super keyword is a reference variable that refers to an
immediate superclass object. It is used for the following purposes:
 To refer immediate parent class instance variable.
 To call immediate parent class constructor.
 To invoke immediate superclass method.

Why do we use this keyword in Java?


Ans: this keyword is a reference variable that refers to the current
class object. It holds the reference to current class object or same
class object.
There are six usages of Java this keyword. They are as follows:
1. this reference can be used to refer to the current class instance
variable.
2. this keyword is used to call the non-static method of the
current class.
3. this() can be used to invoke the current class constructor.
4. this keyword can be used as a parameter in the method call.
5. The keyword “this” can be used as a parameter in the
constructor call.
6. It can also be used to return the object of the current class
from the method.
Is it possible to use this() and super() both in the same
constructor?
Ans: No, Java does not allow using both super() and this()
together in same constructor. As per Java specification, super() or
this() must be the first statement in a constructor.

Difference between super and this


keyword in Java

Functional Interface
A functional interface is an interface with only one abstract method. This
means that the interface implementation will only represent one
behavior. Examples of a functional interface in Java are:
 java.lang.Runnable
 java.util.Comparator
 java.util.concurrent.Callable
 java.io.FileFilter
An important point to remember is that the functional interface can have
a number of default methods but only one abstract method.
An interface with exactly one abstract method is called Functional
Interface. @FunctionalInterface annotation is added so that we can mark an interface as
functional interface. It is not mandatory to use it, but it’s best practice to use it with functional
interfaces to avoid addition of extra methods accidentally. If the interface is annotated
with @FunctionalInterface annotation and we try to have more than one abstract
method, it throws compiler error. The major benefit of java 8 functional interfaces is that we
can use lambda expressions to instantiate them and avoid using bulky anonymous class
implementation. Java 8 Collections API has been rewritten and new Stream API is
introduced that uses a lot of functional interfaces. Java 8 has defined a lot of functional
interfaces in java.util.function package. Some of the useful java 8 functional
interfaces are Consumer, Supplier, Function and Predicate. You can find more detail
about them in Java 8 Stream Example. java.lang.Runnable is a great example of
functional interface with single abstract method run(). Below code snippet provides some
guidance for functional interfaces:

Predicate in Java 8 is defined in the java. util. function package; it


is an interface that contains only one abstract method. It will be
easy to guess what that method would do and return. Since we are
talking about predicates, this method would test a value or an object
with a condition and returns a boolean value.

HTTPS
HTTPS is an abbreviation of Hypertext Transfer Protocol Secure. It is a secure extension
or version of HTTP. This protocol is mainly used for providing security to the data sent
between a website and the web browser. It is widely used on the internet and used for secure
communications. This protocol uses the 443 port number for communicating the data.

This protocol is also called HTTP over SSL because the HTTPS communication protocols
are encrypted using the SSL (Secure Socket Layer).

By default, it is supported by various web browsers.

Those websites which need login credentials should use the HTTPS protocol for sending the
data.

Difference between HTTP and HTTPS


HTTP HTTPS

1. It is an abbreviation of Hypertext Transfer 1. It is an abbreviation of Hypertext Transfer


Protocol Protocol Secure.

2. This protocol operates at the application


2. This protocol operates at the transport layer.
layer.

3. The data which is transferred in HTTP is plain 3. The data which is transferred in HTTPS is
text. encrypted, i.e., ciphertext.

4. By default, this protocol operates on port 4. By default, this protocol operates on port
number 80. number 443.
5. The URL (Uniform Resource Locator) of HTTP 5. The URL (Uniform Resource Locator) of HTTPS
start with http:// start with https://

6. But, this protocol requires an SSL (Secure Socket


6. This protocol does not need any certificate.
Layer) certificate.

7. Encryption technique is available or present in


7. Encryption technique is absent in HTTP.
HTTPS.

8. The speed of HTTP is fast as compared to 8. The speed of HTTPS is slow as compared to
HTTPS. HTTP.

9. It is un-secure. 9. It is highly secure.

10. Examples of HTTP websites are Educational 10. Examples of HTTPS websites are shopping
Sites, Internet Forums, etc. websites, banking websites, etc.

Advantages of HTTPS

Following are the advantages or benefits of a Hypertext Transfer Protocol Secure (HTTPS):

 The main advantage of HTTPS is that it provides high security to users.


 Data and information are protected. So, it ensures data protection.
 SSL technology in HTTPS protects the data from third-party or hackers. And this technology
builds trust for the users who are using it.
 It helps users by performing banking transactions.

Disadvantages of HTTPS

Following are the disadvantages or limitations of a Hypertext Transfer Protocol Secure


(HTTPS):

 The big disadvantage of HTTPS is that users need to purchase the SSL certificate.
 The speed of accessing the website is slow because there are various complexities in
communication.
 Users need to update all their internal links.

Java Interview Questions for 2 to 3


Years Experience
Q1 List down methods present in the Object class?

Below are the important methods present in the Object class:

a. clone(): this method is used to create a clone of the object


b. equals(): this method is used to check whether objects are equal.
c. hashCode(): this method returns the hash value of the object.
d. toString(): this method returns the String representation of the given
object.
e. wait(): causes the current method to wait until another thread calls
notify() or notifyAll() method.
f. notify(): wakes up the single thread waiting for this object's monitor.
g. notifyAll(): wakes up all the threads, waiting for this object's monitor.
h. finalize(): this method is invoked by garbage collector just before the
object is garbage collected.

OOPS Concept
Q2 What is an interface?

In simple words, Interface is a blueprint of the class. It contains static


constants and abstract methods.

Q3 What is the difference between Method Overriding and Method


Overloading in Java?

Method Overloading is used to increase the readability of the program.


Method Overriding is used to provide the specific implementation of the
method. You can find a detailed explanation here.

Q4 Is it possible to override the static method in Java?

No, it is not possible to override the static method in Java. The reason is

a. The static method belongs to the class level, not the object level. In
method overriding, it is the object that decides which method is to be
called.

b. Also, for class-level methods i.e static methods, the type reference
decides which method is called not the object being referred. It concludes
the method called is determined at compile time.

If a child class defines a static method with the same signature as a static
method in the parent class, then the method in the child class hides the
method in the parent class.
Q5 What is the Dynamic method dispatch in Java?

Dynamic method dispatch is also known as Run time polymorphism. It is a


mechanism by which a call to an overridden method is resolved at run
time. At runtime, it is the type of object being referred to not the type
reference of the variable that decides which version of an overridden
method needs to be executed.

Exception Handling
Q6 What is the difference between Checked and Unchecked
Exception in Java?

You can find a detailed explanation here.

Q7 What is the difference between throw and throws in Java?

Find the answer in detail here.

Q8 What is the try with resources statement in Java?

According to Oracle docs, try-with-resources is a try statement that


declares one or more resources. A resource is an object that must be
closed after the program is finished with it. It ensures that each resource is
closed at the end of the statement.

Q9 Does finally block always execute in Java?

No, there is one scenario where the finally block does not execute. When
you run System.exit(0) in the try or catch block, then finally block does not
execute.

Collection
Q10 What is the difference between Array and ArrayList? Which is
better?
The detailed answer to the difference between Array and ArrayList can be
found here.

Q11 What is the difference between LinkedList and ArrayList in Java?

The detailed answer to the difference between LinkedList and ArrayList can
be found here.

Q12 How HashMap works internally in Java?

This is one of the most important questions that every java developer must
know. Find the detailed answer to How HashMap works internally in
Java here.

Q13 What is the difference between fail-safe iterators and fail-fast


iterators?

The detailed answer to the difference between fail-fast and fail-safe can be
found here.

Q14 What is the difference between HashMap and


ConcurrentHashMap?

A detailed explanation of the difference between HashMap and


ConcurrentHashMap can be found here.

Q15 What is the difference between HashMap and Hashtable?

The detailed answer to the difference between HashMap and Hashtable


can be found here.

Q16 How ConcurrentHashMap works internally in Java?

A detailed explanation of ConcurrentHashMap internal working can be


found here.
Multithreading
Q17 What is the difference between wait and sleep methods in Java?

You can find all the differences between the wait and sleep method here.

Q18 Explain the lifecycle of a Thread in java?

The lifecycle of a thread in java is explained in detail here.

Q19 What is the difference between Runnable and Thread in Java?

Differences between Runnable and Thread are explained here.

Q20 Which one is better to implement Runnable or to extends


Thread?

implements Runnable is better than extends Thread. Using extends Thread


we can not inherit any other class since Java does not allow multiple
inheritance of classes.

String
Q21 What is the difference between String, StringBuilder, and
StringBuffer in Java?

You can find the difference between String, StringBuilder, and


StringBuffer here.

Q22 Why String is immutable in Java?

This is one of the important questions. You can find a detailed


explanation here.

Q23 How many objects will be created in the below statement?

String strObj1 = "JavaHungry";


String strObj2 = "JavaHungry";
The answer is only 1 object is created. String strObj1 will create a new
object in String constant pool whereas strObj2 will create the reference to
the String strObj1.

Serialization
Q24 What is the marker interface? Name some marker interfaces in
Java?

An empty interface i.e interface without methods and fields is called a


marker interface in java. java.io.Serializable and java.lang.Cloneable are
some of the examples of marker interface.

Q25 What is autoboxing and unboxing in Java?

Autoboxing can be defined as converting primitive data type (int, float,


double, etc.) into their corresponding object wrapper classes.
for example: int to Integer, float to Float

Unboxing is the reverse of autoboxing. It converts Object wrapper classes


into a primitive data types.

Q26 What is a transient keyword in Java?

transient keyword in Java is used to avoid Serialization. If the variable is


marked as transient then it will not be serialized.

types of memory in java


In Java, there are several types of memory used during the execution of a program. Here are
some of the most common types of memory used in Java:
Heap Memory: Heap memory is used for the storage of objects in Java. Whenever an object
is created, it is stored in the heap memory, which is a shared memory area that is accessible
to all threads in a Java program. Objects are created using the new keyword, and they are
automatically garbage-collected when they are no longer in use.
Stack Memory: Stack memory is used for the execution of methods in Java. Each thread in a
Java program has its own stack, which is used to store local variables, method parameters,
and the return address of method calls. When a method is called, a new frame is pushed
onto the stack to store its local variables and parameters, and the frame is popped off the
stack when the method returns.
Method Area: The method area is used to store the bytecode of loaded classes, as well as
other static data such as class variables, method code, and constant pool. It is a shared
memory area that is accessible to all threads in a Java program.
Native Memory: Native memory is used to store data that is outside the control of the Java
Virtual Machine (JVM), such as data in native libraries or data structures that are allocated
by the operating system.
Permanent Generation: The Permanent Generation (PermGen) is a part of the method area
that is used to store metadata about classes and methods, such as the bytecode of loaded
classes, the names of classes and methods, and other class-related data. In Java 8 and later
versions, PermGen has been replaced by the Metaspace, which is a part of the native
memory.

when to use string , strin buffer and string


builder
In Java, String, StringBuffer, and StringBuilder are classes used for storing and
manipulating text. Here's a brief overview of when to use each of these classes:

String: String is an immutable class, which means that once a String object is
created, its value cannot be changed. This makes String objects thread-safe and ideal for
situations where the value of the string will not change frequently. You can use String
objects for storing constant strings, such as error messages, application labels, and other
similar data.

StringBuffer: StringBuffer is a mutable class that provides methods for appending,


inserting, and deleting characters in a string. StringBuffer is thread-safe and synchronized,
which means that multiple threads can access a StringBuffer object at the same time
without any issues. You can use StringBuffer objects for building strings in a multi-
threaded environment.

StringBuilder: StringBuilder is similar to StringBuffer, but it is not thread-safe.


StringBuilder provides methods for appending, inserting, and deleting characters in a
string, and it is more efficient than StringBuffer in single-threaded environments. You can
use StringBuilder objects for building strings in a single-threaded environment.
In general, you should use String when you need an immutable string, StringBuffer when
you need a mutable string in a multi-threaded environment, and StringBuilder when you
need a mutable string in a single-threaded environment. It's worth noting that
StringBuffer and StringBuilder are both faster than String for building strings, so you
should use them when you need to build a string dynamically.

Use of marker interface


The primary use of a marker interface is to provide additional information to
the compiler or runtime environment. Some common examples of marker
interfaces include the Serializable interface, which indicates that a class can be
serialized and deserialized, and the Cloneable interface, which indicates that a
class can be cloned.
Overall, marker interfaces provide a way to add additional information to
classes and methods without adding any extra functionality. This can be
useful for a variety of purposes, including serialization, cloning, and
defining custom annotations.

Why do we use constructors when we have methods?


ChatGPT
Constructors and methods serve different purposes in object-oriented programming.
A constructor is a special method that is called when an object of a class is created.
Its main purpose is to initialize the object's state, such as setting its initial values or
allocating resources it needs.

Methods, on the other hand, are used to perform specific actions or operations on an
object. They may or may not change the object's state.

So while constructors are used to set up an object's initial state, methods are used to
interact with that state, modify it, or retrieve information about it.

In short, constructors are used to initialize the object's state, while methods are used
to perform actions on that state. Both constructors and methods have important
roles to play in object-oriented programming.

the equals() method and hashCode() method

In Java, the equals() method and hashCode() method are two important methods that are
used to implement object equality and are related to each other.

The equals() method is used to determine whether two objects are equal in value. By default, the
equals() method compares the memory addresses of the two objects to determine equality,
which means that two objects that have the same values but are in different memory locations will
not be considered equal. However, developers can override the equals() method in their classes
to compare the values of the objects instead of the memory addresses.
The hashCode() method is used to generate a hash code value for an object. A hash code is a
numeric value that represents the contents of an object. It is used by data structures such as Hash
Sets and Hash Maps to quickly identify if an object is already present in the collection or not. The
hashCode() method returns an integer value that is used as the hash code for the object.

The equals() and hashCode() methods are related to each other because if two objects are
equal according to the equals() method, their hash codes must be equal too. This is because if
two objects have the same values, they should produce the same hash code. Therefore, if the
equals() method is overridden, the hashCode() method should also be overridden to ensure
that equal objects produce the same hash code.

Memory Management in Java


In Java, memory management is the process of allocation and de-
allocation of objects, called Memory management. Java does memory
management automatically. Java uses an automatic memory
management system called a garbage collector. Thus, we are not
required to implement memory management logic in our application. Java
memory management divides into two major parts:

o JVM Memory Structure


o Working of the Garbage Collector

VM Memory Structure
JVM creates various run time data areas in a heap. These areas are used
during the program execution. The memory areas are destroyed when JVM
exits, whereas the data areas are destroyed when the thread exits.

Method Area
Method Area is a part of the heap memory which is shared among all the
threads. It creates when the JVM starts up. It is used to store class
structure, superclass name, interface name, and constructors. The JVM
stores the following kinds of information in the method area:

o A Fully qualified name of a type (ex: String)


o The type's modifiers
o Type's direct superclass name
o A structured list of the fully qualified names of super interfaces.

Heap Area
Heap stores the actual objects. It creates when the JVM starts up. The user can
control the heap if needed. It can be of fixed or dynamic size. When you use a
new keyword, the JVM creates an instance for the object in a heap. While the
reference of that object stores in the stack. There exists only one heap for each
running JVM process. When heap becomes full, the garbage is collected.

Stack Area
Stack Area generates when a thread creates. It can be of either fixed or
dynamic size. The stack memory is allocated per thread. It is used to store
data and partial results. It contains references to heap objects. It also
holds the value itself rather than a reference to an object from the heap.
The variables which are stored in the stack have certain visibility, called
scope.

Native Method Stack


It is also known as C stack. It is a stack for native code written in a
language other than Java. Java Native Interface (JNI) calls the native stack.
The performance of the native stack depends on the OS.

PC Registers
Each thread has a Program Counter (PC) register associated with it. PC
register stores the return address or a native pointer. It also contains the
address of the JVM instructions currently being executed.

Working of Garbage Collector


Garbage Collector Overview
When a program executes in Java, it uses memory in different ways. The
heap is a part of memory where objects live. It?s the only part of memory
that involved in the garbage collection process. It is also known as
garbage collectible heap. All the garbage collection makes sure that the
heap has as much free space as possible. The function of the garbage
collector is to find and delete the objects that cannot be reached.
Types of Garbage Collection
There are five types of garbage collection are as follows:

o Serial GC: It uses the mark and sweeps approach for young and old
generations, which is minor and major GC.
o Parallel GC: It is similar to serial GC except that, it spawns N (the number
of CPU cores in the system) threads for young generation garbage
collection.
o Parallel Old GC: It is similar to parallel GC, except that it uses multiple
threads for both generations.
o Concurrent Mark Sweep (CMS) Collector: It does the garbage
collection for the old generation. You can limit the number of threads in
CMS collector using XX:ParalleCMSThreads=JVM option. It is also
known as Concurrent Low Pause Collector.
o G1 Garbage Collector: It introduced in Java 7. Its objective is to replace
the CMS collector. It is a parallel, concurrent, and CMS collector. There is
no young and old generation space. It divides the heap into several equal
sized heaps. It first collects the regions with lesser live data.

Miscellaneous
Q27 What is the difference between final, finally, and finalize in Java?

The difference between final, finally and finalize is answered in detail here.

Q28 What are the different ways to call the garbage collector in Java?

There are two ways to call the garbage collector in Java.


a. System.gc()
b. Runtime.getRuntime().gc()

Q29 What is volatile keyword in Java?

If a variable is marked as volatile then this variable is read from the main
memory instead of cache memory.

Q30 What are the features of Java 8?


This question is very important. You can find the features of Java 8 here.

Coding

Q31 How to reverse a string without using reverse() built-in method in


Java? (Solution)

Q32 Write code for the producer-consumer problem in


Java? (Solution)

You might also like