Java Viva Questions Real Life Example of Encapsulation ?
Encapsulation is like enclosing in a capsule.
What are different oops concept in java ? Encapsulation is like your bag in which you can keep
OOPs stands for Object Oriented Programming. The your pen, book etc.
oops concepts are similar in any other programming What is inheritance ?
languages. Because it is not programming concept. It is used in java for achieve concept of re-usability.
All oops concept in java are: Class,Object As the name suggests , inheritance means to take
,Polymorphism ,Inheritance ,Abstraction something that already made.
,Encapsulation ,Aggreagation Composition and What is polymorphism ?
Association It is process to represent any things in multiple forms.
What is class ? Real life example of Polymorphism ?
A class is a specification or blue print or template of A Person who knows more than two languages he can
an object. speak in a language which he knows. Here person is
What is object ? Object and speak is polymorphisam.
Object is instance of class. It is dynamic memory What is method overloading in Java ?
allocation of class. When same method is available in any class with
What are the Characteristics of Object ? same name and different signature is called method
Characteristics of Object are;State Behavior and overloading.
Identity. What is method overriding in Java ?
Can a class extend more than one class in Java ? When same method available in base class and drive
No, a class can only extend another class because class with same name and same signature it is called
Java doesn't support multiple inheritances but yes, it method overriding.
can implement multiple interfaces. What is Aggregation ?
What is the difference between abstraction and If a class have an entity reference, it is known as
polymorphism in Java ? Aggregation. Aggregation represents HAS-A
Abstraction generalizes the concept and relationship..
Polymorphism allow you to use different What is Composition ?
implementation without changing your code. Composition is the design technique to implement
What is an Abstraction ? has-a relationship in classes. Composition in java is
Abstraction is a process to show only usful data and achieved by using instance variables that refers to
remaining hide from user. other objects.
Real Life Example of Abstraction ? Can we declare abstract method as final ?
When you log into your email, compose and send a No. its not possible to declare abstract method with
mail. Again there is a whole lot of background final keyword. Because abstract methods should be
processing involved, verifying the recipient, sending override by its sub classes.
request to the email server, sending your email. Here Is it possible to declare abstract method as
you are only interested in composing and clicking on private ?
the send button. What really happens when you click No. its not possible to declare abstract method with
on the send button, is hidden from you. private. Because abstract methods should be override
Real life example of abstraction ? by its sub classes.
Real life example of abstraction is ATM machine; Why use constructor ?
here only show balance in your account but not The main purpose of create a constructor is, for
display ATM pin code. placing user defined values in place of default values.
What is Encapsulation ? Why constructor not return any value ?
The process of binding data and methods into a single Constructor will never return any value even void,
unit is known as Encapsulation. In other word The because the basic aim constructor is to place value in
process of binding the data with related methods the object
known as encapsulation.
Why constructor definition should not be static ? Real life example of Abstraction ?
Constructor definition should not be static because Mobile phone is one of example of abstraction. We
constructor will be called each and every time when only know about how to call and use mobile but we
object is created. If you made constructor is static can't know about internal functionally of mobile
then the constructor before object creation same like phone.
main method. Real life example of Abstraction and
Why constructor is not inherited ? Encapsulation ?
Constructor will not be inherited from one class to Outer Look of a Television, like it has a display
another class because every class constructor is screen and channel buttons to change channel it
created for initialize its own data members. explains Abstraction but Inner Implementation detail
What is purpose of default constructor ? of a Television how CRT and Display Screen are
The purpose of default constructor is to create connect with each other using different circuits , it
multiple object with respect to same class for placing explains Encapsulation.
same value. Which of the following Java feature show only
What is purpose of parameterized constructor ? important information ?
The purpose of parametrized constructor is to create • Inheritance
multiple object with respect to same class for placing • Encapsulation
different value of same type or different type or both. • Abstraction
Is constructor inherited? • Composition
No, constructor is not inherited. Ans: Abstraction
Can you make a constructor final? What is Polymorphism ?
No, constructor can't be final. The ability to define a function in multiple forms is
What is the purpose of default constructor? called Polymorphism.
The default constructor provides the default values to
What is Overloading ?
the objects. The java compiler creates a default Whenever several methods have same names with;
constructor only if there is no constructor in the class. • Different method signature and different
Can we use both "this" and "super" in a
number or type of parameters.
constructor ?
No, because both this and super should be the first • Same method signature but different number
statement. of parameters.
Does constructor return any value? • Same method signature and same number of
yes, that is current instance (You cannot use return parameters but of different type
type yet it returns a value). It is determined at the compile time.
What is flow of constructor in Java ? What is method overriding ?
Constructor are calling from bottom to top and If subclass (child class) has the same method as
executing from top to bottom. declared in the parent class, it is known as method
Why overriding is not possible at constructor level. overriding in java. It is determined at the run time.
? Difference between method overloading and
The scope of constructor is within the class so that it mehtod Overloading ?
is not possible to achieved overriding at constructor Method overloading is determined at the compile time
level. and method overriding is determined at the run time
What is Abstraction ? How to achieve polymorphism in Java ?
Abstraction is a process of hiding the implementation How to achieve polymorphism in Java ?
details and showing only functionality to the user. In Java, static polymorphism is achieved through
How achieve Abstraction in Java ? method overloading and method overriding.
There are two ways to achieve abstraction in java Types of polymorphism in Java ?
• Abstract class (0 to 100%) In Java, there are two types of polymorphism.
• Interface (100%) • Compile time polymorphism (static binding
or method overloading)
• Runtime polymorphism (dynamic binding or class Demo {
method overriding)
public static void main(String[] args)
How to achieve static polymorphism in Java ? {
In Java, static polymorphism is achieved through Vehicle obj=new MotorBike();
method overloading. obj.move(); // prints message MotorBike can
How to achieve dynamic polymorphism in Java ? move and accelerate too!!!
In Java, dynamic polymorphism is achieved through obj=new Vehicle();
method overriding. obj.move(); // prints message Vehicles can move!!
}
What is Compile time polymorphism ?
}
As the meaning is implicit, this is used to write the
In Java Programming Inheritance is used for reuse
program in such a way, that flow of control is decided
features of one class into another class, Using this
in compile time itself. It is achieved using method
concept enhance (improve or increase) performance
overloading.
of application.
Example
What is Inheritance ?
public static int add(int a, int b)
Inheritance is one of the main features of any object
{
...... oriented programming. Using inheritance concept, a
...... class (Sub Class) can inherit properties of another
} class (Super Class). So it is used for reuse features.
Main advantage of using Inheritance ?
public static double add(double a, double b) Using this feature you can reuse features, less
{
memory wastage, less time required to develop and
......
...... application and improve performance of application.
} Types of Inheritance supported by Java ?
Java support only four types of inheritance in java.
public static float add(float a, float b) • Single Inheritance
{ • Multi level Inheritance
......
...... • Hybrid Inheritance
} • Hierarchical Inheritance
What is Runtime polymorphism ? Why use Inheritance ?
Run time Polymorphism also known as method • For Code Re usability.
overriding and it is achieve at runtime. • For Method Overriding.
Example
What is multilevel inheritance ?
class Vehicle
Getting the properties from one class object to another
{
public void move() class object level wise with different priorities.
{ Which of these keyword must be used to inherit a
System.out.println("Vehicles can move !!!!"); class ?
} • a) super
} • b) this
• c) extent
class MotorBike extends Vehicle
{ • d) extends
public void move() d. extends
{ What is Multiple Inheritance ?
System.out.println("MotorBike can move and The concept of Getting the properties from multiple
accelerate too!!!");
class objects to sub class object with same priorities is
}
} known as multiple inheritance.
How Inheritance can be implemented in java ? concept in java. in java can not extend more than one
Inheritance can be implemented in Java using two classes, but a class can implement more than one
keywords, they are; interfaces.
• extends Why we need to use Inheritance ?
• Implements It is used for code re-usability and for Method
Which of these keywords is used to refer to member Overriding.
of base class from a sub class ? Can a class extend itself ?
• a) upper No, A class can't extend itself.
What is syntax of Inheritance ?
• b) super
Syntax
• c) this public class subclass extends superclass
• d) None of these {
Answer: b
//all methods and variables declare here
extends is used for developing inheritance between }
two classes and two interfaces. Example of Single Inheritance in Java
Implements keyword is used to developed inheritance Example
between interface and class. class Faculty
What is syntax of inheritance ? {
Syntax float salary=30000;
public class subclass extends superclass }
{ class Science extends Faculty
//all methods and variables declare here {
} float bonous=2000;
Which inheritance are not supported bb Java ? public static void main(String args[])
Multi Inheritance is not supported by java. {
Science obj=new Science();
How Inheritance can be implemented in java ? System.out.println("Salary is:"+obj.salary);
Inheritance can be implemented in JAVA using these System.out.println("Bonous is:"+obj.bonous);
two keywords; extends and implements }
How do you implement multiple inheritance in }
java ? why Java Doesn't Support multiple Inheritance ?
Using interfaces java can support multiple inheritance Due to ambiguity problem.
concept in java. What happens if super class and sub class having
Syntax same field name ?
interface A Super class field will be hidden in the sub class. You
{ can access hidden super class field in sub class using
.... super keyword.
.... How do you implement multiple inheritance in
} Java ?
interface B Example
{ interface A
.... {
.... .....
} .....
class C implements A,B }
{ interface B
.... {
.... .....
} .....
How do you implement multiple inheritance in }
java ? class C implements A,B
Using interfaces java can support multiple inheritance {
} What is the use of final keyword in java ?
Can we reduce the visibility of the inherited or Final keyword in java is used to make any class or a
overridden method ? method or a field as unchangeable. We can't extend
Ans. No. final class, not override final method, can't change
Which of the following is tightly bound ? value of final variable.
Inheritance or Composition ?
Ans. Inheritance. Can we change the value of an interface field ?
No, we can't change the value of an interface field.
Does a class inherit the constructor of its super
class ? Because interface fields is by default final and static.
Ans. No They remain constant for whole execution of a
Where you use final keyword in java ? program.
Final keyword in java are used at; What is this keyword ?
• Final at method level this is reference variable that refers to the current
• Final at class level object.
• Final at variable level Why use this keyword ?
this keyword can be used to refer current class
What are final class, final method and final
instance variable and this keyword can also be used to
variable ?
• Final class: can not be extended. return the current class instance.
What are the uses of this keyword in constructor ?
• Final method: can not be overridden in the this can be passed as argument in the constructor call.
sub class. Can we call methods using this keyword ?
• Final class: can not change it’s value once it Yes we can use this keyword to call current class non
is initialized. static methods.
What is the main difference between abstract Uses of this keyword with constructor ?
method and final method? Used to invoke current class constructor.
Abstract methods must be overridden in sub class Difference Between this() and super() ?
where as final methods can not be overridden in sub Super keyword is always pointing to base class
class features and this keyword is always pointing to
When use final class in java ? current class features.
If a class needs some security and it should not this is a reference to the current object in which this
participate in inheritance in this situation we need to keyword is used whereas super is a reference used to
use final class. access members specific to the parent Class.
What will happen if we try to extend final class in this is primarily used for accessing member variables
java ? if local variables have same name, for constructor
Compiler get an error
chaining and for passing itself to some method
Can we declare interface as final ?
whereas super is primarily used to initialize base class
No, because interface must be implement in other
members within derived class constructor.
class.
What is the difference between this. (this dot) and
Can we declare constructor as final ?
this() (this off). ?
No, cunstructor can't be final.
this. can be used to differentiate variable of class and
What will happen if we try to override final
formal parameters of method or constructor.
methods in sub classes ?
Compile time error will come :Cannot override the this() can be used to call one constructor within the
final method from Super class, because you can't another constructor without creation of objects
override final method in sub class. multiple time for the same class.
Can we create object for final class? What is difference between super(), super(..), this()
Yes we can create object for final class. and this(..) ?
super() and super(..) are used for establishing the
Can we declare constructors as final?
No, constructors can not be final. communication between base class and derived class
constructor.
this() and this(...) are used for establishing the What is static keyword in java ?
communication between current class constructor. Static keyword in java are used for memory
What is super keyword ? management
It is used to access members of the base class. Why we use static keyword in java ?
Can we use both "this" and "super" in a Static keyword is mainly used for memory
constructor ? management.
No, because both this and super should be the first What is static variable in java
statement. Variables declared with static keyword is known as
What are usage of java super Keyword ? static variables.
• super is used to refer immediate parent class What is static variable in java? ?
instance variable. Variables declared with static keyword is known as
• super() is used to invoke immediate parent static variables. If we change any static variable value
class constructor. using a particular object then its value changed for all
• super is used to invoke immediate parent class objects means it is common to every object of that
method. class. This type of variable is class level.
When Need of super keyword ? What is static method in java ?
Whenever the derived class is inherits the base class Method which is preceded with static keyword is
features, there is a possibility that base class features know as static method. JVM will not call these static
are similar to derived class features and JVM gets an methods automatically you need to call these static
ambiguity. In order to differentiate between base class methods from main method or static block or variable
features and derived class features must be preceded initialization. These types of method called by using
by super keyword. class name itself no need to create object.
Difference Between this() and super() ? Note: Only Main method will b called by JVM
Super keyword is always pointing to base class automatically.
features and this keyword is always pointing to Example
current class features. static void show()
{
this is a reference to the current object in which this
......
keyword is used whereas super is a reference used to ......
access members specific to the parent Class. }
this is primarily used for accessing member variables What is static block in Java ?
if local variables have same name, for constructor Static blocks are the blocks which will have braces
chaining and for passing itself to some method and with static keyword and these block execute at the
whereas super is primarily used to initialize base class time of class loading.
members within derived class constructor. Example
What is difference between super(), super(..), this() static
{
and this(..) ?
......
super() and super(..) are used for establishing the
......
communication between base class and derived class }
constructor. What is the need of static block ?
this() and this(...) are used for establishing the Static blocks will be executed at the time of class
communication between current class constructor. loading. If you want to execute any logic before main
In a case where there are no instance variables method loading you should go with static block.
what does the default constructor initialize ? Why main method is static in java ?
Java expects the superclass ( Object Class ) To execute main method without creating object.
constructor to be called while creation of any object. .Can we overload static methods in java ?
So super constructor is called in case there are no Yes
instance variables to initialize. Can we override static methods in java ?
No
Can we write static public void main(String [] Is it necessary that each try block to be followed by
args) ? catch block ?
Yes, Order of modifiers can change. It should be followed by either catch or finally block.
Why use string handling in Java Explain throw, throws , try and catch in Java ?
The basic aim of String Handling concept is storing throw: It is used to re throw an exception.
the string data in the main memory (RAM), throws: It is used to declare that the method throws
manipulating the data of the String, retrieving the part the respective exceptions.
of the String etc. String Handling provides a lot of catch: It is used to catch the exception that has been
concepts that can be performed on a string such as thrown by the respective try block.
concatenation of string, comparison of string, find sub Difference between Error and Exception
string etc.What is StringTokenizer ? Error Exception
It is a pre defined class in java.util package can be 1 Can be handle. Can not be handle.
used to split the given string into tokens (parts) based Example: Example:
on delimiters (any special symbols or spaces). 2 NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException
What is Exception Handling ?
The process of converting system error messages into What is thread ?
Thread is a lightweight components and it is a flow of
user friendly error message is known as Exception
control. In other words a flow of control is known as
handling.
thread.
What is Exception ?
An exception is an event, which occurs during the What is multithreading ?
Multithreading in java is a process of executing
execution of a program, that disrupts the normal flow
multiple threads simultaneously.
of the program's Instructions.
Explaing State or Life cycle of thread.
Which is super class for any Exception class ?
State of a thread are classified into five types they are
Object class is super class for any Exception class.
• New State
Can any statement is possible between try and
catch block ? • Ready State
Each and every try block must be immediately • Running State
followed by catch block that is no intermediate • Waiting State
statements are allowed between try and catch block. • Halted or dead State
Can any try block contain another try block ? How to achieve multithreading in java ?
Yes, One try block can contains another try block that In java language multithreading can be achieve in two
is nested or inner try block can be possible. different ways.
Can finally block be used without catch ? • Using thread class
Yes but should follow "try" block then.
• Using Runnable interface
When IOException is thrown ?
IOException is thrown in following conditions which Difference between Process and Thread ?
Process is a program in execution whereas thread is a
is given below;
separate path of execution in a program.
• Try to transfer more data but less data are
In which state no memory is available for thread ?
present.
If the thread is in new or dead state no memory is
• Try to read data which is corrupted
available but sufficient memory is available if that is
• Try to write but file is read only. in ready or running or waiting state.
When ArithmeticException is thrown ? Difference between sleep() and suspend() ?
The ArithmeticException is thrown when integer is Sleep() can be used to convert running state to waiting
divided by zero or taking the remainder of a number state and automatically thread convert from waiting
by zero. It is never thrown in floating-point state to running state once the given time period is
operations. completed. Where as suspend() can be used to convert
running state thread to waiting state but it will never
return back to running state automatically. What is the purpose of the System class ?
What is a Deadlock ? System class provide access to system resources.
When two threads are waiting each other and can't Variable of the boolean type is automatically
precede the program is said to be deadlock. initialized as ?
Difference between Serialization and The default value of the boolean type is false.
Deserialization ? Difference between static vs. dynamic class loading
Serialization is the process of writing the state of an ?
object to a byte stream. Deserialization is the process static loading: Classes are statically loaded with Java
of restoring these objects. new operator.
What is Thread Synchronization ? dynamic class loading: Dynamic loading is a
Allowing only one thread at a time to utilized the technique for programmatically invoking the
same resource out of multiple threads is known as functions of a class loader at run time.
thread synchronization or thread safe. What do you mean by "Java is a statically typed
Difference between yield() and sleeping()? language" ?
When a task invokes yield(), it changes from running It means that the type of variables are checked at
state to runnable state. When a task invokes sleep(), it compile time in Java.The main advantage here is that
changes from running state to waiting/sleeping state. all kinds of checking can be done by the compiler and
What is a daemon thread ? hence will reduce bugs.
These are threads that normally run at a low priority What are different ways of object creation in
and provide a basic service to a program or programs Java ?
.
when activity on a machine is reduced. garbage
• Using new operator - new xyzClass()
collector thread is daemon thread.
• Using factory methods -
Why use Thread Synchronization ?
Whenever multiple threads are trying to use same xyzFactory.getInstance( )
resource than they may be chance to of getting wrong • Using newInstance( ) method
output, to overcome this problem thread • By cloning an already available object -
synchronization can be used. (xyzClass)obj1.clone( )
How to achieve Thread Synchronization in java ?
In java language thread synchronization can be What is an Enum type ?
achieve in two different ways. An enum type is a special data type that enables for a
• Synchronized block variable to be a set of predefined constants.
• Synchronized method What are Wrapper Classes ?
A wrapper class is any class which "wraps" or
How to achieve multiple inheritance in java ?
Using Interface concept you can achieve multiple "encapsulates" the functionality of another class or
inheritance in java. component.
Difference between suspend() and stop() ? What are Primitive Wrapper Classes ?
Suspend method is used to suspend thread which can A Wrapper Class that wraps or encapsulates the
be restarted by using resume() method. stop() is used primitive data type is called Primitive Wrapper Class..
to stop the thread, it cannot be restarted again. Why use Scanner class ?
For reading Data Stream from the input device.
What is a class loader ?
Part of JVM which is used to load classes and Difference between loadClass and Class.forName ?
loadClass only loads the class but doesn't initialize the
interfaces.
object whereas Class.forName initialize the object
What are the different class loaders used by
JVM ? after loading it.
Bootstrap , Extension and System are the class Should we override finalize method ?
loaders used by JVM. Finalize is used by Java for Garbage collection. It
Different types of memory used by JVM ? should not be done as we should leave the Garbage
Class , Heap , Stack , Register , Native Method Stack. Collection to Java itself.
Why Java don't use pointers ? class B type object or class B type reference variable
Pointers are vulnerable and slight carelessness in their can not refer to class A type object.
use may result in memory problems and hence Java What is the priority of Garbage Collector thread.
intrinsically manage their use. is it low or high.?
Do we need to import java.lang.package ? Garbage Collector thread is a low priority thread.
No, It is loaded by default by the JVM. Is an object garbage collected even after an
What is the difference between System.out exception is occurred in the program ?
,System.err and System.in ? Yes, Garbage collector ignores any exceptions
System.out and System.err both represent the monitor occurred in the program.
by default and hence can be used to send data or Is Map of Collection type ?
results to the monitor. But System.out is used to No, Map is not a Collection type. Even though Map is
display normal messages and results whereas included in the collection framework, it does not
System.err is used to display error messages and inherit from Collection interface.
System.in represents InputStream object, which by Can we define sub class first and super class later
default represents standard input device, i.e., in a java file ?
Yes, Order of sub class and super class does not
keyboard.
matter.
Is it possible to compile and run a Java program
without writing main( ) method ? Which package is always imported by default ?
Yes, it is possible by using a static block in the Java java.lang package is always imported by default.
program. Can a class implement two interfaces having same
method ?
Can we call the garbage collector explicitly ? Yes, a class can implement two interfaces having
We can call garbage collector of JVM to delete any
same method but that method should be implemented
unused variables and unreferenced objects from
only once ( or can be overloaded ) in the class.
memory using gc( ) method. This gc( ) method
Which one will be faster ?
appears in both Runtime and System classes of • for(int i = 0; i < 1000; i++) {}
java.lang package.
• for(int i = 1000; i > 0; i–) {}
Are true and false keywords in java ?
No, true and false are not keywords in java. They are for(int i = 1000; i > 0; i–) {} will be faster.
literals in java. You can not use them as identifiers in Can we declare interface methods as static ?
No, we can’t declare interface methods as static.
your program. They are reserved words in java.
Here we cover all topics related to oops concept in
Can we declare local inner class as private ?
No, local inner class can not be declared as private or java. Once again we discuss some oops concept in
protected or public. detail separately.
Is "abc" a primitive value ?
No, "abc" is not a primitive value. It is a string object.
Is an exception occurred in one thread causes
other threads to terminate.?
No, exception is thread wise. Only that thread will
terminate in which exception has occurred. Other
threads will continue to execute.
Can array size be negative.?
No, array size can not be negative. If you specify
array size as negative, there will be no compile time
error, but you will get NegativeArraySizeException at
run time.
If class A and class B are two sub classes of class C,
then can a reference variable of Class A type refer
to an object of class B type or Vice versa.?
No. Class A type reference variable can not refer to