Core Java Question Bank (Set-2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11
At a glance
Powered by AI
The key takeaways from the document are the core concepts of Object Oriented Programming such as abstraction, encapsulation, inheritance and polymorphism.

The core OOP concepts are abstraction, encapsulation, inheritance and polymorphism.

Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects.

QUESTIONS BANK - JAVA PROGRAMMING

(SET-2)
1) What is meant by Object Oriented Programming?
OOP is a method of programming in which programs are organized as cooperative
collections of objects. Each object is an instance of a class and each class belong to a
hierarchy.
2) What is a Class?
Class is a template for a set of objects that share a common structure and
a common behavior.
3) What is an Object?
Object is an instance of a class. It has state, behaviour and identity. It is also
called as an instance of a class.
4) What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of
similar classes are defined in their common class. An instance is also called as
an object.
5) What are the core OOP’s concepts?
Abstraction, Encapsulation, Inheritance and Polymorphism are the core
OOP’s concepts.
6) What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it
from all other kinds of objects.
7) What is meant by Encapsulation?
Encapsulation is the process of compartmentalising the elements of an abstraction
that defines the structure and behavior. Encapsulation helps to separate the
contractual interface of an abstraction and implementation.
8) What are Encapsulation, Inheritance and Polymorphism?
Encapsulation is the mechanism that binds together code and data it
manipulates and keeps both safe from outside interference and misuse. Inheritance is
the process by which one object acquires the properties of another object.
Polymorphism is the feature that allows one interface to be used for general class
actions.
9) What are methods and how are they defined?
Methods are functions that operate on instances of classes in which they are defined.

Notes By: AB Sir’s Coaching (8910350813) Page 1


Objects can communicate with each other using methods and can call methods in
other classes. Method definition has four parts.
10) What are different types of access modifiers (Access specifiers)?
Access specifiers are keywords that determine the type of access to
the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
public: Any thing declared as public can be accessed from anywhere.
Private: Any thing declared as private can’t be seen outside of its class.
Protected: Any thing declared as protected can be accessed by classes in the same
package and subclasses in the other packages.
Default modifier: Can be accessed only to classes in the same package.
11) What is an Object and how do you allocate memory to it?
Object is an instance of a class and it is a software unit that combines a structured set
of data with a set of operations for inspecting and manipulating that data. When an object is
created using new operator, memory is allocated to it.
12) Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also
helps resolve naming conflicts when different packages have classes with the same names.
Packages access level also allows protecting data from being used by the non-authorized
classes.
13) What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with
different arguments is said to be method overloading. Method overriding: When a method in
a class having the same method name with same arguments is said to be method overriding.
14) What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte
codes can be run in any platform and hence java is said to be platform independent.
15) What is a constructor? What is a destructor?
Constructor is an operation that creates an object and/or initializes its state.
Destructor is an operation that frees the state of an object and/or destroys the
object itself. In Java, there is no concept of destructors. Its taken care by the JVM.
16) What is the difference between constructor and method?
Constructor will be automatically invoked when an object is created whereas method
has to be called explicitly
17) What is a Static member class?
A static member class is a static member of a class. Like any other static method, a
static member class has access to all static methods of the parent, or top-level, class.

Notes By: AB Sir’s Coaching (8910350813) Page 2


18) In Java, How to make an object completely encapsulated?
All the instance variables should be declared as private and public getter and
setter methods should be provided for accessing the instance variables.
19) What is static variable and static method?
Static variable is a class variable which value remains constant for the entire class.
Static method is the one which can be called with the class itself and can hold only the
static variables.
20) What is finalize () method?
Finalize () method is used just before an object is destroyed and can be called
just prior to garbage collection.
21) What is the difference between String and String Buffer?
a) String objects are constants and immutable whereas String Buffer objects are not.
b) String class supports constant strings whereas String Buffer class supports growable and
modifiable strings.
22) What is the difference between Array and vector?
Array is a set of related data type and static whereas vector is a growable
array of objects and dynamic
23) What is a package?
A package is a collection of classes and interfaces that provides a high-level layer of
access protection and name space management.
24) What is the difference between this () and super ()?
This () can be used to invoke a constructor of the same class whereas super() can be
used to invoke a super class constructor.
25) Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which
first converts .java file into .class file by using Compiler (.class is nothing but byte code file.)
and Interpreter reads byte codes.
26) Define super class and subclass?
Super class is a class from which another class inherits.
Subclass is a class that inherits from one or more classes.
27) What is meant by Binding, Static binding, Dynamic binding?
Binding: Binding denotes association of a name with a class.
Static binding: Static binding is a binding in which the class association is made
during compile time. This is also called as Early binding.
Dynamic binding: Dynamic binding is a binding in which the class association is not

made until the object is created at execution time. It is also called as Late binding.

Notes By: AB Sir’s Coaching (8910350813) Page 3


28) What is meant by Inheritance?
Inheritance is a relationship among classes, wherein one class shares the
structure or behavior defined in another class. This is called Single Inheritance. If a
class shares the structure or behavior from multiple classes, then it is called Multiple
Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass
inherits from one or more generalised superclasses.
29) What is the use of Inheritance and what are its advantages?
Inheritance is the process of inheriting all the features from a class. The advantages of
inheritance are reusability of code and accessibility of variables and methods of the super
class by subclasses.
30) What is the difference between superclass and subclass?
A super class is a class that is inherited whereas sub class is a class that does the
inheriting.
31) Differentiate between a Class and an Object?
The Object class is the highest-level class in the Java class hierarchy. The Class is
used to represent the classes and interfaces that are loaded by a Java program. The Class
class is used to obtain information about an object's design. A Class is only a definition or
prototype of real life object. Whereas an object is an instance or living representation of
real life object. Every object belongs to a class and every class contains one or more
related objects.
32) What is meant by Binding?
Binding denotes association of a name with a class.
33) What is meant by Polymorphism?
Polymorphism literally means taking more than one form. Polymorphism is a
characteristic of being able to assign a different behavior or value in a subclass, to
something that was declared in a parent class.
34) Define Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response
to the call. Dynamic binding (also known as late binding) means that the code associated with
a given procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.
35) What is final modifier?
The final modifier keyword makes that the programmer cannot change the
value anymore. The actual meaning depends on whether it is applied to a class, a
variable, or a method.
final Classes- A final class cannot have subclasses.
final Variables- A final variable cannot be changed once it is initialized.

Notes By: AB Sir’s Coaching (8910350813) Page 4


final Methods- A final method cannot be overridden by subclasses.
36) What is an Abstract Class?
Abstract class is a class that has no instances. An abstract class is written with the
expectation that its concrete subclasses will add to its structure and behaviour, typically by
implementing its abstract operations.
37) What are inner class and anonymous class?
Inner class: classes defined in other classes, including those defined in methods are
called inner classes. An inner class can have any accessibility including private. Anonymous
class: Anonymous class is a class defined inside a method without a name and is instantiated
and declared in the same place and cannot have explicit constructors
38) What is an Interface?
Interface is an outside view of a class or object which emphasizes its abstraction
while hiding its structure and secrets of its behavior.
39) What is an exception?
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
40) Mention the different ways to generate an Exception?
There are two different ways to generate an Exception.
1. Exceptions can be generated by the Java run-time system.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the
Java language or the constraints of the Java execution environment.
2. Exceptions can be manually generated by the code.
Manually generated exceptions are typically used to report some error condition to
the caller of a method.
41) What is a base class?
Base class is the most generalised class in a class structure. Most applications have
such root classes. In Java, Object is the base class for all classes.
42) What is reflection in java?
Reflection allows Java code to discover information about the fields, methods and
constructors of loaded classes and to dynamically invoke them.
43) Define superclass and subclass?
Superclass is a class from which another class inherits.
Subclass is a class that inherits from one or more classes.
44) What is meant by Binding, Static binding?
Binding: Binding denotes association of a name with a class.
Static binding: Static binding is a binding in which the class association is made
during compile time. This is also called as Early binding.

Notes By: AB Sir’s Coaching (8910350813) Page 5


45) What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime
and dynamically manipulate at run time. This is supported using Reflection API with built-
in classes like Class, Method, Fields, and Constructors etc. Example: Using Java Reflection
API we can get the class name, by using the getName method.
46) What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of
the class's outer class. A static inner class does not have any object instances.
47) What is the difference between abstract class and interface?
a) All the methods declared inside an interface are abstract whereas abstract class must
have at least one abstract method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods whereas interface
we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can’t have subclasses.
48) Can you have an inner class inside a method and what variables can you access?
Yes, we can have an inner class inside a method and final variables can be accessed.
49) What are interface and its use?
Interface is similar to a class which may contain method’s signature only but not
bodies and it is a formal set of method and constant declarations that must be defined
by the class that implements it. Interfaces are useful for:
a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class
relationship. c) Determining an object’s programming interface without revealing
the actual body of the class.
50) How is polymorphism achieved in java?
Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.
51) What modifiers may be used with top-level class? Public,
abstract and final can be used for top-level class.
52) Define: Dynamic proxy.
A dynamic proxy is a class that implements a list of interfaces, which specify at runtime
when the user create the proxy. To create a proxy, use the static method
java.lang.reflect.Proxy::newProxyInstance(). This method takes three arguments:
The class loader to define the proxy class
An invocation handler to intercept and handle method calls
A list of interfaces that the proxy instance implements
53) What are the methods provided by the object class?

Notes By: AB Sir’s Coaching (8910350813) Page 6


The Object class provides five methods that are critical when writing multithreaded
Java programs:
notify
notifyAll
wait (three versions)
54) What is garbage collection? What is the process that is responsible for doing
that in java?
Reclaiming the unused memory by the invalid objects. Garbage collector is
responsible for this process
55) What kind of thread is the Garbage collector thread? - It is a daemon thread.
56) What is a daemon thread? - These are the threads which can run without user
intervention. The JVM can exit when there are daemon thread by killing them abruptly.
57) Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the
Thread class
58) What are the different states of a thread?
The different thread states are ready, running, waiting and dead.
59) Why are there separate wait and sleep methods?
Sleep (long) method maintains control of thread execution but delays the next action
until the sleep time expires. The wait method gives up control over thread execution
indefinitely so that other threads can run.
60) What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of
multiple threads to shared resources. Without synchronization, it is possible for one thread
to modify a shared object while another thread is in the process of using or updating that
object's value. This often leads to significant errors.
61) What is the difference between process and thread?
Process is a program in execution whereas thread is a separate path of execution in a
program.
62) What happens when you invoke a thread's interrupt method while it is sleeping or
waiting?
When a task's interrupt () method is executed, the task enters the ready state. The next
time the task enters the running state, an Interrupted Exception is thrown.
63) How can we create a thread?
A thread can be created by extending Thread class or by implementing Runnable
interface. Then we need to override the method public void run ().
64) What are three ways in which a thread can enter the waiting state?

Notes By: AB Sir’s Coaching (8910350813) Page 7


A thread can enter the waiting state by invoking its sleep () method, by blocking on
I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's
wait() method. It can also enter the waiting state by invoking its (deprecated) suspend ()
method.
65) What is synchronized keyword? In what situations you will Use it?
Synchronization is the act of serializing access to critical sections of code. We will
use this keyword when we expect multiple threads to access/modify the same data. To
understand synchronization we need to look into thread execution manner.
66) What is serialization?
Serialization is the process of writing complete state of java object into output
stream, that stream can be file or byte array or stream associated with TCP/IP socket.
67) What does the Serializable interface do?
Serializable is a tagging interface; it prescribes no methods. It serves to assign the
Serializable data type to the tagged class and to identify the class as one which the
developer has designed for persistence. ObjectOutputStream serializes only those objects
which implement this interface.
68) When you will synchronize a piece of code?
When the expected code will be accessed by different threads and these threads may
change a particular data causing data corruption.
69) What is the difference between yielding and sleeping?
When a task invokes its yield () method, it returns to the ready state. When a task
invokes its sleep () method, it returns to the waiting state.
70) What is casting?
There are two types of casting, casting between primitive numeric types and casting
between object references. Casting between numeric types is used to convert larger values,
such as double values, to smaller values, such as byte values. Casting between object
references is used to refer to an object by a compatible class, interface, or array type
reference.
71) What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
72) A Thread is runnable, how does that work?
The Thread class' run method normally invokes the run method of the Runnable
type it is passed in its constructor. However, it is possible to override the thread's run
method with the own.
73) Can I implement my own start () method?
The Thread start() method is not marked final, but should not be overridden. This
method contains the code that creates a new executable thread and is very specialized. The

Notes By: AB Sir’s Coaching (8910350813) Page 8


threaded application should either pass a Runnable type to a new Thread, or extend Thread
and override the run() method.
74) Do the user need to use synchronized on setValue(int)?
It depends whether the method affects method local variables, class static or
instance variables. If only method local variables are changed, the value is said to be
confined by the method and is not prone to threading issues.
75) What is thread priority?
Thread Priority is an integer value that identifies the relative order in which it should
be executed with respect to others. The thread priority values ranging from 1- 10 and the
default value is 5. But if a thread have higher priority doesn't means that it will execute first.
The thread scheduling depends on the OS.
76) What are the different ways in which a thread can enter into waiting state?
There are three ways for a thread to enter into waiting state. By invoking its sleep ()
method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by
invoking an object's wait () method.
77) How would you implement a thread pool?
The ThreadPool class is a generic implementation of a thread pool, which takes the
following input Size of the pool to be constructed and name of the class which implements
Runnable (which has a visible default constructor and constructs a thread pool with active
threads that are waiting for activation. Once the threads have finished processing they come
back and wait once again in the pool.
78) What is a thread group?
A thread group is a data structure that controls the state of collection of thread as
a whole managed by the particular runtime environment.
79) What is String in Java ? Is String is data type?
String in Java is not a primitive data type like int, long or double. String is a class or in more
simple term a user defined type. This is confusing for some one who comes from C
background. String is defined in java.lang package and wrappers its content in a character
array. String provides equals() method to compare two String and provides various other
method to operate on String like toUpperCase() to convert String into upper case, replace() to
replace String contents, substring() to get substring, split() to split long String into multiple
String.
80) Why String is final in Java
String is final by design in Java, some of the points which makes sense why String is final is
Security, optimization and to maintain pool of String in Java. for details on each of this point
81) What is Difference between String and StringBuffer in Java

Notes By: AB Sir’s Coaching (8910350813) Page 9


This is probably the most common question on String I have seen in Java interviews. Though
String and Stringbuffer are two different class they are used in context of concatenating two
Strings, Since String is immutable in Java every operation which changes String produces
new String, which can be avoided by using Stringbuffer. See String vs StringBuffer for more
details.
82) What is difference in String on C and Java
If you have mentioned C in your resume, then you are likely to face this String interview
question. Well C String and Java String are completely different to each other, C String is a
null terminated character array while String in Java is an Object. Also String is more feature
rich in Java than C.
83) Does String is thread-safe in Java
If you are familiar with the concept of immutability and thread-safety you can easily answer
this String interview question in Java. Since String is immutable, it is thread-safe and it can
be shared between multiple thread without external synchronization.
84) What is mean by String Literals?
The string of characters is represented as String literals in Java. In Java a string is not
a basic data type, rather it is an object. These strings are not stored in arrays as in C
language. There are few methods provided in Java to combine strings, modify strings and to
know whether to strings have the same value.
Lets see some more examples of string literals:
"" // the empty string
"\"" // a string containing "
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
85) List the two methods to search a string.
1. indexOf()
2. lastIndexOf()
86) Define String Buffer Class.
StringBuffer class is a mutable class unlike the String class which is immutable.
Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed
dynamically. String buffers are preferred when heavy modification of character strings is
involved (appending, inserting, deleting, modifying etc).
Strings can be obtained from string buffers. Since the StringBuffer class does not
override the equals() method from the Object class, contents of string buffers should be
converted to String objects for string comparison. A StringIndexOutOfBoundsException is
thrown if an index is not valid when using wrong index in String Buffer manipulations

Notes By: AB Sir’s Coaching (8910350813) Page 10


It consist of the following functions append, insert, reverse, setCharAt, charAt,
length, deleteCharAt, substring, delete, capacity.
87) What is the use of toString() Method?
The method is used to get a String object representing the value of the Number
Object.
If the method takes a primitive data type as an argument then the String object
representing the primitive data type value is return.
If the method takes two arguments then a String representation of the first argument
in the radix specified by the second argument will be returned.
88) What is the use of getBytes() Method?

This method has following two forms:

getBytes(String charsetName): Encodes this String into a sequence of bytes using


the named charset, storing the result into a new byte array.
getBytes(): Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.

Notes By: AB Sir’s Coaching (8910350813) Page 11

You might also like