Sie sind auf Seite 1von 15

What is Daemon thread?

Daemon threads in Java are like a service providers for other threads or objects
running in the same process as the daemon thread. Daemon threads are used for
background supporting tasks and are only needed while normal threads are
executing. If normal threads are not running and remaining threads are daemon
threads then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal
thread and daemon threads differ in what happens when they exit. When the JVM
halts any remaining daemon threads are abandoned: finally blocks are not
executed, stacks are not unwound JVM just exits. Due to this reason daemon
threads should be used sparingly and it is dangerous to use them for tasks that
might perform any sort of I/O.
setDaemon(true/false) ? This method is used to specify that a thread is daemon
public boolean isDaemon() ? This method is used to determine the thread is daemon
thread or not.
Example:package com.myjava.threads;
public class DaemonThread extends Thread{

public DaemonThread(){
public void run(){
System.out.println("Is this thread Daemon? - "+isDaemon());
public static void main(String a[]){
DaemonThread dt = new DaemonThread();
// even you can set daemon constrain here also
// it is like dt.setDeamon(true)

What is the access scope of a protected method?

A protected method can be accessed by the classes within the same package or by
the subclasses of the class in any package.
What is synchronization and why is it important? Explain the use of
synchronization keyword.
Java supports multiple threads to be executed. This may cause two or more
threads to access the same fields or objects. Synchronization is a process which

keeps all concurrent threads in execution to be in synch. Synchronization avoids

memory consistence errors caused due to inconsistent view of shared memory.
When a method is declared as synchronized; the thread holds the monitor for that
method's object If another thread is executing the synchronized method, your
thread is blocked until that thread releases the monitor.
Java - the use of synchronization keyword.
When a method in Java needs to be synchronized, the keyword synchronized should
be added.
Public synchronized void increment()
Synchronization does not allow invocation of this Synchronized method for the same
object until the first thread is done with the object. Synchronization allows having
control over the data in the class.
What is the purpose of the wait (), notify (), and notifyAll() methods?
wait() causes the thread to pause for certain number of milli seconds or until it is
notify() A thread in wait state will be returned to running state
notifyAll() All threads those are in wait state will be returned to running state
Diff erence between Abstract Class and Interface



keyword is used to create an abstract class and it can be used with

methods also whereasinterface keyword is used to create interface and it cant

be used with methods.
2. Subclasses use


keyword to extend an abstract class and they need to

provide implementation of all the declared methods in the abstract class


















implementation for all the methods declared in the interface.

3. Abstract classes can have methods with implementation whereas interface
provides absolute abstraction and cant have any method implementations.

4. Abstract









5. Abstract class have all the features of a normal java class except that we
cant instantiate it. We can useabstract keyword to make a class abstract but
interfaces are a completely different type and can have only public static
final constants and method declarations.
6. Abstract classes methods can have access modifiers as public, private,
protected, static but interface methods are implicitly public and abstract, we
cant use any other access modifiers with interface methods.
7. A subclass can extend only one abstract class but it can implement multiple
8. Abstract classes can extend other class and implement interfaces but
interface can only extend other interfaces.
9. We can run an abstract class if it has


method but we cant run an

interface because they cant have main method implementation.


Interfaces are used to define contract for the subclasses whereas abstract

class also define contract but it can provide other methods implementations
for subclasses to use.
What is runtime polymorphism?
Runtime polymorphism or Dynamic Method Dispatchis a process in which a call to an
overridden method is resolved at runtime rather than compile-time.In this process, an
overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable..

When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:


class A{}
class B extends A{}
A a=new B();//upcasting

Example of Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference
variable of Parent class. Since it refers to the subclass object and subclass method overrides
the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime

class Bike{
void run(){System.out.println("running");}

class Splender extends Bike{

void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splender();//upcasting;

Output:running safely with 60km.

Real example of Java Runtime Polymorphism

Consider a scenario, Bank is a class that provides method to get the rate of interest. But,
rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7% and 9% rate of interest.

Note: It is also given in method overriding but there was no upcasting.


class Bank{
int getRateOfInterest(){return 0;}

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

class Test{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
SBI Rate of Interest: 8
ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Runtime Polymorphism with data member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved
by data members.
In the example given below, both the classes have a datamember speedlimit, we are
accessing the datamember by the reference variable of Parent class which refers to the
subclass object. Since we are accessing the datamember which is not overridden, hence it
will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.


class Bike{
int speedlimit=90;

class Honda extends Bike{

int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda();

Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

class Animal{
void eat(){System.out.println("eating");}

class Dog extends Animal{

void eat(){System.out.println("eating fruits");}

class BabyDog extends Dog{

void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();


a2=new Dog();
a3=new BabyDog();;;;
Output: eating
eating fruits
drinking Milk

How is final different fron finally and finalize()?

final: final is a keyword. The variable decleared as final should beinitialized only
once and cannot be changed. Java classes declared as final cannot be extended.
Methods declared as final cannot be overridden.
finally is a block. The finally block always executes when the try block
exits. This ensures that the finally block is executed even if an unexpected
exception occurs. But finally is useful for
more than just exception handling - it
allows the programmer toavoid having cleanup code accidentally bypassed by a
continue, or break. Putting cleanup code in a finally block is always a
good practice, even when no exceptions are anticipated.
finalize is a method. Before an object is garbage collected, theruntime
system calls its finalize() method. You can write system
resources release code in
finalize() method before getting garbagecollected.
What is partial implementation in java?

Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that interface, then
that class must bedeclared as abstract.
Explain compareTo() and charAt () in reference to string.
charAt():This method returns the character located at the String's specified index. The string indexes
start from zero.

Syntax: public char charAt(int index)

public class Test {
public static void main(String args[]) {

String s = "Strings are immutable";

char result = s.charAt(8);
compareTo():. Compares values and returns an int which tells if the values compare less than,
equal, or greater than.

The a.compareTo(b) function is used to determine the order of 2objects. If a is is

ordinally higher, it returns 1; lower returns -1;and the same value returns 0;
public class CompareTest{
public static void main(String[] args){
String a = "a";
String b = "b";
String c = "a";
System.out.println("a.compareTo(b) = "+a.compareTo(b));
System.out.println("b.compareTo(a) = "+b.compareTo(a));
System.out.println("a.compareTo(c) = "+a.compareTo(c));

List any two stream classes and their subclasses in java

FileInputStream and FileOutputStream
Read data from or write data to a file on the native file system.
PipedInputStream and PipedOutputStream
Implement the input and output components of a pipe. Pipes are used to channel
the output from one program (or thread) into the input of another. A

PipedInputStream must be connected to a PipedOutputStream

PipedOutputStream must be connected to a PipedInputStream.


ByteArrayInputStream and ByteArrayOutputStream

Read data from or write data to a byte array in memory.
Concatenate multiple input streams into one input stream.
Allow programs to read from a StringBuffer as if it were an input stream.

Program to compare two strings.

import java.util.Scanner;
class CompareStrings
public static void main(String args[])
String s1, s2;
Scanner in = new Scanner(;
System.out.println("Enter the first string");
s1 = in.nextLine();
System.out.println("Enter the second string");
s2 = in.nextLine();

if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
System.out.println("Both strings are equal.");

What is use of super and final keywords in java program?

The super keyword is used to call variables, methods, and/or constructors of a
parent class. If references the parent class through the super keyword (super.[field]
or super.[method/constructor]([args])).
The final keyword has a few uses.
1. The most common is to make a variable's value constant, and create a compile
error if it is changed after its first assignment of a value. This does not mean

that the variable is immutable: the value itself can possibly change, but the
assignment to that value cannot.
2. A method declared final cannot be changed in a subclass.
3. A final class cannot be subclassed.
Expalin left and right shift operators with example.

Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.

A << 2 will give 240 which

is 1111 0000


Binary Right Shift Operator. The left operands value is moved right by the A >> 2 will give 15 which is
number of bits specified by the right operand.

Why java is considered as the best language for internet applications?

java is an object oriented language and a very simple language. Because it has no space for
complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling
set up boxes and devices. But later new features were added to it and it was renamed as Java. Java
became a general purpose language that had many features to support it as the internet language. Few
of the features that favors it to be an internet language are:
Cross Platform Compatibility: The java source files (java files with .java extension) after compilation
generates the bytecode (the files with .class extension) which is further converted into the machine code
by the interpreter. The byte code once generated can execute on any machine having a JVM. Every
operating system has it's unique Java Virtual Machine (JVM) and the Java Runtime Environment (JRE).
Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols
like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc .
Support to HTML: Most of the programming languages that are used for web application uses the html
pages as a view to interact with the user. Java programming language provide it's support to html. For
example. Recently the extension package jipxhtml is developed in java to parse and create the html 4.0
Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides the
mechanism to retrieve the values from respective fields and accordingly creates the java objects. These
objects enables to invoke methods to achieve the desired functionality.

Support to XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using
different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different
applications over the internet.
Support to Web Services : Java has a rich variety of APIs to use xml technology in diverse applications
that supports N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC ,
JAXR etc enables to implement web services in java applications. It makes java a most suited internet
Support to java enabled Mobile devices: Java programming language is made in such a way so that it
is compatible with mobile devices also. Java language also works with any java enabled mobile devices
that support MIDP 1.0/2.0 including the symbian OS mobile devices.
Support to Personal Digital Assistants: Java language is compatible with Personal Java 1.1 such as
chaiVM, Jeode, CrEME, and JV-Lite2 or with all the later version and it also support PDAs like
HP/Compaq, iPAQ, Fujitsu-Siemens Pocket Loox and SimPad, HHP, NEC, Samsung, Sharp Electronics,
Toshiba, psion m5, and any other device.
Program that accepts number from user and converts it in to binary using wrapper class method
package com.java2novice.wrapper.integer;
public class MyIntegerToBinary {
public static void main(String a[]){
Integer i = new Integer(20);
String binary = Integer.toBinaryString(i);
System.out.println("Binary value: "+binary);

A final class cannot be subclassed. Doing this can confer security and efficiency benefits, so many
of the Java standard library classes are final, such asjava.lang.System and java.lang.String.
All methods in a final class are implicitly final.
public final class MyFinalClass {...}
public class ThisIsWrong extends MyFinalClass {...}

Final variables[edit]
A final variable can only be initialized once, either via an initializer or an assignment statement. It
does not need to be initialized at the point of declaration: this is called a "blank final" variable. A
blank final instance variable of a class must be definitely assigned in every constructor of the class in
which it is declared; similarly, a blank final static variable must be definitely assigned in a static
initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases. [5]
(Note: If the variable is a reference, this means that the variable cannot be re-bound to reference
another object. But the object that it references is still mutable, if it was originally mutable.)
Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.
It is considered good practice to represent final constants in all uppercase, using underscore to
separate words.[6]
public class Sphere {
// pi is a universal constant, about as constant as anything can be.
public static final double PI = 3.141592653589793;




Sphere(double x, double y, double z, double r) {

radius= r;
xPos = x;
yPos= y;
zPos= z;

What is final variable in Java?
Any variable either member variable or local variable (declared inside method or
block) modified by final keyword is called final variable. Final variables are often
declare with static keyword in java and treated as constant. Here is an example of
final variable in Java
public static final String LOAN = "loan";

LOAN = new String("loan") //invalid compilation error

Final variables are by default read-only.
What is final Class in Java
Java class with final modifier is called final class in Java. Final class is complete in
nature and can not be sub-classed or inherited. Several classes in Java are final e.g.
String, Integer and other wrapper classes. Here is an example of final class in java
final class PersonalLoan{
class CheapPersonalLoan extends PersonalLoan{ //compilation error: cannot inherit
from final class
Give 4 methods of string buffer class.
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class is same as String except it is mutable i.e. it can be changed.
1. public synchronized StringBuffer reverse(): is used to reverse the string.
2. public int capacity(): is used to return the current capacity.
3. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
4. public char charAt(int index): is used to return the character at the specified
5. public int length(): is used to return the length of the string i.e. total number of
6. public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
7. public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.

Why string objects are considered to be mutable?

String is an immutable class in Java. An immutable class is simply a class whose
instances cannot be modified. All information in an instance is initialized when the
instance is created and the information can not be modified. There are many
advantages of immutable classes. This article summarizes whyString is designed to
be immutable. A good answer depends on deep understanding of memory,
synchronization, data structures, etc.
1. Requirement of String Pool

String pool (String intern pool) is a special storage area in Method Area. When a
string is created and if the string already exists in the pool, the reference of the
existing string will be returned, instead of creating a new object and returning its
The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:

If string is not immutable, changing the string with one reference will lead to the
wrong value for the other references.
2. Caching Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being
immutable guarantees that hashcode will always the same, so that it can be cashed
without worrying the changes.That means, there is no need to calculate hashcode
every time it is used. This is more efficient.
In String class, it has the following code:
private int hash;//this is used to cache hash code.
3. Facilitating the Use of Other Objects
To make this concrete, consider the following program:
HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));

for(String a: set)
a.value = "a";
In this example, if String is mutable, it's value can be changed which would violate
the design of set (set contains unduplicated elements). This example is designed for
simplicity sake, in the real Stringclass there is no value field.
4. Security
String is widely used as parameter for many java classes, e.g. network connection,
opening files, etc. Were String not immutable, a connection or file would be changed
and lead to serious security threat. The method thought it was connecting to one
machine, but was not. Mutable strings could cause security problem in Reflection
too, as the parameters are strings.
Here is a code example:
boolean connect(string s){
if (!isSecure(s)) {
throw new SecurityException();
//here will cause problem, if s is changed before this by using other references.
5. Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among
multiple threads freely. This eliminate the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and
security. This is also the reason why immutable classes are preferred in general.