My java question
My java question
(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.
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.
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.
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.
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.
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.
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.
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
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
interfaces
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.
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?
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.
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.
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?
Agar super() agar nhi bhi likhenege toh bhi parent class ka constructor bydefault call hota hai pehele
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.
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?
==================================================================================
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).
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.
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.
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 providing predefined methods to insert, update , delete, retrieve or sort etc.
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.
Collections is called as framework because it is providing predefined interfaces, classes and method
to perform operations on data.
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
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.
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.
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 :
i.HashSet:-
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.
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.
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.
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.
Fail Fast collections will throw error immediately when we modity collection object while traversing
the collection.
#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)
Note -: Fail fast collections will throw concurrent modification exception when collection is modified.
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.
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
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.
JIT Compiler:
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.
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.
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.
String args[] are array of string objects we need to pass from command line arguments. Every Java
application must have atleast one main method.
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.
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.
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.
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”
Constants are fixed values whose values cannot be changed during the execution of program. We
create constants in java using final keyword.
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
3) If method contains multiple words, every inner word should start with uppercase letter. Ex :
toString()
Ex : getCarName(),getCarNumber()
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.
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.
Identifiers are names in java program. Identifiers can be class name, method name or variable name.
Rules for defining identifiers in java:
5) First letter can be alphabet, or underscore and dollar sign. From second letter we can have
numbers .
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.
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.
‘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.
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.
We can use only two access modifiers for class public and default.
We can use all access modifiers public, private, protected and default for methods.
We can use all access modifiers public, private, protected and default for variables.
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.
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.
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.
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.
1. BombBlaustException
2. ArithmeticException
3. NullPointerException
If they are -ve then it cannot be calculate , then it should inform the calling method that I am not
able calculate
class HelloWorld {
Static int area(int l, int b) throws Exception{
if(l<0 || b<0)
throw new Exception();
return l*b;
}
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:
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.
Threads are
1) Light weight
3) creating thread is simple when compared to process because creating thread requires less
resources when compared to process
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.
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.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
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 :
@Override
We can create a thread by extending Thread class. The class which extends Thread class must
override the run() method. Example :
@Override
public void run() {
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.
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.
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 :
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:
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.
If we try to restart a dead thread by using start method we will get run time exception since the
thread is not alive.
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.
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): 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.
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.
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.
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);
We can access static members and static methods of outer class without creating any instance of
outer class.
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.
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.
1) EnclosingName.class
2) EnclsoingName$1.class
};
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?
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.
Only methods can be overridden in java. Constructors can’t be inherited in java. So there is no point
of overriding constructors 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:
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.
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.
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
boolean --------------------Boolean
int--------------------------- Integer
float ------------------------Float
char-------------------------Character
byte -----------------------Byte
long-------------------------Long
short -----------------------Short
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.