Java Sample Questions: Core Java Sample Questions
Java Sample Questions: Core Java Sample Questions
com
1. How could Java classes direct program messages to the system console, but error
messages, say to a file?
Answer: The class System has a variable out that represents the standard output, and
the variable err that represents the standard error device.By default, they both point at
the system console.This how the standard output could be re-directed:
Answer: An abstract class may contain code in method bodies, which is not allowed
in an interface.With abstract classes, you have to inherit your class from it and Java
does not allow multiple inheritance.On the other hand, you can implement multiple
interfaces in your class.
Answer: Synchronized blocks place locks for shorter periods than synchronized
methods.
Answer: This keyword indicates that the value of this member variable does not have
to be serialized with the object.When the class will be de-serialized, this variable will
be initialized with a default value of its data type (i.e.zero for integers).
Answer: You can't force GC, but could request it by calling System.gc().JVM does
not guarantee that GC will be started immediately.
Answer: If you assign a superclass object to a variable of a subclass's data type, you
need to do explicit casting.For example: Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is
performed automatically.
http://sparshme5.googlepages.com
1
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: The code sleep(1000); puts thread aside for exactly one second.The code
wait(1000), causes a wait of up to one second.A thread could stop waiting earlier if it
receives the notify() or notifyAll() call.The method wait() is defined in the class
Object and the method sleep() is defined in the class Thread.
8. Can you write a Java class that could be used both as an applet as well as an
application?
Answer: Constructors must have the same name as the class and can not return a
value.They are only called once while regular methods could be called many times.
10. Can you call one constructor from another if a class has multiple constructors
Answer: 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 you to protect data from being used by the non-
authorized classes.
Answer: You need to add a directory or a jar file that contains the package directories to the
CLASSPATH environment variable.Let's say a class Employee belongs to a package
com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java.In this case, you'd
need to add c:\dev to the variable CLASSPATH.If this class contains the method main(), you
could test it from a command prompt window as follows: c:\>java com.xyz.hr.Employee
What would you use to compare two String variables - the operator == or the method
equals()?
Answer: I'd use the method equals() to compare the values of the Strings and the == to check
if two variables point at the same instance of a String object.
http://sparshme5.googlepages.com
2
First Job…. Dream Job…. Sparshme5.googlepages.com
Can an inner class declared inside of a method access local variables of this method?
What can go wrong if you replace && with & in the following code: String a=null; if
(a!=null && a.length()>10) {...}
Answer: This method is used to ensure that Swing components are updated through the event-
dispatching thread.
Answer: Use the following syntax: super.myMethod(); To call a constructor of the superclass,
just write super(); in the first line of the subclass's constructor.
Answer: Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
You can create an abstract class that contains only abstract methods.On the other
hand, you can create an interface that declares the same methods.So can you use
abstract classes instead of interfaces?
Answer: Sometimes.But your class may be a descendent of another class and in this case the
interface is your only option.
What comes to mind when you hear about a young generation in Java?
If you're overriding the method equals() of an object, which other method you might
also consider?
http://sparshme5.googlepages.com
3
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: hashCode()
You are planning to do an indexed search in a list of objects.Which of the two Java
collections should you use: ArrayList or LinkedList?
Answer: ArrayList
How would you make a copy of an entire Java object with its state?
Answer: Have this class implement Cloneable interface and call its method clone().
How can you minimize the need of garbage collection and make the memory use more
effective?
There are two classes: A and B.The class B need to inform a class A when some
important event has happened.What Java technique would you use to implement it?
Answer: If these classes are threads I'd consider notify() or notifyAll().For regular classes you
can use the Observer interface.
What access level do you need to specify in the class declaration to ensure that only
classes from the same directory can access it?
Answer: You do not need to specify any access level, and Java will use a default package
access level.
Answer: Yes
Answer: No
Answer: Yes.
Answer: No
What is Externalizable?
Answer: Externalizable is an Interface that extends Serializable Interface.And sends data into
Streams in Compressed Format.It has two methods:
http://sparshme5.googlepages.com
4
First Job…. Dream Job…. Sparshme5.googlepages.com
writeExternal(ObjectOuput out)
readExternal(ObjectInput in)
Answer: Only public and abstract modifiers are allowed for methods in interfaces.
Answer: Because C++ has proven by example that operator overloading makes code almost
impossible to maintain.In fact there very nearly wasnt even method overloading in Java, but it
was thought that this was too useful for some very basic methods like print().Note that some
of the classes like DataOutputStream have unoverloaded methods like writeInt() and
writeByte().
Answer: Static variables and methods are instantiated only once per class.In other words they
are class variables, not instance variables.If you change the value of a static variable in a
particular object, the value of that variable changes for all instances of that class.Static
methods can be referenced with the name of the class rather than the name of a particular
http://sparshme5.googlepages.com
5
First Job…. Dream Job…. Sparshme5.googlepages.com
object of the class (though that works too).Thats how library methods like
System.out.println() work.out is a static field in the java.lang.System class.
Answer: Threads block on i/o (that is enters the waiting state) so that other threads may
execute while the I/O operation is performed.
Which characters may be used as the second character of an identifier,but not as the
first character of an identifier?
Answer: The digits 0 through 9 may not be used as the first character of an identifier but they
may be used after the first character of an identifier.
What modifiers may be used with an inner class that is a member of an outer class?
Answer: A (non-local) inner class may be declared as public, protected, private, static, final,
or abstract.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
Answer: Unicode requires 16 bits and ASCII require 7 bits.Although the ASCII character set
uses only 7 bits, it is usually represented as 8 bits.UTF-8 represents characters using 8, 16,
and 18 bit patterns.UTF-16 uses 16-bit and larger bit patterns.
Answer: Wrapped classes are classes that allow primitive types to be accessed as objects.
What restrictions are placed on the location of a package statement within a source
code file?
Answer: A package statement must appear as the first line in a source code file (excluding
blank lines and comments).
http://sparshme5.googlepages.com
6
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence.Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks.The scheduler
then determines which task should execute next, based on priority and other factors.
Answer: A native method is a method that is implemented in a language other than Java.
What are order of precedence and associativity, and how are they used?
Answer: Order of precedence determines the order in which operators are evaluated in
expressions.Associatity determines whether an expression is evaluated left-to-right or right-
to-left
Answer: If a checked exception may be thrown within the body of a method, the method must
either catch the exception or declare it in its throws clause.
Answer: An anonymous class may implement an interface or extend a superclass, but may
not be declared to do both.
Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and
Dialog classes.
http://sparshme5.googlepages.com
7
First Job…. Dream Job…. Sparshme5.googlepages.com
non synchronized multithreaded application, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating the object's
value.Synchronization prevents such type of data corruption.
E.g.Synchronizing a function:
Answer: The Collection API is a set of classes and interfaces that support operation on
collections of objects.These classes and interfaces are more flexible, more powerful, and
more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
Answer: Iterator is an interface which is used to step through the elements of a Collection.
Interfaces provide a form of multiple inheritance.A class can extend only one other
class.
Interfaces are limited to public methods and constants with no
implementation.Abstract classes can have a partial implementation, protected parts,
static methods, etc.
A Class may implement several interfaces.But in case of abstract class, a class may
extend only one abstract class.
Interfaces are slow as it requires extra indirection to to find corresponding method in
in the actual class.Abstract classes are fast.
Similarities:
http://sparshme5.googlepages.com
8
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: A class containing abstract method is called Abstract class.An Abstract class can't be
instantiated.
Example of Abstract class:
Answer: In Java Interface defines the methods but does not implement them.Interface can
include constants.A class that implements the interfaces is bound to implement all the
methods defined in Interface.
Emaple of Interface:
Answer: User defined Exceptions are the separate Exception classes defined by the user for
specific purposed.An user defined can created by simply sub-classing it to the Exception
class.This allows custom exceptions to be generated (using throw) and caught in the same
way as normal exceptions.
Example:
Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and
Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:
Scrollable result sets- using new methods in the ResultSet interface allows
programmatically move the to particular row or to a position relative to its current
position
JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
Java applications can now use the ResultSet.updateXXX methods.
New data types - interfaces mapping the SQL3 data types
Custommapping of user-defined types (UTDs)
http://sparshme5.googlepages.com
9
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: Garbage collection is one of the most important feature of Java.Garbage collection is
also called automatic memory management as JVM automatically removes the unused
variables/objects (value is null) from the memory.User program cann't directly free the object
from memory, instead it is the job of the garbage collector to automatically free the objects
that are no longer referenced by a program.Every class inherits finalize() method from
java.lang.Object, the finalize() method is called by garbage collector when it determines no
more references to the object exists.In Java, it is good idea to explicitly assign null into a
variable when no more in use.I Java on calling System.gc() and Runtime.gc(),JVM tries to
recycle the unused objects, but there is no guarantee when all the objects will garbage
collected.
What is OOPS?
Method overloading
Method overriding through inheritance
Method overriding through the Java interface
Answer: Access specifiers are keywords that determines the type of access to the member of
a class.These are:
Public
Protected
Private
Defaults
Answer: Wrapper class is wrapper around a primitive data type.An instance of a wrapper
class contains, or wraps, a primitive value of the corresponding type.
http://sparshme5.googlepages.com
10
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: The primitive types and the corresponding wrapper classes are listed below:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
void java.lang.Void
Describe the three OOPS principles?
Encapsulation:It is the way the code and data are confined and are in isolation from
the outside environment of the system.
Inheritance:It is the process by which one object acquires the properties of another
object.
Polymorphism:It is a feature that allows one interface to be used for a general class
of actions.The specific action is determined by the exact nature of the situation.
Answer: Endianness describes how multiple data types such as short , int and long are stored
in memory.If it takes two bytes to represent a short, then to predict if the most significant or
the least significant comes first.If the most significant byte is first, followed by the least
significant one then the machine is said to be big endian.Machines such as the SPARC and
Power PC are big-endian, while the Intel x86 series is little-endian.
Answer: There are four types of literals they are Integer literals, Floating point literals,
Boolean literals and character literals.
http://sparshme5.googlepages.com
11
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: The technique that automatically destroys the dynamically created objects is called
garbage collection.When no reference to an object exists, that object is assumed to be no
longer needed , and memory occupied by that object can be reclaimed.
Private - Makes a method or a variable accessible only from within its own class.
Protected - Makes a method or a variable accessible only to classes in the same
package or subclasses of the class.
Public - Makes a class , method or variable accessible from any other class.
http://sparshme5.googlepages.com
12
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: There are three ways , you can represent integer numbers in JAVA.They are
decimal (base 10) , octal (base 8) , and hexadecimal (base 16).
A note on defining floating point literal?
Answer: A floating point literal is defined as float g = 3576.2115F.
A note on arrays of object references?
Answer: A11.If the array type is CLASS then one can put objects of any subclass of
the declared type into the array.
The following example on sports explains the above concept:
class sports { }
class football extends sports { }
class hockey extends sports { }
class baseball extends sports { }
sports [ ] mysports = { new football (),
new hockey (),
new baseball ()};
What is meant by "instanceof" comparison?
Answer: It is used for object reference variables only.You can use it to check wether
an object is of a particular type.
Wen is a method said to be overloaded?
Answer: Two or more methods are defined within the same class that share the same
name and their parameter declarations are different then the methods are said to be
overloaded.
What is meant by Recursion?
Answer: It is the process of defining something in terms of itself.Interms of JAVA it
is the attribute that allows a method to call itself.
The following example of calculating a factorial gives an example of recursion. class
Factorial {
int fact (int n) {
int result;
if (n= 1) return 1;
result = fact(n -1) * n;
return result;
}
}
class Recursion {
Public static void main (string args[ ]) {
Factorial f = new Factorial ();
system.out.println ("Factorial of 10 is " + f.fact(10));
}
}
A cool example to explain the concept of METHOD in JAVA.
Answer: Let us say you are in Mcdonalds and you order for #7 for here with medium
coke.The cashier takes your order and punches it on the computer.The folks in the
kitchen get the order and they get the crispy chicken and pass it on to the guy who
puts a medium fries and finally a medium coke is filled and the order is served to
you.In other terms if all this was supposed to be done by a robot then it could have
been programmed the following way. void #7forherewithmediumcoke( )
{
Get (crispy chicken, lattice, butter, fries, coke);
make (sandwich);
http://sparshme5.googlepages.com
13
First Job…. Dream Job…. Sparshme5.googlepages.com
Answer: Applets are small programs transferred through Internet, automatically installed and
run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic
and interactive program that runs inside a Web page displayed by a Java-capable browser. We
don't have the concept of Constructors in Applets. Applets can be invoked either through
browser or through Appletviewer utility provided by JDK.
init() method: It is called when an applet is first loaded. This method is called only
once in the entire cycle of an applet. This method usually intialize the variables to be
used in the applet.
start( ) method: It is called each time an applet is started.
paint() method: It is called when the applet is minimized or refreshed.
This method is used for drawing different strings, figures, and images on the applet window.
stop( ) method: It is called when the browser moves off the applet's page.
destroy( ) method: It is called when the browser is finished with the applet.
What is the sequence for calling the methods by AWT for applets?
Answer: When an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place :
stop()
destroy()
http://sparshme5.googlepages.com
14