Core java interview questions with answers
101. What are the three types of Thread priority ?
Ans: Thread have following three priority
- Thread.MIN_PRIORITY - minimum thread priority.
- Thread.MAX_PRIORITY - maximum thread priority.
- Thread.NORM_PRIORITY - default thread priority
102. What is the use of synchronizations ?
Ans: The
synchronized
keyword can be used for locking in program or utilize for lock and free the
resource for any thread/program.
103. Garbage collector thread belongs to which priority
?
Ans: Low-priority
Thread.
104. What is meant by time-slicing ?
Ans: Time- slice means which provided threads of equal priority and
enable to share a processor equally, even if the thread has not finished
executing while the quantum expires, the processor is taken away from that
thread and given to the next thread of equal priority, if another thread is
available.
105. What is the use of ‘this’ ?
Ans: Simple
this keyword
is refer to the current state of an object and also enable to call a constructor
to another constructor
106. How can you find the length and capacity of a
string buffer ?
Ans: String buffer class is belong to mutable class unlike string class
is a immutable. So string buffer is have length as well capacity too.
- int
capacity() method - used for
found current capacity of the String buffer.
- int length()
method- used for
found length( char count) of an string buffer.
// An example of stringbuffer( length and capacity)
package r4r.co.in;
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer x = new StringBuffer("StringBufferDemo");
System.out.println("bufferinput = " + x);
System.out.println("length = " + x.length());
System.out.println("capacity = " + x.capacity());
}
}
Result:
bufferinput = StringBufferDemo
length = 16
capacity = 32
107. How to compare two strings ?
Ans: By
equal() method.
108. What are the interfaces defined by
java.lang.Package?
Ans: Following interface defined in
java.lang.Package are
- Appendable
- An object to which char
sequences and values can be appended. The
Appendable interface must be implemented by any class whose
instances are intended to receive formatted output from a
Formatter. Appendables
are not necessarily safe for multithreaded access.
(Introduce since JDK- 1.5 ).
- CharSequence
-A CharSequence is a readable
sequence of
char values. This
interface provides uniform, read-only access to many different kinds of
char sequences. A
char value represents a character
in the Basic Multilingual Plane (BMP) or a surrogate.
(Introduce since JDK- 1.4 ).
- Cloneable
-A class implements the
Cloneable
interface to indicate to the
Object.clone() method
that it is legal for that method to make a field-for-field copy of instances
of that class. it is important that Cloneable doesn't contain
any clone()method.
(Introduce since JDK- 1.0 ).
- Comparable<T>
-This interface imposes a total ordering on the objects of each class
that implements it. This ordering is referred to as the class's natural
ordering, and the class's
compareTo()
method is referred to as its natural comparison method.
*T - the type of objects
that this object may be compared to
( Introduce since JDK- 1.2)
- Deprecated
-A program element annotated @Deprecated is one that programmers are
discouraged from using, typically because it is dangerous, or because a
better alternative exists. Compilers warn when a deprecated program element
is used or overridden in non-deprecated code.
(Introduce since JDK- 1.4 ).
- Iterable<T>
-Implementing this interface allows an object to be the target of the
"foreach" statement .
(Introduce since JDK- 1.5 ).
- Override
- Indicates that a method declaration is intended to override a
method declaration in a superclass. If a method is annotated with this
annotation type but does not override a superclass method, compilers are
required to generate an error message.
(Introduce since JDK- 1.5 ).
- Readable
- A Readable is a source of
characters. Characters from a Readable are made available to
callers of the read method via a
CharBuffer. (Introduce
since JDK- 1.5 ).
- Runnable
-The
Runnable interface
should be implemented by any class whose instances are intended to be
executed by a thread. The class must define a method of no arguments called
run. This interface is designed to
provide a common protocol for objects that wish to execute code while they
are active. (Introduce since JDK- 1.0 ).
- SuppressWarnings
- Indicates that the named compiler warnings should be suppressed in
the annotated element (and in all program elements contained in the
annotated element).
(Introduce since JDK- 1.5 ).
(** Following data taken form sun/java)
109. What is the purpose of run-time class and system
class?
Ans:
110. What is meant by Stream and Types of Stream ?
Ans: Generally, Streams are a way of
transferring and filtering information or use data in one form or
another, however it is as input, output, or both. The sources of input and
output can vary between a local file, a database, variables in memory, a socket
on the network, or another program. Streams may be in between byte and character
streams and various stream classes define into the
java.io package,
so stream are of two type-
- Input Stream
- Output Stream
111. What is the method used to clear the buffer ?
Ans: For Clear the buffer following method is call-
-
clear() -The position is set to zero, the limit is set to
the capacity, and the mark is discarded.
-
flip() - The limit is set to the current position and then
the position is set to zero.
rewind()- The position is set to zero and the mark is discarded.
112. What is meant by StreamTokenizer ?
Ans: The
StreamTokenizer class
takes an input stream and parses it into "tokens", allowing the tokens to be
read one at a time.
113. What is serialization and de-serialization ?
Ans: Serialization is the process of
transforming
a
data structure/object
into a sequence of bits stream so that it can be stored in a memory buffer or
file, or transmitted across a
network
while
in case of Deserialization
is the inverse process of reconstructing
an object from a byte stream to the same state in which the object was
previously serialized.
// Serialization code
FileOutputStream out = new FileOutputStream( “save.ser” );
ObjectOutputStream x = new ObjectOutputStream( out );
oos.writeObject( new Date() );
x.close();
//Deserialization code
FileInputStream in = new FileInputStream( “save.ser” );
ObjectInputStream x = new ObjectInputStream( in );
Date d = (Date) ois.readObject();
x.close();
114. What is meant by Applet ?
Ans: Applets are small applications
that are accessed on an Internet server, transported over the Internet,
automatically installed, and run as part of a Web document.
115. How to find the host from which the Applet has
originated ?
Ans: Following two method may be used-
public java.net.URL getDocumentBase();
public java.net.URL getCodeBase();
116. What is the life cycle of an Applet ?
Ans: Life cycle of an Applet totally dependent upon following four
method which is-
public void
init();
public void start();
public void stop();
public void
destroy();
// A very simpleDemo of an Applet life
package r4r.co.in;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class AppletDemo extends Applet {
StringBuffer Demo;
public void init() {
Demo = new StringBuffer();
addItem("initializing/java//java/. "); // initializing an applet
}
public void start() {
addItem("starting of an applet. "); //start an applet
}
public void stop() {
addItem("stopping an applet. "); //stop an applet
}
public void destroy() {
addItem("Finally unload."); //Free all the resource
}
private void addItem(String newWord) {
System.out.println(newWord);
Demo.append(newWord);
}
public void paint(Graphics g) {
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); // Rectangular area
g.setColor(Color.BLUE); // Color in applet
g.drawString(Demo.toString(), 10, 15); //Display the string inside the rectangle.
}
}
Result:
initializing/java//java/.
starting of an applet.
//Remaining two method call on closing the applet.
stopping an applet.
Finally unload.
117. How do you load an HTML page from an Applet ?
Ans: For such operation used small code which written in HTML file
<applet code="AppletDemo" width=300 height=100>
</applet>
118. What is meant by AppletStub Interface ?
Ans: The
AppletStub interface is a way to get
information from the run-time browser environment. The
Applet class provides following methods-
- public abstract boolean
isActive()-The
isActive() method returns the current state of the
applet.
- public abstract
URL getDocumentBase()-
The
getDocumentBase() method returns
the complete URL of the HTML file that loaded the applet.
- public abstract
URL getCodeBase()-
The
getCodeBase() method returns the
complete URL of the .class file that contains the
applet.
- public abstract
String getParameter(String
name)-
The
getParameter() method allows you to get parameters from
<PARAM> tags within the
<APPLET> tag of the HTML file that loaded the applet.
- public abstract
AppletContext getAppletContext()-
The
getAppletContext() method returns
the current AppletContext of the applet.The
getAppletContext() method returns the current
AppletContext of the applet.
- public abstract void
appletResize(int
width, int
height)-
The
appletResize() method is called by the
resize method of the Applet class.
(** Following data taken from JAVA AWT
Reference( Chapter 14))
119. What is meant by getCodeBase and getDocumentBase
method ?(Not sure)
Ans: The getCodebase()
method is used to establish a path to other files/folders that are in the same
location as the class being run.
URL getCodeBase() - Gets the base URL.
URL getDocumentBase() - Gets the URL of the document
in which the applet is embedded.
120. How can you call an applet from a HTML file?
Ans: Following example is used
<HTML>
<HEAD>
<TITLE>AppletDemo example- call applet parameter from HTML file </TITLE>
</HEAD>
<BODY>
<APPLET CODE="AppletDemo.class" WIDTH="500" HEIGHT="100">
</APPLET>
</BODY>
</HTML>
121. What is meant by Applet Flickering ?
Ans: When an applet is executing some graphics using a thread, some
color desolation will be happening, this is called as flickering.
122. What is the use of parameter tag ?
Ans: The <param> tag is used to define parameters or variables for an
object or applet element.
123. What is audio clip Interface and what are all the
methods in it ?
Ans:Three methods define the
AudioClip
interface-
void
play()- Starts playing this audio clip from the beginning.
void
loop()-
Starts playing this audio clip in a continuously
loop
void
stop()-
Stops playing this audio clip.
124. What is the difference between getAppletInfo and
getParameterInfo ?
Ans:
getAppletInfo()method is used for returns information about this
applet in the String form.
(public
String getAppletInfo())
getParameterInfo() method is used for returns
information about the parameters that are understood by this applet in the array
of Strings.
( public
String[][] getParameterInfo())
125. How to communicate between applet and an applet ?
Ans:JavaScript functions enable communication between two applets by
receiving messages from one applet and invoking methods of other applets.
126. What is meant by event handling ?
Ans:
In Java, events represent
the activity that happen between the user and the application. Here, Java’s
Abstract Windowing Toolkit (AWT) enable to communicates these actions to the
programs using events. All the event belongs to
java.awt.*;
package.
//Example for login page display mouse
event(AxtionListener)
package r4r.co.in;
import java.awt.*;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class FrameClass extends javax.swing.JFrame implements ActionListener {
JButton Bu32;
JTextField tx1, tx2;
JLabel La11, La21;
FrameClass() {
JFrame fr = new JFrame("Login form in Swing");
JPanel panel = new JPanel(new GridLayout(3, 2));
fr.setVisible(true);
fr.setSize(400, 200);
La11 = new JLabel("Username");
tx1 = new JTextField(15);
La21 = new JLabel("Password");
tx2 = new JTextField(10);
Bu32 = new JButton("Sign In");
panel.add(La11);
panel.add(tx1);
panel.add(La21);
panel.add(tx2);
panel.add(Bu32);
Bu32.addActionListener(this);
panel.setBackground(Color.LIGHT_GRAY);
fr.getContentPane().add(panel);
fr.show();
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String str1 = tx1.getText();
String str2 = tx2.getText();
try {
if (str1.equals("r4r@techsoft") && str2.equals("r4r")) {
System.out.print("Welcome to R4R");
} else {
System.out.println("Please enter valid username and password");
}
} catch (Exception e) {
System.out.print(e);
}
}
}
public class NewClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
}
}
Result: Display on your platform like
Welcome to R4R
Please enter valid username and password
127. What are all the listeners in java and explain ?
Ans: In java programming a listening is an object that is used to
handle events. Main types of listener are-
- ActionListener
- FocusListener
- WindowListener
- MouseListener
- void
mouseClicked(MouseEvent
event)
void mousePressed(MouseEvent
event)
void mouseReleased(MouseEvent
event)
void
mouseEntered(MouseEvent
event)
void mouseExited(MouseEvent
event)
- KeyListener
- void
keyPressed(KeyEvent
event)
void keyReleased(KeyEvent
event)
void keyTyped(KeyEvent
event)
- MouseMotionListener-
void mouseDragged(MouseEvent
event)
void mouseMoved(MouseEvent
event)
128. What is meant by an adapter class ?
Ans: An adapter class
which provides an empty implementation of all methods in an event listener
interface ,e.g. consider a
MouseMotionAdapter
class has two method like
mouseDragged( )
and
mouseMoved( )
both method is empty but implement
MouseMotionListener
interface.
129. What are the types of mouse event listeners ?
Ans:
Main type of mouse event are-
- void
mouseClicked(MouseEvent
event)
- void
mousePressed(MouseEvent
event)
- void
mouseReleased(MouseEvent
event)
- void
mouseEntered(MouseEvent
event)
- void
mouseExited(MouseEvent
event)
130. What are the types of methods in mouse listeners ?
131. What is the difference between panel and frame ?
Ans: JFrame: A movable, resizable windows( as programmer
required) with title bar and close button, and import three main package
from Swing is-
javax.swing.*;
java.awt.*;
java.event.*;
JPanel: Panel is define in internal region of JFrame, for regroup
component while the panel is sub-level container.
//Example for Add Panel(with textfield,button)to Frame
package r4r.co.in;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class FrameClass extends JFrame {
JButton Bu;
JTextField tx;
FrameClass() {
JFrame fr = new JFrame("Frame Bar Ready");
JPanel panel = new JPanel();
fr.setVisible(true);
fr.setSize(350, 250);
tx = new JTextField(10);
panel.add(tx);
Bu = new JButton("click");
panel.add(Bu);
panel.setBackground(Color.LIGHT_GRAY);
fr.getContentPane().add(panel);
fr.show();
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
}
}
public class NewClass {
public static void main(String[] args) {
JFrame frame = new FrameClass();
}
}
132. What is the default layout of the panel and frame
?
Ans: By default, a panel uses a
FlowLayout() to lay out its
components while a frame uses a BorderLayout() to lay out its
Border.
134. What is the difference between a scroll bar and a
scroll panel?
Ans: A Scrollbar is a Component while Scrollpanel is a Container and
handles its own events like own scrolling.
137. What are the different types of Layouts ?
Ans: Following layout is-
-
FlowLayout - left to right, top to bottom.
-
BoxLayout and Boxes - horizontal ,vertical sequence of
components.
-
BorderLayout - north, east, south, west, and center areas.
-
GridBagLayout - unequal sized grid.
-
GridLayout - equal sized grid elements, another layout (which
generally not in used) is
SpringLayout.
138. What is meant by CardLayout ?
Ans: A
CardLayout object is a layout manager for a
container, or treat each component as a card. Container act as a stack of card
and visible a card at a time.
140. What is the difference between menu item and
checkbox menu item.
141. What is meant by vector class, dictionary class ,
hash table class, and property class ?
Ans: Vectors (java.util.Vector ) are commonly used instead
of arrays, because they expand automatically when new data is added to them.
Dictionary( java.util.Dictionary ) class is the abstract
parent of Hashtable, which maps keys to values. Any object can be used as a key
and/or value.
This class implements a
hashtable( java.util.Hashtable), which
maps keys to values. Any non-null object can be used as a key or as
a value. An instance of Hashtable has two parameters that
affect its performance: initial capacity and load factor.
Property( java.util.Properties ) class represents a
persistent set of properties. The Properties can be saved to a
stream or loaded from a stream. Each key and its corresponding value in the
property list is a string.
142. Which class has no duplicate elements ?
Ans: The java.util.Set interface and
related implementations don't support duplicate elements.
143. What is resource bundle ?
Ans:Resource bundles contain locale-specific objects. Resource bundles
are essentially text files, most common example is list of strings, because each
string has a “key” to identify it, which is the same in all the different
resource bundles.
Resource bundles can allows you to write programs that can:
- easily localized, or translated, into different languages .
- handle multiple locales at once
- be easily modified later to support even more locales
144. What is an enumeration in java ?
Ans:An object that implements the Enumeration interface generates a
series of elements, one at a time. Contain two main method-
hasMoreElements()- Tests if this enumeration contains more
elements returns boolean.
nextElement()- Returns the next element of this enumeration if
this enumeration object has at least one more element to provide return
Object.
145. What is meant by Swing ?
Ans: Swing is the primary
Java
GUI
widget
toolkit( Design by
Sun Microsystems, Inc.)
utilize for providing a
graphical user interface (GUI) for Java
programs. Since Swing provides a native
look and feel, also support a
pluggable look and feel that allows
applications to have a look and feel unrelated to the underlying platform. Major
disadvantage of Swing is it provide emulates the look and feel of several
platforms mean it's depend platform.
147. What is the difference between an applet and a Japplet
|
Applet |
JApplet |
1. Applet is a class of javax.awt.*
package.
2. Do to support AWT it is heavy weight process.
3. Java Applet is pure java application platform independent.
4. To
add component in Applet, add() method
is call
5. Since Applet is AWT component less feature than JApplet |
1. Japplet is a class of javax.swing.* package.
2. Do to support Swing class it is light weight process.
3.Swing/JFC components, identified by the letter "J" (JPanel,
JFrame, etc.)
4. To
add component in Japplet, add() of
content pane is call
5. Swing components provide better look and
feel. |
148. What are all the components used in Swing ?
Ans:Main
Swing Component are-
- Buttons and Labels.
- Checkboxes and Radio Buttons.
- Lists and Combo Boxes.
- Borders.
- Menus.
- The
PopupMenu Class.
- The
JScrollPane Class.
- The
JSplitPane Class.
- The
JTabbedPane Class.
- Scrollbars and Sliders.
- Dialogs.
149. What is meant by tab pans ?
Ans: Tab Panes provide the ability to switch between various panels.
150. What is the use of JTree ?
Ans: JTree is a method to display hierarchical data
although it doesn't contain data while provide a simple view of data(
JTree displays its data vertically). Each row displayed by the tree
contains exactly one item of data, which is called a node.Each tree has
a root node from which all nodes descend.
Question: Make a login Form in Swing.
Ans:
//Example for login page.
package r4r.co.in;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class FrameClass extends javax.swing.JFrame implements ActionListener {
JButton Bu1;
JTextField tx1, tx2;
JLabel La1, La2;
FrameClass() {
JFrame fr = new JFrame("Login form in Swing");
JPanel panel = new JPanel();
fr.setVisible(true);
fr.setSize(400, 200);
panel.setLayout(null);
La1 = new JLabel("Username");
tx1 = new JTextField(15);
La2 = new JLabel("Password");
tx2 = new JTextField(10);
Bu1 = new JButton("Sign In");
La1.setBounds(30, 10, 120, 30);
panel.add(La1);
tx1.setBounds(130, 10, 180, 30);
panel.add(tx1);
La2.setBounds(30, 70, 120, 40);
panel.add(La2);
tx2.setBounds(130, 70, 180, 30);
panel.add(tx2);
Bu1.setBounds(130, 120, 80, 30);
panel.add(Bu1);
Bu1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Bu1.addActionListener(this);
panel.setBackground(Color.CYAN);
fr.getContentPane().add(panel);
fr.show();
fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String str1 = tx1.getText();
String str2 = tx2.getText();
try {
if (str1.equals("r4r@techsoft") && str2.equals("r4r")) {
NewPage page = new NewPage();
page.setVisible(true);
JLabel label = new JLabel("Welcome to R4R TECH SOFT");
page.getContentPane().add(label);
System.out.println("Welcome to R4R TECH SOFT"); //Its optional
} else {
NewPage page = new NewPage();
page.setVisible(true);
JLabel label = new JLabel("Please enter valid username and password");
page.getContentPane().add(label);
System.out.println("Please enter valid username and password"); //Its optional
}
} catch (Exception e) {
System.out.print(e);
}
}
}
public class LOGINFORM {
public static void main(String[] args) {
JFrame frame = new FrameClass();
}
}
//Save this page as LOGINFORM.java
//NewPage open when condition is checked.
package r4r.co.in;
class NewPage extends javax.swing.JFrame {
NewPage() {
setTitle("Second page belongs to Login form in Swing");
setSize(300, 100);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
}
//save this as NewPage.java
Result: Display on your platform(optional
call)
Welcome to R4R TECH SOFT

Please enter valid username and password

Core java interview questions with answers