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

My java question

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities, enhancing code readability and maintainability. Key features of OOP include inheritance, encapsulation, polymorphism, and data abstraction, which facilitate better software design and management. The document also discusses the Collection Framework in Java, highlighting its architecture for storing and manipulating groups of objects, and differentiates between 'Collection' as an interface and 'Collections' as a utility class.

Uploaded by

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

My java question

Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities, enhancing code readability and maintainability. Key features of OOP include inheritance, encapsulation, polymorphism, and data abstraction, which facilitate better software design and management. The document also discusses the Collection Framework in Java, highlighting its architecture for storing and manipulating groups of objects, and differentiates between 'Collection' as an interface and 'Collections' as a utility class.

Uploaded by

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

Object Oriented Programming languages

(Ques. 189-197)
1.What is meant by the term OOPs?

OOPs refers to Object-Oriented Programming. It is the programming paradigm that is defined using
objects. Objects can be considered as real-world instances of entities like class, that have some
characteristics and behaviours.

2. What is the need for OOPs?

There are many reasons why OOPs is mostly preferred, but the most important among them are:
1.OOPs helps to understand the software easily, although they don’t know the actual
implementations.

2. With OOPs, the readability, understandability, and maintainability of the code increase multifold.

3. Even very big software can be easily written and managed easily.

4. What are some other programming paradigms other than OOPs?

Programming paradigm is the style or a method of writing a program.  two types

Imperative Programming Paradigm


1.Procedural Programming Paradigm
2.Object-Oriented Programming or OOP
3.Parallel Programming
Declarative Programming Paradigm
a) Logical Programming Paradigm
b) Functional Programming Paradigm:
c) Database Programming Paradigm

1. Imperative Programming Paradigm:


a) Procedural Programming Paradigm:

b) Object-Oriented Programming or OOP


c) Parallel Programming: Parallel programming paradigm breaks a task into subtasks
and focuses on executing them simultaneously at the same time.

2. Declarative Programming Paradigm:

Here we just want the data but how that we don’t care.
a) Logical Programming Paradigm
b) Functional Programming Paradigm:
c) Database Programming Paradigm

9. What is a class?

A class can be understood as a template or a blueprint, which contains some values, known as
member data or member, and some set of rules, known as behaviors or functions. So when an object
is created, it automatically takes the data and functions that are defined in the class.

10. What is an object?

An object refers to the instance of the class. In the real world, an object is an actual entity to which a
user interacts, whereas class is just the blueprint for that object. So the objects consume space and
have some characteristic behavior. For example, a specific car.

5. What is meant by Structured Programming?

Structured Programming refers to the method of programming which consists of a completely


structured control flow. Here structure refers to a block, which contains a set of rules, and has a
definitive control flow, such as (if/then/else), (while and for), block structures, and subroutines.
Nearly all programming paradigms include Structured programming, including the OOPs model.

6. What are the main features (Pillars) of OOPs?

OOPs or Object Oriented Programming mainly comprises of the below four features, and make sure
you don't miss any of these:

Inheritance = 4 types
Encapsulation
Polymorphism
Data Abstraction
Inheritance = Inheritance is a mechanism that allows one class to inherit the
properties and behaviors (fields and methods) of another class. The class that is
being inherited from is called the superclass or parent class, and the class that
inherits is called the subclass or child class.
Example  We can take parent and child relationship as an example of inheritance.
1. Single Inheritance: A class can only inherit from one
superclass.

2. Multilevel Inheritance: A class can inherit from another


class, which in turn can inherit from another class.
3. Hierarchical Inheritance: Multiple classes can inherit from a
single superclass.
4. Multiple Inheritance (through interfaces): A class can
implement multiple interfaces, allowing it to inherit the abstract
methods from those interfaces.
Q. why java doesn’t support multiple inheritance.
In Java, multiple inheritance of classes is not supported, meaning a class
cannot directly inherit from more than one class. This design choice was
made by Java's creators to avoid certain complications and ambiguities
that can arise with multiple inheritance, such as the diamond problem.

The diamond problem occurs when a class inherits from two classes that
have a common ancestor. This can lead to ambiguity in method resolution
if both parent classes provide an implementation for the same method.
Resolving such conflicts can become complex and error-prone.

However, Java supports multiple inheritance of interfaces. An interface in


Java is a contract specifying a set of methods that a class implementing
the interface must provide. Since interfaces only contain method
signatures and constants, and not actual implementations, there's no
conflict when a class implements multiple interfaces.
Encapsulation = Encapsulation is defined as the binding of data and methods in a single unit. It
also implements data hiding.

Encapsulation can also be defined in two different ways:

1) Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting
access to any member of an object.

2) Data binding: Encapsulation is the process of binding the data members and the methods
together as a whole, as a class.

Example = Capsule
The bag contains different stuffs like pen, pencil, notebook etc within it, in
order to get any stuff you need to open that bag, similarly in java an encapsulation
unit contains it's data and behavior within it and in order to access them you need
an object of that unit.
 The Person class encapsulates the data ( name and age) by making
them private, which means they can only be accessed within the
Person class itself.
 Getter methods ( getName() and getAge()) are provided to retrieve
the values of the encapsulated data, and setter methods ( setName()
and setAge()) are provided to modify them. These methods act as
interfaces to the encapsulated data, allowing controlled access from
outside the class.
 Encapsulation ensures that the internal state of a Person object
cannot be directly accessed or modified from outside the class,
promoting data integrity and encapsulation.

Polymorphism=Polymorphism is composed of two words - “poly” which means “many”, and


“morph” which means “shapes”. Therefore Polymorphism refers to something that has many shapes.
Polymorphims in java is a mechanism in which an object or it's behavior can have
many different forms, we call such objects as polymorphic object.

1.To take a real time example, we can consider ourself. As a person we have many

different forms like student, teacher, player, father/mother etc. The same person can

be a teacher as well as a player, so we can say person object is polymorphic in

nature.
2. Another real world example is your mobile. Sometime your mobile behaves as a

phone, sometime as a camera, sometime as a radio etc. Here the same mobile

phone has different forms, so we can say the mobile object is polymorphic in nature.

Compile-time polymorphism

Run time polymorphism

Compile-time Polymorphism (Method Overloading): (Static Polymorphism)


Also known as method overloading, this type of polymorphism occurs when a
class has multiple methods with the same name but different parameter
lists (different types or a different number of parameters). The compiler
determines which method to invoke based on the method's signature during the
compile-time phase. Method overloading
Runtime Polymorphism: (dynamic polymorphism) also known as Dynamic
Polymorphism, refers to the type of Polymorphism that happens at the run time. What it means is it
can't be decided by the compiler. Therefore what shape or value has to be taken depends upon the
execution. Hence the name Runtime Polymorphism. method overriding.
Abstraction=
Hide all unnecessary details and showing only the important part to the user.

 abstract classes {we give idea but not implementation }

interfaces

In Java and other object-oriented programming languages, abstraction is often


implemented through abstract classes and interfaces. Abstract classes provide a
blueprint for other classes and may include abstract methods (methods without a
body) that must be implemented by concrete subclasses. Interfaces define a
contract that implementing classes must adhere to, specifying a set of methods
that must be implemented.

Example To take a real time example, when we login to any social networking
site like Facebook, Twitter, Linkedin etc, we enter our user id and password and then

we get logged in. Here we don't know how they are processing the data or what logic

or algorithm they are using for login. Those informations are abstracted/hidden from

us, since those are not essential for us. This is basically what abstraction is.
Another real world example of abstraction could be your TV remote. The remote has

different functions like on/off, change channel, increase/decrease volume etc. You

use these functionalities just pressing the button. The internal mechanism of these

functionalities are abstracted from you as those are not essential for you to know.
 Shape is an abstract class that defines an abstract method
calculateArea() . This method doesn't have an implementation; it's
left to concrete subclasses to provide their own implementations.
 Rectangle and Circle are concrete subclasses of Shape. They provide
their own implementations of the calculateArea() method based on
the specific formulas for calculating the area of a rectangle and a
circle, respectively.
 By using abstraction, we can treat different shapes uniformly
through the common Shape interface, regardless of their specific
implementations.

Abstraction helps in managing complexity by hiding implementation


details, promoting code reusability, and enabling flexibility in code design.
It allows developers to focus on high-level concepts and interactions
rather than dealing with low-level implementation specifics.

25. Are there any limitations of Inheritance?

Yes, with more powers comes more complications. Inheritance is a very powerful feature in OOPs,
but it has some limitations too. Inheritance needs more time to process, as it needs to navigate
through multiple classes for its implementation. Also, the classes involved in Inheritance - the base
class and the child class, are very tightly coupled together. So if one needs to make some changes,
they might need to do nested changes in both classes. Inheritance might be complex for
implementation, as well. So if not correctly implemented, this might lead to unexpected errors or
incorrect outputs.
32. What is the difference between overloading and overriding?

Overloading is a compile-time polymorphism feature in which an entity has multiple


implementations with the same name. For example, Method overloading and Operator overloading.

Whereas Overriding is a runtime polymorphism feature in which an entity has the same name, but its
implementation changes during execution. For example, Method overriding.

34. What is an abstract class?

An abstract class is a special class containing abstract methods. The significance of abstract class is
that the abstract methods inside it are not implemented and only declared. So as a result, when a
subclass inherits the abstract class and needs to use its abstract methods, they need to define and
implement them.

cannot create an instance of abstract class.

can have abstract/ non-abstract methods

can have contructor

29. What is an interface?

Interfaces is a blue print of a class.

Multiple inheritance (5th type)

total abstraction (100 % )


All methods are public, abstract & without implementation.

Used to achieve total abstraction.

Variables in the interfaces are final, public and static.

An interface refers to a special type of class, which contains methods, but not their definition. Only
the declaration of methods is allowed inside an interface. To use an interface, you cannot create
objects. Instead, you need to implement that interface and define the methods for their
implementation classes.
Q. What is static variable?

Static keyword in java is used to share the same variable or method of a given class.

Properties

Functions

Blocks

Nested Classes

output :- JVM

Even if we haven’t created the value of schoolName of object s2 still the output is same as object s1.
Q. What is Super keyword?

Super keyword is used to refer immediate super class object.

to access parent’s properties.

to access parent’s function.

to access parent’s constructor.

Agar super() agar nhi bhi likhenege toh bhi parent class ka constructor bydefault call hota hai pehele

Yeh automatically line likh deta hai

36. What are access specifiers and what is their significance?

Access specifiers, as the name suggests, are a special type of keywords, which are used to control or
specify the accessibility of entities like classes, methods, etc. Some of the access specifiers or access
modifiers include “private”, “public”, etc. These access specifiers also play a very vital role in
achieving Encapsulation - one of the major features of OOPs.

Q. What are Constructor in Java?

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


The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes.
Constructor have the same name as the class name.
Constructor don’t have a return type. ( Not even void )
Constructor are only called once, at object creation.
Memory allocation happens when constructor is called.
1. Non- parameterized
2. Parameterized
3. Copy Constructor

Q. what is constructor Overloading?

Constructor overloading is a feature in object-oriented programming languages that allows a class to


have more than one constructor, each with a different parameter list. This enables the creation of
objects in different ways, depending on the arguments provided.
Q. What is copy constructor?

A copy constructor in Java is a special type of constructor used to create a new object as a copy of an
existing object. This constructor takes an object of the same class as a parameter and initializes the
new object with the same values as the given object.
Q. what is destructor?

A destructor works opposite to constructor; it destructs the objects of classes. It


can be defined only once in a class. Like constructors, it is invoked automatically.
But in Java it not exists, Here garbage collector works as a destructor.

==================================================================================

Collection Framework Questions


(197-230)
1. What is Collection in Java?

In Java, a collection is a framework that provides an architecture for storing and manipulating a
collection of objects. In JDK 1.2, a new framework called "Collection Framework" was created, which
contains all of the collection classes and interfaces. Collections in Java are capable of doing any data
operations such as searching, sorting, insertion, manipulation, and deletion. A single unit of objects
in Java is referred to as a collection. The two basic “root” interfaces of Java collection classes are the
Collection interface (java.util.Collection) and the Map interface(java.util.Map). Many interfaces (Set,
List, Queue, Deque) and classes are available in the Java Collection framework (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

2.Why we need to go for collection?

To store the data there two methods available:

1.Primitive data type - ( int, byte, short, long etc)


int a=2;

int b=3;

for storing the thousand of value we need to create the 1000 variables which is very inefficient
method so we came with Arrays concept.

2.Refrenced data type- (Array, String, Class)


We can now store the 1000 values in a single variable
int[] a= new int[500]
int [0] a= 100;
int [499]=777;
Limitations for Arrays-
1.Arrays size is fixed, in future according to need we cannot increase or
decrease the size;
2. We can only store the homogenous data type.
Student a[] = new Student[100];
a[0]= new Student[101, “Raju”];
a[1]= new Employee[ 102, “”Sanju];-----------x
To overcome this problem we can use the Object class Array
Object [] a= new Object[100];
3.Insert, update, sort, retrive the data these common operations are
supported.
To overcome the problems of array we are going to use Collections.

Collection
1. Collections are growable in nature that is based on our requirement we can increase (or) decrease
the size hence memory point of view collections concept is recommended to use.

2. Collections can hold both homogeneous and heterogeneous objects.

3. Every collection class is implemented based on some standard data structure hence for every
requirement ready-made method support is available being a programmer we can use these
methods directly without writing the functionality on our own.
--->Collections is an entity which is used to store the group of Objects.

---->Collections are growable in nature

(dynamically collection size can be increased or decreased based on data).

--->We can store any type of data (Homogenous and hetrogenous).

---> Collections providing predefined methods to insert, update , delete, retrieve or sort etc.

---->Collections is a entity / container which is used to store group of objects.

4.Differentiate between Collection and collections in the context of Java.

Collection: The collection framework's root interface is referred to as the collection. It has a number
of classes and interfaces for representing a collection of individual objects as a single unit.

Collections: "Collections is an utility class" present in java.util package to define several utility
methods for Collection objects. These methods include sorting, searching,
synchronizing, and other operations on collections.

Q. Why we are calling collections as a framework?


Collections ------------- Collections Framework

Collections is called as framework because it is providing predefined interfaces, classes and method
to perform operations on data.

5.Explain the hierarchy of the Collection framework in Java.


3. What is the difference between Array and Collection in java?
5. Explain the various interfaces used in the Collection framework.

The collection framework has several interfaces, each of which is used to store a different sort of
data. The interfaces included in the framework are listed below.

1. Iterable Interface: This is the collection framework's primary interface. The iterable interface is
extended by the collection interface. As a result, all interfaces and classes implement this interface
by default. This interface's main purpose is to provide an iterator for the collections. As a result, this
interface only has one abstract method, the iterator.

2. Collection Interface: The collection framework's classes implement this interface, which extends
the iterable interface. This interface covers all of the basic methods that every collection has, such as
adding data to the collection, removing data from the collection, clearing data, and so on. All of
these methods are incorporated in this interface because they are used by all classes, regardless of
their implementation style. Furthermore, including these methods in this interface guarantees that
the method names are consistent across all collections. In summary, we may conclude that this
interface lays the groundwork for the implementation of collection classes.

3. List Interface: The collection interface has a child interface called the list interface. This interface
is devoted to list data, in which we can store all of the objects in an ordered collection. This also
allows for the presence of redundant data. Various classes, such as ArrayList, Vector, Stack, and
others, implement this list interface. We can create a list object with any of these classes because
they all implement the list.

4. Queue Interface: A queue interface, as the name implies, follows the FIFO (First In First Out) order
of a real-world queue line. This interface is for storing all elements in which the order of the
elements is important. When we try to shop at a store, for example, the bills are issued on a first-
come, first-served basis. As a result, the individual whose request is first in line receives the bill first.
PriorityQueue, Deque, ArrayDeque, and other classes are available. Because all of these subclasses
implement the queue, we can use any of them to create a queue object.

5. Deque Interface: It differs slightly from the queue data structure. Deque, also known as a double-
ended queue, is a data structure in which elements can be added and removed from both ends. The
queue interface is extended by this interface. ArrayDeque is the class that implements this interface.
Because this class implements the deque, we can use it to create a deque object.

6. Set Interface: A set is an unordered group of objects in which duplicate values cannot be kept. This
collection is utilised when we want to avoid duplication of things and only keep the ones that are
unique. Various classes, such as HashSet, TreeSet, LinkedHashSet, and others, implement this set
interface. We can create a set object with any of these classes because they all implement the set.

7. Sorted Set Interface: This interface resembles the set interface in appearance. The only difference
is that this interface provides additional methods for maintaining element ordering. The sorted set
interface is an extension of the set interface that is used to manage sorted data. TreeSet is the class
that implements this interface. We can create a SortedSet object using this class because it
implements the SortedSet interface.
6. Difference between ArrayList and LinkedList.

ArrayList LinkedList

1) ArrayList internally uses LinkedList internally uses


a dynamic array to store a doubly linked list to
the elements. store the elements.

2) Manipulation with Manipulation with LinkedList


ArrayList is slow because it is faster than ArrayList
internally uses an array. If because it uses a doubly
any element is removed linked list, so no bit shifting
from the array, all the other is required in memory.
elements are shifted in
memory.

3) An ArrayList class can act LinkedList class can act as


as a list only because it a list and queue both
implements List only. because it implements List
and Deque interfaces.

4) ArrayList is better for LinkedList is better for


storing and manipulating data.
accessing data.

5) The memory location for The location for the


the elements of an ArrayList elements of a linked list is
is contiguous. not contagious.

6) Generally, when an There is no case of default


ArrayList is initialized, a capacity in a LinkedList. In
default capacity of 10 is LinkedList, an empty list is
assigned to the ArrayList. created when a LinkedList is
initialized.

7. Differentiate between ArrayList and Vector in java.

Vector is synchronized, which means that only one thread can access the code at a time, however,
ArrayList is not synchronized, which means that multiple threads can operate on ArrayList at the
same time. In a multithreading system, for example, if one thread is executing an add operation,
another thread can be performing a removal action. If multiple threads access ArrayList at the same
time, we must either synchronize the code that updates the list fundamentally or enable simple
element alterations. The addition or deletion of element(s) from the list is referred to as structural
change. It is not a structural change to change the value of an existing element.

8. Differentiate between List and Set in Java.


The List interface is used to keep track of an ordered collection. It is the Collection's child interface. It
is an ordered collection of objects that allows for the storage of duplicate values. The insertion order
is preserved in a list, which enables positional access and element insertion.

The set interface is part of java.util package and extends the Collection interface. It is an unordered
collection of objects in which duplicate values cannot be stored. It's an interface for using the
mathematical set. This interface inherits the Collection interface's methods and adds a feature that
prevents duplicate elements from being inserted.

9. Differentiate between Iterator and ListIterator in Java.

In Java's Collection framework, iterators are used to obtain elements one by one. It can be used on
any type of Collection object. We can execute both read and remove operations using Iterator.
Iterator must be used whenever we want to iterate elements in all Collection framework
implemented interfaces, such as Set, List, Queue, and Deque, as well as all Map interface
implemented classes. The only cursor accessible for the entire collection framework is the iterator.

ListIterator is only useful for classes that implement List collections, such as array lists and linked lists.
It can iterate in both directions. When we wish to enumerate List elements, we must use ListIterator.
This cursor has additional methods and capabilities than the iterator.
10. Differentiate between HashSet and TreeSet. When would you prefer TreeSet to HashSet?
Set :

Set is interface available in java.util package.

Set interface extending from collection interface.

Set is used to store group of objects.

Duplicates objects are not allowed.

Support homogenous &Hetrogeneous data.

i.HashSet:-

Insertion ordered not maintained.

Duplicates are not allowed.

Null objects are allowed.

Initial capacity is 16.

Load Factor 0.75.

Internal data structure is Hashtable.

iii.TreeSet
Natural sorting order, it means whatever type object you give as input it will automatically arrange
itself in a ascending order or in alphabetical order.

Internal data structure is Binary Tree.

Null values are not allowed because it arranges data it ascending order and null values can’t be
compare with other data to arrange itself.

Homogenous values.

When we add null values it will try to compare null values with previous objects we will get
NullPointerException.

TreeSet shouble perform sorting so always it will compare newly added objects with old objects. In
order to compare the objects should be same type otherwise we will get the ClassCastException.

Following are the cases when TreeSet is preferred to HashSet :

1. Instead of unique elements, sorted unique elements are required. TreeSet returns a sorted list that
is always in ascending order.

2. The locality of TreeSet is higher than that of HashSet. If two entries are close in order, TreeSet
places them in the same data structure and hence in memory, but HashSet scatters the entries over
memory regardless of the keys to which they are linked.

3. To sort the components, TreeSet employs the Red-Black tree method. TreeSet is a fantastic
solution if you need to do read/write operations regularly.

12. What is a priority queue in Java?

A PriorityQueue is used when the objects are supposed to be


processed based on the priority. It is known that a Queue follows
the First-In-First-Out algorithm, but sometimes the elements of the
queue are needed to be processed according to the priority, that’s
when the PriorityQueue comes into play.
The PriorityQueue is based on the priority heap. The elements of
the priority queue are ordered according to the natural ordering, or
by a Comparator provided at queue construction time, depending
on which constructor is used.
14. Differentiate between Set and Map in Java.
Set :

Set is interface available in java.util package.


Set interface extending from collection interface.
Set is used to store group of objects.
Duplicates objects are not allowed.
Support homogenous &Hetrogeneous data.
Map: key, value

Map is an interface available in java.util package.


Map is used to store the data in key-value format.
One key-value pair is called as one entry.
In map keys should be unique and values be duplicates.
Map < K, V > == Map < Object, Object >
If we try store duplicates key in map then it will replace old key data with new
key data.
We can take key value as any type of data.
Map interface having several implementation classes.
15. Differentiate between HashSet and HashMap.
HashSet is a Set Interface implementation that does not allow duplicate values. The essential
point is that objects stored in HashSet must override equals() and hashCode() methods to
ensure that no duplicate values are stored in our set.
HashMap is a Map Interface implementation that maps a key to a value. In a map, duplicate
keys are not permitted.

16. What is the default size of the load factor in hashing based collection?

The default load factor size is 0.75. The default capacity is calculated by multiplying the initial
capacity by the load factor.

19. Differentiate between Comparable and Comparator in the context of Java.


20. What do you understand about BlockingQueue in Java?
21. Explain fail-fast and fail-safe iterators. Differentiate between them.
collections are divided into a types:

1. Fail Fast Collection

2. Fail Safe Collection

Fail Fast collections will throw error immediately when we modity collection object while traversing
the collection.

Ex LinkedList, Vector, ArrayList, Lin HashSet LHS etc

#Note fail fast will throw concurrent modification exception when collections is modified.

Fail safe collections will not throw any error even if we modify Collection object data (Add) Remove)

Ex-> CopyOnWriteArrayList, ConcurentHashMap etc

Note -: Fail fast collections will throw concurrent modification exception when collection is modified.

23. Differentiate between Iterator and Enumeration.


Iterator: Because it can be applied to any Collection object, it is a universal iterator. We can execute
both read and remove operations using Iterator. It's an enhanced version of Enumeration that adds
the ability to remove an element from the list.

Enumeration: An enumeration (or enum) is a data type that is defined by the user. It's mostly used
to give integral constants names, which make a program easier to comprehend and maintain. Enums
are represented in Java (since 1.5) through the enum data type.

24. What is the use of Properties class in Java? What is the advantage of the Properties file?
25. Differentiate between HashMap and HashTable.
HashMap is a non-synchronized data structure. It is not thread-safe and cannot be shared across
many threads without the use of synchronization code,

while Hashtable is synchronized. It's thread-safe and can be used by several threads. HashMap
supports one null key and numerous null values, whereas Hashtable does not. If thread
synchronization is not required, HashMap is o

26. Why does HashMap allow null whereas HashTable does not allow null?
The objects used as keys must implement the hashCode and equals methods in order to successfully
save and retrieve objects from a HashTable. These methods cannot be implemented by null because
it is not an object. HashMap is a more advanced and improved variant of Hashtable. HashMap was
invented

(7-8Q )

================================================================================
Q ( 1-25 )Basics
1.what are static blocks and static initalizers in Java ?

Static blocks or static initializers are used to initalize static fields in java. we declare static blocks
when we want to intialize static fields in our class. Static blocks gets executed exactly once when the
class is loaded . Static blocks are executed even before the constructors are executed.

2. How to call one constructor from the other constructor ?

With in the same class if we want to call one constructor from other we use this() method. Based on
the number of parameters we pass appropriate this() method is called. Restrictions for using this
method :
1) this must be the first statement in the constructor
2)we cannot use two this() methods in the constructor

5) What is super keyword in java ?


In Java, the super keyword is a reference variable that is used to refer to the immediate
parent class object. It is often used to invoke the superclass methods, access superclass
fields, and to call the superclass constructor. The super keyword is particularly useful in
scenarios where a subclass wants to override a method or field defined in its superclass
but still wants to access or invoke the original implementation.

1. Invoke Superclass Method:


2. Access Superclass Fields:
3. Invoke Superclass Constructor:

1. Invoke Superclass Method: When a method in a subclass overrides a


method in its superclass, you can use super to explicitly call the overridden
method from the superclass.
In this example, the makeSound method in the Dog class uses
super.makeSound() to call the makeSound method from the Animal class
before adding its own functionality.

2. Access Superclass Fields: The super keyword can be used to access fields
of the superclass when there is a field with the same name in both the superclass
and the subclass.

In this example, the displayColors method in the Dog class uses super.color to
access the color field from the Animal class.
3. Invoke Superclass Constructor: The super keyword is used to call the
constructor of the immediate parent class. This is particularly useful when a
subclass constructor needs to perform some additional initialization after calling
the superclass constructor.

7) Why java is platform independent?


The most unique feature of java is platform independent. In any programming language soruce code
is compiled in to executable code . This cannot be run across all platforms. When javac compiles a
java program it generates an executable file called .class file. class file contains byte codes. Byte
codes are interpreted only by JVM’s . Since these JVM’s are made available across all platforms by
Sun Microsystems, we can execute this byte code in any platform. Byte code generated in windows
environment can also be executed in linux environment. This makes java platform independent.

9) What is JIT compiler ?


The term you are likely referring to is "JIT compiler," which stands for "Just-In-Time
compiler." In the context of Java, the JIT compiler is an essential component of the Java
Virtual Machine (JVM). Here's an explanation of JIT compilation and its role in Java:

JIT Compiler:

1. Compilation Process in Java:


 When you write Java code, it is first translated into an intermediate form
called bytecode by the Java compiler. This bytecode is platform-
independent and is not directly executable by the computer's hardware.
2. Java Virtual Machine (JVM):
 The JVM is responsible for executing Java bytecode on different platforms.
Instead of interpreting the bytecode directly, the JVM uses a combination
of interpretation and Just-In-Time compilation for performance
optimization.
3. Just-In-Time (JIT) Compilation:
 The JIT compiler is a component of the JVM that translates bytecode into
native machine code at runtime, just before the code is executed. This
process is known as Just-In-Time compilation.
 The JIT compiler analyzes the frequently executed portions of the bytecode
and translates them into machine code, taking advantage of the specific
features of the underlying hardware.
 By translating bytecode into native machine code, the JIT compiler aims to
improve the performance of Java applications by reducing the overhead
associated with interpreting bytecode.

10) What is bytecode in java ?


Bytecode in Java refers to the intermediate representation of a Java program that
is generated by the Java compiler. Instead of compiling Java source code directly
into machine code, the Java compiler translates it into a platform-independent
bytecode. This bytecode is a set of instructions that is designed to be executed
by the Java Virtual Machine (JVM) during runtime.

11) Difference between this() and super() in java ?

this() is used to access one constructor from another with in the same class while super() is used to
access superclass constructor. Either this() or super() exists it must be the first statement in the
constructor.

14)What is method in java ?

In Java, a method is a block of code within a class that performs a specific task or
operation. It defines a set of instructions that can be executed when the method
is called. Methods are used to organize and structure the code, promote code
reuse, and encapsulate behavior within objects in an object-oriented
programming paradigm.

16) Why main() method is public, static and void in java ?

public : “public” is an access specifier which can be used outside the class. When main method is
declared public it means it can be used outside class.
static : To call a method we require object. Sometimes it may be required to call a method without
the help of object. Then we declare that method as static. JVM calls the main() method without
creating object by declaring keyword static.

void : void return type is used when a method doesn’t return any value . main() method doesn’t
return any value, so main() is declared as void.

17) Explain about main() method in java ?

Main() method is starting point of execution for all java applications.

public static void main(String[] args) {}

String args[] are array of string objects we need to pass from command line arguments. Every Java
application must have atleast one main method.

18)What is constructor in java ?


In Java, a constructor is a special method that is used for initializing objects of a class. It
has the same name as the class and is invoked when an object is created using the new
keyword. The primary purpose of a constructor is to set up the initial state of the object
by initializing its fields or performing other necessary setup operations.

Key points about constructors in Java:

1. Same Name as Class: The constructor method has the same name as the class
it belongs to.
2. No Return Type: Unlike regular methods, constructors do not have a return
type, not even void. They are implicitly called when an object is created and
cannot be called explicitly like other methods.
3. Initialization: Constructors are responsible for initializing the fields of the object
and performing any necessary setup. Initialization code is placed within the
constructor.
4. Default Constructor: If a class does not explicitly define any constructors, Java
provides a default constructor with no parameters. This default constructor
initializes fields to default values.
5. Overloading Constructors: A class can have multiple constructors, and they
can be overloaded by having different parameter lists. This allows for creating
objects with different initialization options.
19) What is difference between length and length() method in java ?

length() : In String class we have length() method which is used to return the number of characters in
string. Ex : String str = “Hello World”; System.out.println(str.length()); Str.length() will return 11
characters including space.

length : we have length instance variable in arrays which will return the number of values or objects
in array. For example : String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”}; Will return 6 since the
number of values in days array is 6.

20) What is ASCII Code?

ASCII stands for American Standard code for Information Interchange. ASCII character range is 0 to
255. We can’t add more characters to the ASCII Character set. ASCII character set supports only
English. That is the reason, if we see C language we can write c language only in English we can’t
write in other languages because it uses ASCII code.

21) What is Unicode ?

Unicode is a character set developed by Unicode Consortium. To support all languages in the world
Java supports Unicode values. Unicode characters were represented by 16 bits and its character
range is 0- 65,535.

Java uses ASCII code for all input elements except for Strings,identifiers, and comments. If we want
to use telugu we can use telugu characters for identifiers.We can enter comments in telugu.

22) Difference between Character Constant and String Constant in java ?

Character constant is enclosed in single quotes. String constants are enclosed in double quotes.
Character constants are single digit or character. String Constants are collection of characters.

Ex :’2’, ‘A’

Ex : “Hello World”

23) What are constants and how to create constants in java?

Constants are fixed values whose values cannot be changed during the execution of program. We
create constants in java using final keyword.

Ex : final int number =10; final String str=”java-interview –questions”

24) What are packages in java?


In Java, a package is a mechanism for organizing classes and interfaces into a
hierarchical structure. It helps in avoiding naming conflicts and provides a way to group
related classes and interfaces together. A package is essentially a directory that contains
a collection of related Java files.

Here are some key points about packages in Java.

The main use of package is :-

1) To resolve naming conflicts


2) For visibility control : We can define classes and interfaces that are not accessible outside the
class.

(Q 26- 51 )  Interview questions on Coding Standards


26) Explain Java Coding Standards for classes or Java coding conventions for classes?

Sun has created Java Coding standards or Java Coding Conventions . It is recommended highly to
follow java coding standards. Classnames should start with uppercase letter. Classnames names
should be nouns. If Class name is of multiple words then the first letter of inner word must be capital
letter.
Ex : Employee, EmployeeDetails, ArrayList, TreeSet, HashSet

27) Explain Java Coding standards for interfaces?

1) Interface should start with uppercase letters

2) Interfaces names should be adjectives

Example : Runnable, Serializable, Marker, Cloneable

28) Explain Java Coding standards for Methods?

1) Method names should start with small letters.

2) Method names are usually verbs

3) If method contains multiple words, every inner word should start with uppercase letter. Ex :
toString()

4) Method name must be combination of verb and noun

Ex : getCarName(),getCarNumber()

29) Explain Java Coding Standards for variables ?

1) Variable names should start with small letters.

2) Variable names should be nouns

3) Short meaningful names are recommended.

4) If there are multiple words every innerword should start with Uppecase character.

Ex : string,value,empName,empSalary

25) Can we have more than one package statement in source file ?

We can’t have more than one package statement in source file. In any java program there can be
atmost only 1 package statement. We will get compilation error if we have more than one package
statement in source file.

26) Can we define package statement after import statement in java?

We can’t define package statement after import statement in java. package statement must be the
first statement in source file. We can have comments before the package statement.

47) What are identifiers in java?

Identifiers are names in java program. Identifiers can be class name, method name or variable name.
Rules for defining identifiers in java:

1) Identifiers must start with letter, Underscore or dollar($) sign.

2) Identifiers can’t start with numbers .


3) There is no limit on number of characters in identifier but not recommended to have more than 15
characters.

4) Java identifiers are case sensitive.

5) First letter can be alphabet, or underscore and dollar sign. From second letter we can have
numbers .

6) We should’nt use reserve words for identifiers in java.

28) Can we have multiple classes in single file ?

Yes we can have multiple classes in single file but it people rarely do that and not recommended. We
can have multiple classes in File but only one class can be made public. If we try to make two classes
in File public we get following compilation error.

“The public type must be defined in its own file”.

29) What does null mean in java?

When a reference variable doesn’t point to any value it is assigned null. Example: Employee
employee; In the above example employee object is not instantiate so it is pointed no where.

30) What is ‘IS-A ‘ relationship in java?

‘is a’ relationship is also known as inheritance. We can implement ‘is a’ relationship or inheritance in
java using extends keyword. The advantage or inheritance or is a relationship is reusability of code
instead of duplicating the code. Ex : Motor cycle is a vehicle Car is a vehicle Both car and motorcycle
extends vehicle.

31) What is ‘HAS A’’ relationship in java?

‘Has a ‘ relationship is also known as “composition or Aggregation”. As in inheritance we have


‘extends’ keyword we don’t have any keyword to implement ‘Has a’ relationship in java. The main
advantage of ‘Has-A‘ relationship in java code reusability.

32) What are access modifiers in java?

The important feature of encapsulation is access control. By preventing access control we can misuse
of class, methods and members.

A class, method or variable can be accessed is determined by the access modifier. There are three
types of access modifiers in java. public,private,protected. If no access modifier is specified then it
has a default access.

33) What is the difference between access specifiers and access modifiers in java?

In C++ we have access specifiers as public, private, protected and default and access modifiers as
static, final. But there is no such divison of access specifiers and access modifiers in java. In Java we
have access modifiers and non access modifiers.

Access Modifiers : public, private, protected, default

Non Access Modifiers : abstract, final, stricfp.


34) What access modifiers can be used for class ?

We can use only two access modifiers for class public and default.

35) Explain what access modifiers can be used for methods?

We can use all access modifiers public, private, protected and default for methods.

36) Explain what access modifiers can be used for variables?

We can use all access modifiers public, private, protected and default for variables.

37) What is final access modifier in java?

final access modifier can be used for class, method and variables. The main advantage of final access
modifier is security no one can modify our classes, variables and methods. The main disadvantage of
final access modifier is we cannot implement oops concepts in java.

Ex: Inheritance, polymorphism.

final class: A final class cannot be extended or subclassed. We are preventing inheritance by marking
a class as final. But we can still access the methods of this class by composition. Ex: String class

final methods: Method overriding is one of the important features in java. But there are situations
where we may not want to use this feature. Then we declared method as final which will print
overriding. To allow a method from being overridden we use final access modifier for methods.

final variables: If a variable is declared as final, it behaves like a constant. We cannot modify the
value of final variable. Any attempt to modify the final variable results in compilation error. The error
is as follows.

“final variable cannot be assigned.”

38) Can we create constructor in abstract class ?

We can create constructor in abstract class, it doesn’t give any compilation error. But when we
cannot instantiate class there is no use in creating a constructor for abstract class.

39) What are abstract methods in java?


An abstract method is the method which does’nt have any body. Abstract method is declared with
keyword abstract and semicolon in place of method body.

Signature : public abstract void <method-name>();

Ex : public abstract void getDetails();

It is the responsibility of subclass to provide implementation to abstract method defined in abstract


class.

Exception Handling Interview questions


There are various types of errors
 Syntax Error
 Logical Error o
 Runtime Error.
Syntax Error
• Syntax and Logical errors are faced by Programmers, and runtime errors are faced by user.
• Spelling or grammatical mistakes are syntax errors, for example using uninitialised variable it and
using underdefined variable etc and missing a semicolon etc.
• Syntax errors can be removed with the help of compiler.

Logical Error
 Logical error is a bug in program that it to operate incorrectly, for example missing
parenthesis in the calculation.
 Logical errors are removed with the help of debugger.

Runtime Error
• Mishandling of a program causes Runtime error.

• Causes of runtime errors are bad input, unavailability of resources.

• Major problems with runtime errors is program will crash.

• Exception handling is process of responding to the runtime errors.

1. What is an exception in Java?


An unwanted unexpected event that disturbs normal flow of the program is
called exception.
2. What is exception handling in Java and what are the
advantages of exception handling?
Exception handling doesn't mean repairing an exception. We have to define
alternative way to continue rest of the program normally this way of
"defining alternative is nothing but exception handling".

Example: Suppose our programming requirement is to read data from


remote file locating at London at runtime if London file is not available
our program should not be terminated abnormally.

We have to provide a local file to continue rest of the program normally.


This way of defining alternative is nothing but exception handling.

3.Explain the exception class hierarchy.


3. Differentiate between Checked Exception and
Unchecked Exceptions in Java.
Checked Exception = Means must handle them using try and catch. You
must handle these exception. The exceptions which are checked by the
compiler for smooth execution of the program at runtime are called checked
exceptions.
Examples: IOException, FileNotFoundException, DataAccessException, InterruptedException,
etc

unchecked exceptions = The exceptions which are not checked by


the compiler are called unchecked exceptions. Means if you want to
handle it just handle it other wise no need.

1. BombBlaustException
2. ArithmeticException
3. NullPointerException

10. Can you catch and handle Multiple Exceptions in


Java?
Yes, you can catch and handle multiple exceptions in Java using multiple
catch blocks or a single catch block with a multi-catch statement. Here's
how you can do it:
When we are using multiple catch blocks, we need to ensure that in a case where the
exceptions have an inheritance relationship, the child exception type should be the first and
the parent type later to avoid a compilation error.

4. What are the important methods defined in Java’s


Exception Classs?
6.What is the difference between the throw and throws
keywords in Java?
The throw keyword allows a programmer to throw an exception object to interrupt normal program
flow. The exception object is handed over to the runtime to handle it. For example, if we want to
signify the status of a task is outdated, we can create an OutdatedTaskException that extends the
Exception class and we can throw this exception object as shown below:

If they are -ve then it cannot be calculate , then it should inform the calling method that I am not
able calculate

Then throwing an exception is basically alternative to returning.

class HelloWorld {
Static int area(int l, int b) throws Exception{
if(l<0 || b<0)
throw new Exception();
return l*b;
}

Static void meth1() Throws Exception{


System.out.println("Area is " +area(-10,5));
}
public static void main(String[] args) throws Exception {

meth1();
}
}

The throws keyword in Java is used along with the method signature to specify exceptions that the
method could throw during execution. For example, a method could throw NullPointerException or
FileNotFoundException and we can specify that in the method signature as shown below:

11. What is a stack trace and how is it related to an


Exception?
A stack trace is information consisting of names of classes and methods that were
invoked right from the start of program execution to the point where an exception
occurred. This is useful to debug where exactly the exception occurred and due to what
reasons. Consider an example stack trace in Java,

Exception in thread "main" java.lang.NullPointerException


at com.example.demoProject.Book.getBookTitle(Book.java:26)
at com.example.demoProject.Author.getBookTitlesOfAuthor(Author.java:15)
at com.example.demoProject.DemoClass.main(DemoClass.java:14)

To determine where an exception has occurred, we need to check for the beginning of
the trace that has a list of “at …”. In the given example, the exception has occurred at
Line Number 26 of the Book.java class in the getBookTitle() method. We can look at this
stack trace and go to the method and the line number mentioned in the trace and debug
for what could have caused the NullPointerException. Furthermore, we can get to know
that the getBookTitle() method in the Book.java class was called by the
getBookTitlesOfAuthor() method in the Author.java class in Line Number 15 of the file
and this in turn was called by the main() method of the DemoClass.java file in Line
Number 14.
12. What is Exception Chaining?
Exception Chaining happens when one exception is thrown due to another exception. This helps
developers to identify under what situation an Exception was thrown that in turn caused another
Exception in the program. For example, we have a method that reads two numbers and then divides
them. The method throws ArithmeticException when we divide a number by zero. While retrieving
the denominator number from the array, there might have been an IOException that prompted to
return of the number as 0 that resulted in ArithmeticException . The original root cause in this
scenario was the IOException . The method caller would not know this case and they assume the
exception was due to dividing a number by 0. Chained Exceptions are very useful in such cases. This
was introduced in JDK 1.4.

13. Can we have statements between try, catch and finally


blocks?
No. This is because they form a single unit.
Java Interview questions on threads (83-138)
83) What is process ?

A process is an independent unit of execution with its own memory space,


resources, and runtime environment. Java programs run as processes within the
Java Virtual Machine (JVM), which provides a platform-independent execution
environment.

84) What is thread in java?

A thread is the smallest unit of execution within a process. A thread represents a


separate flow of control, allowing concurrent execution of tasks. Java programs
can have multiple threads running concurrently, and each thread operates
independently, with its own set of instructions to execute.

Thread is separate path of execution in program.

Threads are

1) Light weight

2) They share the same address space.

3) creating thread is simple when compared to process because creating thread requires less
resources when compared to process

4) Threads exists in process. A process have atleast one thread.

86) What is multitasking ?


Multitasking means performing more than one activity at a time on the computer. Example Using
spreadsheet and using calculator at same time.

88) What are the benefits of multithreaded programming?

Multithreading enables to use idle time of cpu to another thread which results in faster execution of
program. In single threaded environment each task has to be completed before proceeding to next
task making cpu idle.

90) List Java API that supports threads?

java.lang.Thread : This is one of the way to create a thread. By extending Thread class and overriding
run() we can create thread in java.

java.lang.Runnable : Runnable is an interface in java. By implementing runnable interface and


overriding run() we can create thread in java

java.lang.Object : Object class is the super class for all the classes in java. In object class we have
three methods wait(), notify(), notifyAll() that supports threads.

java.util.concurrent : This package has classes and interfaces that supports concurrent programming.
Ex : Executor interface, Future task class etc

92) In how many ways we can create threads in java?

We can create threads in java by any of the two ways :

1) By extending Thread class

2) By Implementing Runnable interface.

93) Explain creating threads by implementing Runnable class?

This is first and foremost way to create threads . By implementing runnable interface and
implementing run() method we can create new thread. Method signature : public void run() Run is
the starting point for execution for another thread within our program.

Example :

public class MyClass implements Runnable {

@Override

public void run() { // T

94) Explain creating threads by extending Thread class ?

We can create a thread by extending Thread class. The class which extends Thread class must
override the run() method. Example :

public class MyClass extends Thread {

@Override
public void run() {

// Starting point of Execution }

95) Which is the best approach for creating thread ?

The best way for creating threads is to implement runnable interface. When we extend Thread class
we can’t extend any other class. When we create thread by implementing runnable interface we can
implement Runnable interface. In both ways we have to implement run() method.

96) Explain the importance of thread scheduler in java?

Thread scheduler is part of JVM use to determine which thread to run at this moment when there
are multiple threads. Only threads in runnable state are choosen by scheduler. Thread scheduler first
allocates the processor time to the higher priority threads. To allocate microprocessor time in
between the threads of the same priority, thread scheduler follows round robin fasion.

97) Explain the life cycle of thread?

A thread can be in any of the five states :

1) New : When the instance of thread is created it will be in New state.

Ex : Thread t= new Thread(); In the above example t is in new state. The thread is created but not in
active state to make it active we need to call start() method on it.

2) Runnable state : A thread can be in the runnable state in either of the following two ways :

a) When the start method is invoked or

b) A thread can also be in runnable state after coming back from blocked or sleeping or waiting
state.

2) Running state : If thread scheduler allocates cpu time, then the thread will be in running state

4) Waited /Blocking/Sleeping state: In this state the thread can be made temporarily inactive for a
short period of time. A thread can be in the above state in any of the following ways:

1) The thread waits to acquire lock of an object.

2) The thread waits for another thread to complete.

3) The thread waits for notification of other thread.

5) Dead State : A thread is in dead state when thread’s run method execution is complete. It dies
automatically when thread’s run method execution is completed and the thread object will be
garbage collected.

98) Can we restart a dead thread in java?

If we try to restart a dead thread by using start method we will get run time exception since the
thread is not alive.

99) Can one thread block the other thread?

No one thread cannot block the other thread in java. It can block the current thread that is running.
100) Can we restart a thread already started in java?

A thread can be started in java using start() method in java. If we call start method second time once
it is started it will cause RunTimeException(IllegalThreadStateException). A runnable thread cannot
be restarted.

Interview questions on Nested classses and inner classes


(138-190)
139) What are nested classes in java?

In Java, a nested class is a class defined within another class. There are several
types of nested classes in Java, including:

1. Static Nested Class (Static Inner Class)


2. Inner Class (Non-static Nested Class)
3. Local Inner Class
4. Anonymous Inner Class

1. Static Nested Class (Static Inner Class): This type of nested class is
declared with the static keyword. It is associated with the outer class, but it
doesn't have access to the instance variables and methods of the outer class
unless they are static.

outerStaticVariable is a static variable of the


outer class, and the static nested class can
directly access it.
outerInstanceVariable is an instance
variable of the outer class, but the static
nested class cannot access it directly.
If you want to access the instance
variables of the outer class in a static
nested class, you would need an instance
of the outer class.
This might involve creating an instance of
the outer class and then using that
instance to access its instance variables.
However, this is not a common practice for
static nested classes, as they are often
used in scenarios where an independent
class is needed. If instance-specific access
is required, using a non-static nested class
(inner class) is more appropriate.

2. Inner Class (Non-static Nested Class): Unlike static nested classes, inner
classes are not declared as static. They have access to the instance variables
and methods of the outer class.
3.Local Inner Class: These are inner classes defined within a method. They
have access to the variables of the method in which they are defined.

4.Anonymous Inner Class: These are inner classes without a name, often used
for implementing interfaces or extending classes on the fly.

141) Why to use nested classes in java?

(or) What is the purpose of nested class in java?

1) Grouping of related classes Classes which are not reusable can be defined as inner class instead of
creating inner class. For example : We have a submit button upon click of submit button we need to
execute some code. This code is related only to that class and cannot be reused for other class .
Instead of creating a new class we can create inner class

2) To increase encapsulation : Inner class can access private members of outer class.so by creating
getter and setter methods for private variables , outside world can access these variables. But by
creating inner class private variables can be accessed only by inner class.
3) Code readable and maintainable : Rather than creating a new class we can create inner class so
that it is easy to maintain.

4) Hiding implementation : Inner class helps us to hide implementation of class.

142) Explain about static nested classes in java?

When a static class is defined inside a enclosing class we define that as nested class. Static nested
classes are not inner classes. Static nested classes can be instantiated without instance of outer class.
A static nested doesnot have access to instance variables and non static methods of outer class.

In Java, a static nested class is a class that is defined within another class, and it
is marked with the static keyword. Unlike non-static nested classes (also known
as inner classes), static nested classes do not have access to the instance
variables and methods of the outer class without an explicit object reference.

1. Static Member:
 The static nested class is a static member of the outer class,
meaning it is associated with the class itself rather than with
instances of the class.
2. Accessing the Nested Class:
 You can instantiate the static nested class without creating an
instance of the outer class. For example:
OuterClass.StaticNestedClass nestedObj = new OuterClass.StaticNestedClass();
3. Access to Outer Class Members:
 Unlike non-static nested classes, a static nested class does not
have direct access to the instance variables and methods of
the outer class. If it needs to access them, it must do so
through an object reference to an instance of the outer class.
4. Use Cases:
 Static nested classes are often used when the nested class
logically belongs to the outer class, but doesn't require access
to its instance members. They can be seen as a way to group
classes that have a close relationship and should be placed
together.

NestedClass(5);

143) How to instantiate static nested classes in java?

We can access static members and static methods of outer class without creating any instance of
outer class.

Syntax for instantiating Static nested class :

OuterclassName.StaticNestedClassName ref=new OuterclassName.StaticNestedClassName();

144) Explain about method local inner classes or local inner classes in java?

Nested classes defined inside a method are local inner classes. We can create objects of local inner
class only inside method where class is defined. A local inner classes exist only when method is
invoked and goes out of scope when method returns.

146) Explain about anonymous inner classes in java?

Inner class defined without any class name is called anonymous inner class. Inner class is declared
and instantiated using new keyword. The main purpose of anonymous inner classes in java are to
provide interface implementation. We use anonymous classes when we need only one instance for a
class. We can use all members of enclosing class and final local variables.

When we compile anonymous inner classes compiler creates two files

1) EnclosingName.class

2) EnclsoingName$1.class

148) Is this valid in java ? can we instantiate interface in java?


Runnable r = new Runnable() {

@Override public void run() {

};

Runnable is an interface. If we see the above code it looks like we are instantiating Runnable
interface. But we are not instantiating interface we are instantiating anonymous inner class which is
implementation of Runnable interface.

In Java, you cannot instantiate an interface directly using the new keyword. An
interface is a collection of abstract methods and constants, and it cannot be
instantiated on its own. The purpose of an interface is to define a contract for
implementing classes, and instances are created for those implementing classes,
not for the interfaces themselves.
152) What are reference variables in java?
In Java, a reference variable is a variable that stores the memory address
(reference) of an object rather than the actual value of the object. This means
that when you declare a reference variable, you are creating a pointer to an
object in memory. Unlike primitive data types (e.g., int, float), which store actual
values, reference variables store the memory address of objects.

153) Will the compiler creates a default constructor if I have a parameterized constructor in the
class?

In Java, if you define a parameterized constructor in a class and don't provide a


default (no-argument) constructor explicitly, the Java compiler will not
automatically generate a default constructor for you. However, if you don't
define any constructor in your class, the compiler will provide a default
constructor for you.

154) Can we have a method name same as class name in java?

Yes we can have method name same as class name it won’t throw any compilation error but it shows
a warning message that method name is same as class name.

155) Can we override constructors in java?

Only methods can be overridden in java. Constructors can’t be inherited in java. So there is no point
of overriding constructors in java.

156) Can Static methods access instance variables in java?

No. Instance variables can’t be accessed in static methods. When we try to access instance variable
in static method we get compilation error. The error is as follows:

Cannot make a static reference to the non static field name.

157) How do we access static members in java?

Instance variables and instance methods can be accessed using reference variable . But to access
static variables or static methods we use Class name in java.
159) Difference between object and reference?

Reference and object are both different. Objects are instances of class that resides in heap memory.
Objects does’nt have any name so to access objects we use references. There is no alternative way to
access objects except through references. Object cannot be assigned to other object and object
cannot be passed as an argument to a method.

Reference is a variable which is used to access contents of an object. A reference can be assigned to
other reference ,passed to a method.

160 ) Objects or references which of them gets garbage collected?

Objects get garbage collected not its references.

161) How many times finalize method will be invoked ? who invokes finalize() method in java?
The finalize() method in Java is a method of the Object class. It is called by the garbage
collector before an object is reclaimed (i.e., before it is garbage collected). The purpose
of the finalize() method is to allow an object to perform cleanup operations before it is
garbage collected.

The finalize() method is invoked only once for an object during its lifetime. It gets called
by the garbage collector when it determines that there are no more references to the
object, and the object is eligible for garbage collection. It's important to note that the
invocation of finalize() is not guaranteed to happen at a specific time, and it is
dependent on the garbage collector's decisions.

It's generally not recommended to rely on the finalize() method for critical cleanup
tasks, as there are no guarantees about when it will be called or whether it will be called
at all. Instead, it's often better to use other mechanisms, such as try-with-resources for
resource management or explicit cleanup methods, to ensure proper resource release
and cleanup in Java.

163) Explain wrapper classes in java?

In Java, wrapper classes are used to convert primitive data types into objects
(reference types). Each primitive data type has a corresponding wrapper class in
Java. The primary purpose of wrapper classes is to provide a mechanism to treat
primitives as objects and to provide additional methods and utility functions
associated with these objects.

Wrapper classes are immutable in java. Once a value is assigned to it we cannot change the value.
if you want to use an int as an object, you can use the Integer

164) Explain different types of wrapper classes in java?


For every primitive in java we have corresponding wrapper class. Here are list of wrapper classes
available in java.

Primtive Wrapper Class

boolean --------------------Boolean
int--------------------------- Integer
float ------------------------Float
char-------------------------Character
byte -----------------------Byte
long-------------------------Long
short -----------------------Short

167) What is type conversion in java?


Assigning a value of one type to variable of other type is called type conversion. Example : int a =10;
long b=a; There are two types of conversion in java:
1) Widening conversion
2) Narrowing conversion

168) Explain about Automatic type conversion in java?


Java automatic type conversion is done if the following conditions are met :
1) When two types are compatible Ex : int, float int can be assigned directly to float variable.
2) Destination type is larger than source type. Ex : int, long

Int can be assigned directly to long .Automatic type conversion takes place if int is assigned to long
because long is larger datatype than int.
Widening Conversion comes under Automatic type conversion.

169) Explain about narrowing conversion in java?


When destination type is smaller than source type we use narrowing conversion mechanism in java.
Narrowing conversion has to be done manually if destination type is smaller than source type. To do
narrowing conversion we use cast. Cast is nothing but explicit type conversion.
Example : long a; byte b;
b=(byte)a;
Note : casting to be done only on valid types otherwise classcastexception will be thrown.

170) Explain the importance of import keyword in java?


Import keyword is used to import single class or package in to our source file.import statement is
declared after package decalaration. We use wild character (*) to import package. Note : After
compilation the compiled code does not contain import statement it will be replaced with fully
qualified class names

171) Explain naming conventions for packages ?


Sun defined standard naming conventions for packages.
1) Package names should be in small letters.
2) Package name starts with reverse company domain name (excluding www) followed by
department and project name and then the name of package.
Example : com.google.sales.employees

172) What is classpath?


The path where our .class files are saved is referred as classpath. JVM searches for .class files by
using the class path specified. Class path is specified by using CLASSPATH environment variable.
CLASSPATH environment variable can contain more than one value. CLASSPATH variable containing
more than one value is separated by semicolon. Example to set class path from command prompt :
set CLASSPATH= C:Program FilesJavajdk1.6.0_25bin;.; only parent directories need to be added to
classpath. Java compiler will look for appropriate packages and classes.
173) What is jar ?
Jar stands for java archive file. Jars are created by using Jar.exe tool. Jar files contains .class files,
other resources used in our application and manifest file.Manifest file contains class name with main
method.jar contains compressed .class files. Jvm finds these .class files without uncompressing this
jar.

Core java Serialization interview questions


(231-241)

You might also like