Java Questions
Java Questions
An object is an entity with certain attributes or qualities and behaviors, for a simple example, a
'Laptop' is an object which has certain attributes like weight,color,screen size,manufacturer etc.It
has various behaviors or activities to do or act upon, as play games,browse Internet,write/check
emails , watch movies ,listen music etc.
is a methodology to analyze,design and develop application using objects and their relations and
message based communication to each other.Everything in OOAD is visualized in terms of
objects and classes.OOAD introduced a paradigm shift from thinking and programming
procedurally to objects oriented programming.This approach helps in designing complex real time
systems with ease.The features like Data Abstraction and Encapsulation, Inheritance and
Polymorphism form fundamentals of object oriented programming.
Advantages:
• Enhanced Reusability
• Modular approach towards problem solving which will be
• Better Maintainability
Better Performance if system is designed cautiously using OOAD concepts
Data Abstraction is extraction of essential information for a particular purpose and ingnoring the
remainder of the information,e.g. a car is consisted of an engine,air filters,a carburetor,a gear
box,a steering,a fuel tank,tyres etc.A driver of a car need not to be bothered about several finer
points of the car,he/she should know what it requires to drive a car.Take another user, a car
mechanic, he will require different set of information in order to repair the car.
An abstraction denotes the essential characteristics of an object that distinguish it from all other
kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective
of the viewer." -- [Booch, 1991]
While information hiding is not sharing the details of an object with outside world.Here are few
standard definitions of Information Hiding which will elaborate more on this concept:
"The technique of encapsulating software design decisions in modules in such a way that the
module's interfaces reveal little as possible about the module's inner workings; thus each module
is a 'black box' to the other modules in the system." -- [IEEE, 1983]
Inheritance is a mechanism by which a specific object acquires attributes and behaviors of more
general objects.In OOP terminology ,Inheritance is the mechanism which allows a Class 'A' to
inherit properties of Class 'B' and we say 'A inherits from B' or in other words B is a
'Superclass'/'Parent class' while A is a 'Subclass'/'Child class'. A typical example of inheritance is
a family tree which consists of son,father,grandfather,great grandfather and so on.The different
types of Inheritance are:
1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
In single inheritance, a class inherits implementation from only one super class. For example, if
class B inherits from class A, class B will acquire all the members declared in class A.
B------>A(Parent)
In multilevel inheritance, a class inherits from a derived class (or subclass). For example, if class
C inherits from class B, and class B inherits from class A, class C will acquire all the members
declared in class B as well as all the members declared in class A.
C------->B------>A(Parent)
In hierarchical inheritance, many sub classes inherit from a single super class. For example, if
classes B, C, and D inherit from class A, classes B, C, and D will acquire all the members
declared in class A.
B------>A(Parent)C------>A(Parent)D------>A(Parent)
In multiple inheritance, a class inherits from several super classes. For example, if class C
inherits from both class A and class B, class C will acquire all the members declared in class A as
well as all the members declared in class B. Multiple inheritance is not directly supported by Java
but through Interfaces one can.C------>A(Parent)C------>B(Parent)
A hybrid inheritance is a combination of any two of the above discussed inheritance types
All objects in Java are inherited from same base class called 'Object'.In Java all objects have
common interface to implement and it makes implementaion of Garbage collector lot easier in
Java.The necessary implementaion is provided in base class , and the garbage collector can then
send the necessary messages to every objectc in the system.Without singly rooted hierarchy,it
would have been difficult to implement garbage collection feature.It enables lot of ease to
programmers not to be bothered about memory management while development.It greatly
simplifies argument passing amongst object too on the heap. As Java started from scratch and
has no backward compatibility issues with any existing language, it was a logical choice to use
the singly-rooted hierarchy in common with most other object-oriented programming languages.
Java does not support multiple inheritance atleast not the way it does in case of C++.In
designer’s view Multiple Inheritance poses many problems and confusions than it solves.e.g.
famous Diamond problem The diamond problem is an ambiguity that can occur when a class
multiply inherits from two classes that both descend from a common super class. In such
scenarios assuming if Java implements multiple inheritance then it would be difficult to know
which method is to be called by an inheriting class object of two of the super classes. In Java,
interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java
allows multiple inheritance of interface but not of implementation. Implementation, which includes
instance variables and method implementations, is always singly inherited. As a result, confusion
will never arise in Java over which inherited instance variable or method implementation to use.
Java takes inspirations from C and C++.The native datatypes like 'char','int','float','double' are
straight pick from C, which is not an Object Oriented Language.Resonably enough, Java is not a
100% pure Object Oriented Language.
The assignment of types to variables and expressions at compilation time is known as 'Early
Binding',it is also called 'static binding' and 'static typing'.\
When an object is sent a message then it does not know itself what type it is, the runtime
environment will decide about function calling over an object. This feature of connecting an object
with its associated message at runtime is known as Polymorphism or Late binding or Dynamic
binding.
1. Pointers are supported in C++ while not in Java. The memory management is done
automatically with help of part of JVM called Garbage Collector.
2. Multiple inheritance is not supported in Java but supported in C++.
3. There are no structures and unions in Java.
4. There is no scope resolution operator in Java (::).
5. There are no destructors in Java like C++.
6. There is no virtual keyword in Java because all non-static method use dynamic
binding.
Each time a Java Application is executed then an instance of JVM ,responsible for its running,is
created.A JVM instance is described in terms of subsystems, memory areas, data types, and
instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :
Each JVM has a class loader subsystem which loads classes and interfaces with fully qualified
names.Each JVM has an execution engine too , which executes all instructions contained by
methods of a loaded class.While executing a Java program,a JVM requires memory for storing
bytecodes,objects ,local variables,method arguments,return values,intermediate computational
results and JVM does that memory management on several runtime data areas.The specification
of runtime data areas is quite abstract.This abstract nature of JVM specification helps different
designers to provide implementation on wide variety of OS and as per choice of the
designers.Some implementations may have a lot of memory in which to work, others may have
very little. Some implementations may be able to take advantage of virtual memory, others may
not.
Each instance of the Java virtual machine has one method area and one heap. These areas are
shared by all threads running inside the virtual machine. When the virtual machine loads a class
file, it parses information about a type from the binary data contained in the class file. It places
this type information into the method area. As the program runs, the virtual machine places all
objects the program instantiates onto the heap.
When a new thread is created, it gets its own pc register (program counter) and Java stack. If the
thread is executing a Java method (not a native method), the value of the pc register indicates the
next instruction to execute. A thread's Java stack stores the state of Java (not native) method
which includes its local variables, the parameters with which it was invoked, its return value (if
any), and intermediate calculations. The state of native method invocations is stored in an
implementation-dependent way in native method stacks, in registers or other implementation-
dependent memory areas.
The Java stack is composed of stack frames (or frames). A stack frame contains the state of one
Java method invocation. When a thread invokes a method, the Java virtual machine pushes a
new frame onto that thread's Java stack. When the method completes, the virtual machine pops
and discards the frame for that method.
In JVM ,the instruction set uses the Java stack for storage of intermediate data values.The stack-
based architecture of the JVM's instruction set optimizes code done by just-in-time and dynamic
compilers.
The Class loader is a subsystem of a JVM which is responsible,predominantly for loading classes
and interfaces in the system.Apart from this,a class loader is responsible for the following
activities:
-Allocating memory for class variables and initializing them to default values.Static fields for a
class are created and these are set to standard default values but they are not explicitly
initialized.The method tables are constructed for the class.
-Resolving symbolic references from type to direct references The class loaders can be of two
types: a bootstrap or primordial class loader and user defined class loaderEach JVM has a
bootstrap class loader which loads trusted classes , including classes from Java API.JVM specs
do not tell how to locate these classes and is left to implementation designers.
A Java application with user defined class loader objects can customize class loading.These load
untrustworthy classes and not an intrinsic part of JVM.They are written in Java,converted to class
files and loaded into the JVM and installed like any other objects.
The heap is the part of memory of JVM where all objects reside.
The stack is consisted of stack frames.When a thread invokes a method,the JVM pushes a new
frame onto that thread's Java stack.Each stack frame is consisted of operand stack and the local
variable array.All arguments,local variables,intermediate computations and return values if any
are kept in these stack corresponding to the method invoked.The stack frame on the top of the
stack is called the active stack frame,which is the current place of execution.When the method
completes, the virtual machine pops and discards the frame for that method.
When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance
invoke main() method of Java application.The main() method of an application serves as the
starting point for that application's initial thread. The initial thread can in turn fire off other threads.
This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a
stack frame is pushed onto the stack,this then becomes the active tack frame.The program
counter in the new Java stack frame will point to the beginning of the method.
If there are more method invocations within main() method then this process of pushing new
stack frame onto the stack for each method call is repeated as and when they are invoked.When
a method returns, the active frame is popped from the stack and the one below becomes the
active stack frame.The PC is set to the instruction after the method call and the method
continues.
There is only one heap corresponding to an instance of JVM and all objects created are stored
here.This heap is shared by all threads created in an application.
Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A
daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that
performs garbage collection. The application, however, can mark any threads it creates as
daemon threads. The initial thread of an application--the one that begins at main()--is a non-
daemon thread.
A Java application continues to execute (the virtual machine instance continues to live) as long as
any non-daemon threads are still running. When all non-daemon threads of a Java application
terminate, the virtual machine instance will exit. If permitted by the security manager, the
application can also cause its own demise by invoking the exit() method of class Runtime or
System.
When main() returns,it terminates the application's only non-daemon thread, which causes the
virtual machine instance to exit.
A Magic Number of a class file is a unique identifier for tools to quickly differentiate class files
from non class files.The first four bytes of each Java class file has the magic value as
0xCAFEBABE
If your program is I/O bound or running in native methods, do these activities engage JVM?
The answer is 'No'.If the program is I/O bound or running in native methods, then the VM is not
involved in the consumption of CPU time. The VM technology will engage CPU for running
bytecodes. Typical examples of time spent not running bytecode are graphical operations that
make heavy use of native methods, and I/O operations such as reading and writing data to
network sockets or database files.
An interpreter produces a result from a program, while a compiler produces a program written in
assembly language and in case of Java from bytecodes.The scripting languages like
JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting
language will directly be executed with interpreter installed on that computer,if it is absent then
this program will not execute.While in case of compiled code,an assembler or a virtual machine in
case of Java is required to convert assembly level code or bytecodes into machine level
instructions/commands.Generally, interpreted programs are slower than compiled programs, but
are easier to debug and revise.
GUI intensive Java application mostly run underlying OS specific native libraries which is time
and more CPU cycles consuming.
The virtual machine is responsible for byte code execution, storage allocation, thread
synchronization, etc. Running with the virtual machine are native code libraries that handle input
and output through the operating system, especially graphics operations through the window
system. Programs that spend significant portions of their time in those native code libraries will
not see their performance on HotSpot improved as much as programs that spend most of their
time executing byte codes
A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any
computer.A JRE contains a Java Virtual Machine(JVM),all standard,core java classes and
runtime libraries. It does not contain any development tools such as compiler, debugger, etc.
JDK(Java Development Kit) is a whole package required to Java Development which essentially
contains JRE+JVM,and tools required to compile and debug,execute Java applications.
The lexical meaning of word transient is 'existing for a short duration',in Java,a transient variable
is one which one would not like to be saved during seralization.This is mostly the case when a
variable is sensitive enough that it should not be saved during serialization, such as a
password.Even when such variable is private in the object,once it is serialized it is possible to
read it inside a file or over a network.The keyword 'transient' is solution for such variables that are
not required to be serialized.
What is the difference between the '&' operator and the '&&' operator?
If you have static block, constructor and main method in Java file then what will be the sequence
of method calls?
Whenever a java file is executed it is done by java command given as below: java Usage: java [-
options] class [args...]
(to execute a class)
or java -jar [-options] jarfile [args...]
(to execute a jar file)
when some arguments are also passed with execution command then these arguments are
called command line arguments as they are taken as an array of String as a parameter in main
method.
Whenever you say something is static that means data or method is not associated with an object
instance of that class.They are allocated when a class is loaded,during compile time. Only a
single copy of that will be created for that class. So even if you have never created an object of a
class you an always access static data and method of that class. If you have class by name
'Vehicle' and you have a static method 'drive()' then it can simply be invoked by ' Vehicle.drive()',
no need of object cretaion in this scenario.A static method cannot access non static data and can
invoke other static methods.All static methods are automatically final. It is redundant to make
them final.
An abstract class is one which cannot be instantiated but a static method defined in abstract class
can be invoked without creating an instance.So there is no mechanism to ensure call of an
abstract static method.
Is 'sizeof' a keyword?
No, 'sizeof' is an operator used in C and C++ to determine the bytes of a data item, but it is not
used in Java as all data types are standard sized in all machines as per specifications of the
language.
A JVM is free to store data any way it pleases internally, big or little endian, with any amount of
padding or overhead, though primitives must behave as if they had the official sizes.In JDK 1.5+
you can usejava.lang.instrument.Instrumentation.getObjectSize() to get the object size.
On JavaWorld, I have found an interesting article
The table shown in image below is organised from higher precedence to low, when you traverse
from top to the bottom of the table.
By value
What is the difference between class variable, member variable and automatic(local) variable?
The class variable is a static variable and it does not belong to any instance of class but shared
across all the instances.
The member variable belongs to a particular instance of class and can be called from any method
of the class.
The automatic or local variable is created on a method entry and valid within method scope and
they have to be initialized explicitly.
The static variables are initialized at class load time during compilation and non static variables
are initialized just before the constructor is called.
No
All variables in Java are introduced/declared with some basic datatypes with some basic values,
e.g. every decimal value by default is adouble.The names of variables must avoid reserved Java
keywords.The local variables are explicitly initialized.
What are Java Modifiers?
'final' modifier can be applied to classes, methods and variables and the features cannot be
changed. final class cannot be subclassed, methods cannot be overridden and final variables are
constants.
No the reference cannot be changed, but the data in that object can be changed.
No,an abstract class cannot be instantiated i.e you cannot create a new object of this class.
When does the compiler insist that the class must be abstract?
They can be applied to variables, methods and even a block of code, static methods and
variables are not associated with any instance of class.They are loaded at the class compile time.
What is static initializer code?
A class can have a block of initializer code that is simply surrounded by curly braces and labeled
as static e.g.
public class Demo{
static int =10;
static{
System.out.println("Hello world');
}
}
And this code is executed exactly once at the time of class load.
Can an anonymous class implement an interface and extend a class at the same time?
No,an anonymous class can either implement an interface or extend a class at a particular time
but not both at the same time.
No,when features are friendly or protected they can be accessed from all the classes in that
package but not from classes in another package.
When one wants to complete the iteration of a loop prematurely then 'continue' statement is used.
While the 'break' statement is used to exit the entire loop whenever encountered.
As per the design decision Java does not support pointers explicitly.This greatly reduces the
burden of dynamic memory management while coding from programmers.Though programmers
dynamically allocate memory while coding but they need not worry about deallocating this
memory.The automatic garbage collection feature of Java collects dangling references of objects
though it has a trade off on performance as programmer managed memory management will be
efficient as compared to JVM driven automatic garbage collection.
What can prevent the execution of the code in finally block?
-Use of System.exit()
-The death of thread
-Turning off the power to CPU
-An exception arising in the finally block itself
An abstract class allows its subclasses to override the methods defined in it. It is never
instantiated and a class can inherit from a single class, as Java doesn't support for Multiple
Inheritance. It may contain both abstract and non-abstract methods.
An interface has public, abstract methods and may have public, static and final variables (read
only). It introduces multiple inheritance by a class implementing several interfaces.
If you use super() or this() in a constructor where should it appear in the constructor?
What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected,private, static, final, or abstract.
What is a thread?
A thread is most fundamental unit of a computer program which is under execution independent
of other parts.A thread and a task are similar and often confused.An operating system executes a
program by allocating it certain resources like memory,CPU cycles and when there are many a
programs doing several things corresponding to several users requests.In such a scenario each
program is viewed as a 'task' by OS for which it identifies an allocate resources. An OS treats
each application e.g. Word Processor,spreadsheet,email client etc as a separate task , if a certain
program initiates some parallel activity e.g. doing some IO operations,printing then a 'thread' will
be created fro doing this job.
A thread is part of a process; a process may contain several different threads. Two threads of the
same process share a good deal of state and are not protected against one another, whereas two
different processes share no state and are protected against one another. Two threads of the
same process have different values of the program counter; different stacks (local variables); and
different registers.The program counter, stack pointer, and registers are therefore saved in the
thread table. Two threads share open files and memory allocation; therefore, file information and
memory information (e.g. base/limit register or page table) is stored in the process table.
What are two ways of creating threads in Java and why so?
A Java object can be locked for an exclusive use of a thread by making it available via a
'synchronized' block or method.Only a particular thread at given time which will be possessing the
lock on the object will be able to do execution of code available in synchronized block or method,
once this thread with lock is through with its executions then it releases the lock on the object and
it is made available to the next thread in wait state.
These methods are used for thread intercommunication and usually called within synchronised
block or methods.A thread with lock on the object when calls wait() then it goes into wait state till
some other thread with lock on this object invokes notify() method or thenotifyAll() method.
A ''daemon'' thread is one that is supposed to provide a general service in the background as
long as the program is running, but is not part of the essence of the program. Thus, when all of
the non
daemon threads complete the program is terminated. Conversely, if there are any non-daemon
threads still running the program doesn' t terminate.
Serialization is a process of converting an object into byte stream which can be stored in
persistent storage area like file system or database and can occur over a network.This persisted
object can be converted back,called a process of deserialization, to restore original object. A
java.io.Serailizable interface provides syntactical approach to do serialization.This interface does
not contain any method,also known as marker interface.
Object serialization is necessary for:
-Java RMI, while sending messages to a remote object,it is necessary to transport arguments to
remote object and return values.
-Java Beans, state information of object is stored and later recovered when needed.
A memory leak occurs when all references (pointers) to a piece of allocated memory are
overwritten, cleared, or pass out of scope. The result is that the program simply "forgets" about
that particular piece of memory.Unfortunately , the operating environment (usually an OS) is not
aware of the application's amnesia. That memory is treated by the outside world as though it still
belongs to the application. The memory is therefore completely unavailable;it has "leaked". (In the
worst case, the memory can become unavailable to all applications in the system, even if the
application that created the leak is terminated. The memory can only be reclaimed by rebooting
the system.)
An applet runs in client side web browser. A class extending java.awt.Applet class which has
methods like init(), start(), stop(), destroy(),paint() overridden.An applet has restriction of
accessing client side resources like network connections, it cannot open socket connections and
cannot write to client side files i.e. hard disk.
An application runs standalone with a support of virtual machine. An application does not have
nay restrictions as Applets have over network and file related activities.They are free to open
sockets over a network read and write to a file.
Explain Lifecycle of the Applet and what is the order of method invocation in an applet?
-init():An applet can initialize itself and does whatever initializations are required to do for an
applet.
-start(): This method is automatically called when applet is initialized.When a user comes back to
a page with an applet this method is invoked then too.
-stop(): This method is called when user moves away from the webpage containing applet
-destroy:It is responsible for clean up and is called when browser is shut down normally.
An applet can be initialized and destroyed only once in its lifetime but it can be started and
stopped several times.
What is a Layout Manager and what are its different types and their advantages?
In Java,a GUI component does not decide about its geometry(location and size) on its own.A
layout manager is an object which is responsible for managing or arranging the size and location
of a GUI component.In AWT there are following layout managers which are supported:
-Flow
-Border
-GridBag
-Card
-GridBag
These layout managers organizes components consistently across all windowing platforms.
Irrespective of underlying windowing OS,layouts behave in a regular fashion and show GUI
components.A layout manager also represents an instance of a class which implements
LayoutManager interface.The layout manager is set by setLayout(LayoutManager
layoutManager) method.
Explain StreamTokenizer?
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens
to be read one at a time. The parsing process is controlled by a table and a number of flags that
can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted
strings, and various comment styles.
Each byte read from the input stream is regarded as a character in the range '\u0000' through
'\u00FF'. The character value is used to look up five possible attributes of the character: white
space, alphabetic, numeric, string quote, and comment character. Each character can have zero
or more of these attributes.