Monday, December 3, 2012

Java Interview Questions -1


System.gc() & Runtime.gc()
=============================
System.gc() internally calls Runtime.gc() or Runtiem.getRuntime().gc();
System.gc() is class method. Runtime.gc() is instance method.

public class Test {

protected void finalize(){

System.out.println("Finalize");

}

int i;
void intaliI(int i)
{ this.i=i; }

int retValueI()
  { return i; }

}


public  class SystemRuntimeGC {

public static void main(String args[]){

System.out.println("Starting");
System.gc();
System.out.println("Ending");

Test t1=new Test();
t1=null;
System.gc();
}
}

Garbage collection is happening via garbage collector.
OutOfMemoryError  Unchecked

Synchronization Block vs method
===============================
Method:
public synchronized void testFun()
{
statements;

}

Block
public void testFun(){

statements;
synchronized(this){
statements...;
}
}

Vector vs ArrayList
==================
Vector is synchronized & arraylist is not.
Vector double the size and arraylist is 50%.
Adding , removing at O(1)
Removing at particular position O(n-i) i is index

Abstract methods & Non Abstract Methods
=====================
Abstract methods can be called via non abstract methods

public abstract class AbstractExamples {

public int i;

public abstract void function1();

public void function2(){
System.out.println("Non abstract method");
function1();
}
}

public class AbstractClassExample extends AbstractExamples {

/**
* @param args
*/
public static void main(String[] args) {

AbstractClassExample abs=new AbstractClassExample();
abs.function1();
abs.function2();

System.out.println("int"+abs.i);

}

@Override
public void function1() {
System.out.println("Implemention abstract methods");

}

}

iterator
==========
iterator is an interface

Used step through collection of elements.

import java.util.Iterator;
import java.util.LinkedList;

public class IteratorExample {

/**
* @param args
*/
public static void main(String[] args) {
LinkedList ll=new LinkedList();
ll.add(2);
ll.add(5);

Iterator it=ll.iterator();
while(it.hasNext())
System.out.println(it.next());
}

}

Interface vs abstract
======================
we can implement multiple interface for class
Interface is limited to public and abstract methods. Abstract class can provide non abstract methods also.
Interface will take time for finding the corresponding methods. Abstract are fast

public abstract class AbstractExamples {

public int i;

public abstract void function1();

public void function2(){
System.out.println("Non abstract method");
function1();
}
}

public interface InterfaceExample {

public int j=0;

public void  interfaceFun1();

public void interfaceFun2();
}

public interface InterfaceExample2 {

public void interfaceExample2Fun1();
}

public class AbstractInterfaceExampleiMpl extends AbstractExamples implements InterfaceExample,InterfaceExample2{

@Override
public void interfaceFun1() {
// TODO Auto-generated method stub
System.out.println("Interface Fun1");
}

@Override
public void interfaceFun2() {
// TODO Auto-generated method stub
System.out.println("Interface Fun2");
}

@Override
public void function1() {
// TODO Auto-generated method stub
System.out.println("Abstract Fun1");
}

public static void main(String args[]){

}

@Override
public void interfaceExample2Fun1() {
// TODO Auto-generated method stub
System.out.println("Interface Example2 Fun1");
}
}

Virtual Functions in Java
=============
Abstract classes contain pure virtual functions in java.
Virual functions are like normal functions in java and we can override in subclasses.


wait vs sleep
================
wait can resume by notify or notifyall
sleep canto resume
wait can be called via synchronized block or method
wait is on Object and sleep is on Thread(sleep is static method)
yield pause the exection and give chance to other thread for execution
IllegalMonitorStateException occur in java if we dont call wait,notify,notifyAll in Synchronized method and race condition may happen between wait and notify



Checked vs Unchecked Exceptions
=============================

Checked exceptions should be handled in the code.

Compile error will throw for checked exception if we are not handling in  code.

Unchecked exception
===================
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Checked exception
=============
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Final
=======
Final methods canot be overriden but can be overloaded.
Final variable canot be reassigned or intialized.
Final classes canot be subclassed

Primitive Vs Wrapper
==============
Primitive - int,double,float,...
Wrapper- Integer,Double...

Reference: http://en.wikipedia.org/wiki/Primitive_wrapper_class

Sunday, September 9, 2012

Streams in Java


Java Streams has following abstract classes:
InputStream , OutputStream , Reader and Writer

IO Streams: Designed for byte streams
Reader and Writer: Character Streams

Writing to File Using Java Programming Language


package com.io;

import java.io.*;
import java.util.Scanner;

public class FileWrite {

public static void main(String args[]){

try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");

//Passing File name to File Class
String file=br.readLine();
File fname = new File(file);

boolean exist=fname.createNewFile();

                       //Verifying file exists or not ..
if(!exist){
System.out.println("File already exists");
System.exit(0);
}
else
{
FileWriter fwrite=new FileWriter(file);
BufferedWriter bwr=new BufferedWriter(fwrite);
bwr.write(br.readLine());
bwr.close();

System.out.println("Successfully created");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:
========
Enter File name
Hello.txt
Hello first file
Successfully created

Reading File in Java Using Java Programming


package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}

Output:
==========
Hi,
This is first file for reading
Thanks

Saturday, September 1, 2012

Polymorphism in Java Using Overloading and Overridden methods


Polymorphism
One form and many implementations.
It can be acheived by using inheritence,overloading and Overriding.
Compile time Polymorphism: Over loading
Runtitme Polymorphism: Over riding
Runtime Polymorphism /Dynamic method dispatch:
Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.
Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call
Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.

Overloading.
Two or more methods with same name in the same class with different arguments.

  • Overloaded methods Must change the argument list
  • May change the return type
  • May change the access modifiers.
  • May change the checded exceptions.

Example:
package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){
System.out.println("Int Int");
return a+b;
}

public double sum(double a,double b){
System.out.println("Double Double");
return a+b;
}

public int sum(int a,double b){
System.out.println("Int Double");
return (int) (a+b);
}
public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();
System.out.println("Overloading method"+oe.sum(3, 7));
System.out.println("Overloading method"+oe.sum(2.5, 5.7));
System.out.println("Overloading method"+oe.sum(2, 5.5));
}
}

Output:
=======
Int Int
Overloading method10
Double Double
Overloading method8.2
Int Double
Overloading method7


Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.

  • It can be used for defining the behaviour of child class.
  • Argument list same as overriden method.
  • Constructors canot be overridden.
  • final methods canot be overridden.
  • Static method cannot be overridden but can be re-declared.
  • super() can be used for invoking parent class(Super class) methods.

Example
package com.oops;

class OverExample{

public void fun1(){
System.out.println("Super Function1");
}

public void fun2(){
System.out.println("Super Using super() Function2");
}

}
public class OverRiddingExample extends OverExample{

public void fun1(){
System.out.println("Subclass Function1");
}


public void fun2(){
super.fun2();
System.out.println("Subclass Function2");
}

public static void main(String[] args) {
OverExample or=new OverRiddingExample();
OverExample oe=new OverExample();
or.fun1();
oe.fun1();
or.fun2();
}

}

Output:
========

Subclass Function1
Super Function1
Super Using super() Function2
Subclass Function2


Inheritance in Object Orient Programming and Java


Inheritance
Its a process where one object acquire properites another.
Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:
Class A extends B{
statements
}

Example:
=============
Pulsar is subclass of Bike
TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}
public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){
TwoWheeler two=new TwoWheeler();
SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
}
}

Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface. 

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}

interface Car
{
   public void setBrandname(String name);
}

interface HeaveyVechile{

public void setProperites(String prop);
}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{


public static void main(String args[]){

TwoWheeler two=new TwoWheeler();
Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
si.setBrandname("First");
si.setProperites("HeavyLoadVechile");
}

@Override
public void setBrandname(String name) {
System.out.println("Brand name is"+name);

}

@Override
public void setProperites(String prop) {
System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);


}

}

Output
=========
true
Calling method in SuperClass
Color: Red & Brand:Own
Brand name isFirst
Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile

interfaces in Object Oriented Programming Language


interface
==========
Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:
=========================
Canot mark interface as final
Cannot instiate interface.
Default: Methods in interface are abstract
fields in interface are static and final.
interface can implement class.
interface can extend multiple interfaces.

Class Implementing Interface
============================
package com.oops;

interface Bike{

//final static fields as default
int Capacity=150;

//abstract  methods as default
public void speed();
public void price();
}
public class InterfaceExample implements Bike {

@Override
public void speed() {
System.out.println("Speed of Bike is 100 KMPH");

}

@Override
public void price() {
System.out.println("Price of Bike is 75K");

}

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();
it.speed();
it.price();
}

}

Interface extends Multiple Interfaces

public interface Computer
{
   public void setBrandname(String name);
}

public interface Desktop extends Computer
{
   public void setProperty(String prop);
   public void viewProperty(String id);
}

public interface Laptop extends Computer
{
   public void setProcess(double process);
   public void setScreen(int size);
}

public interface Laptop extends Computer,Device{

statements
}

Encapsulation in Java Programming


Encapsulation: is like information Hiding.
Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:
============================

EmpDetails.java:
package com.oops;

public class EmpDetails {

private int empid;
private String empname;

public void setEmpid(int id){
empid=id;
}

public int getEmpid(){
return empid;
}

public void setEmpName(String name){
empname=name;
}

public String getEmpName(){
return empname;
}
}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**
* @param args
*/
public static void main(String[] args) {

EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

}

}

Output
==========
Employee details id: 1 and name:First

Abstraction and Abstract Class in java


Abstraction: Abstraction is act of representing data without including background details.

In java it can be achieved by using abstract classes/interfaces.
Hiding information can be achieved by modifiers.

Example for Abstract method:
  abstract  void function();

Example of abstract class:
 abstract class TestAbstract{

   abstract void fun1();
   public void fun2(){
    statements
   }

abstract classes contain abstract methods and normal methods.

Abstract Class Example:
package com.oops;

abstract class Area{
int side;

Area(int a){
side=a;
}
abstract int area();
public void nonAbstractMethod(){
System.out.println("Non abstract Method");
}
}

class Square extends Area{

Square(int a) {
super(a);
}

@Override
int area() {

System.out.println("Square Area");
return side*side;
}

}

class Rect extends Area{

public Rect(int a) {
super(a);
// TODO Auto-generated constructor stub
}

@Override
int area() {
// TODO Auto-generated method stub
System.out.println("Area of Triangle");
return side*side;
}

}

public class AbstractClassExample {

public static void main(String args[]){

Square sq=new Square(3);
Rect rt=new Rect(5);

Area ar;

ar=sq;
System.out.println("Square Area"+ar.area());

ar=rt;
System.out.println("Rectangle area"+ar.area());
}
}

Output:
============
Square Area
Square Area9
Area of Triangle
Rectangle area25

Sunday, August 26, 2012

Thread Programming Interview Questions in Java 2


Q) How to set & get Priority in Threads using java?

public class ThreadExample implements Runnable{

public  void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

System.out.println("Thread 1 Priority"+t1.getPriority());

t2.setPriority(9);

System.out.println("Thread 2 Priority "+t2.getPriority());

}

}

Output
=============
Thread Starting
Thread Starting
012345678Thread 1 Priority5
Thread 2 Priority 5
012345678

Q) Difference between green thread and native thread in Java?
A) Native threads can switch between threads pre-emptively, switching control from a running thread to a non-running thread at any time. Green threads only switch when control is explicitly given up by a thread (Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.).
On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU.

Q)  Difference between thread and process?
A) Threads share the address space of the process that created it; processes have their own address space.
Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

Q) Thread Life Cycle?



Q) What is context switching in multi-threading?
A) When doing context switching on a single-core processor, the code responsible is executed on the only CPU which takes care of switching the threads.
The kernel is multi-threaded. It can execute on any core. When a core comes to need to swap threads, it invokes the part of the kernel responsible for selecting the next thread it should execute.

5)  What thread-scheduling algorithm is used in Java?
6)  What is thread-scheduler in Java?
7)  How do you handle un-handled exception in thread?
8)  What is thread-group, why its advised not to use thread-group in Java?
9)  Why Executor framework is better than creating and managing thread by application ?
10) Difference between Executor and Executors in Java?
10) How to find which thread is taking maximum cpu in windows and Linux server?


Q) In which class would you find the methods sleep() and yield()?  Thread class

Q) Can you notify a particular thread? :   No

Q) How to make a normal thread as daemon thread?
A) We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

Q) Give one good example of a daemon thread? : Garbage Collector is a low priority daemon thread.

Q) What are the two ways that a code can be synchronised?
A) Method can be declared as synchronised and A block of code be sychronised.


Q)What happens when I make a static method as synchronized?
A) Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.


Q) Can a thread execute another objects run() method?
A) A thread can execute it's own run() method or another objects run() method.

Q) What are different ways in which a thread can enter the waiting state?
A) A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an object's lock
4. By invoking an object's wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.

Q) What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state.

Q)What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
A)Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait( ), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.

Q) What is the difference between preemptive scheduling and time slicing?
A) 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 re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q) run(): After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Q) wait(), notify(), and notifyAll() methods : Methods are used to provide an efficient way for thread inter-communication.

Q) Thread & States ?
A) A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

Q) What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Q) What happens when a thread cannot acquire a lock on an object?
A) Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

Q) What is the difference between process and thread?
A) A thread is a separate path of execution in a program. A Process is a program in execution.

Q) Why would you use a synchronized block vs. synchronized method?
A) Synchronized blocks place locks for shorter periods than synchronized methods.

Q) What is an object's lock and which objects have locks?
A) An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q)Let`s say you have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
(A) It can be achieved using join method of Thread class.

Q)How to know the thread priority?
A) isAlive() —it returns true when Thread is running
A) join() these two methods are used to know thread priority.

Q) What is a deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. Deadlock ocurred on Two threads call Thread.join() on each other and Two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

Java Threading Programming Interview Questions 1


Q) Explain different way of using thread?
A) A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is can be used for Thread because we can inherit one more class.

Q) What are the two types of multitasking?
A) process-based and Thread-based

Q) Thread Example by extending Thread Class
A) public class ThreadExample extends Thread{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
new ThreadExample().start();

}

}

Q) Thread Example by Implmenting runnable interface?
public class ThreadExample implements Runnable{

public void run(){
System.out.println("Thread Starting");
for(int i=0;i<9;i++)
System.out.println(i);
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();
}

}

Q) What is synchronization in respect to multi-threading in Java?
A) Synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Example
=======
public class ThreadExample implements Runnable{

public  synchronized void run(){
System.out.println("Thread Starting");

{
for(int i=0;i<9;i++)
System.out.print(i);
}
}

public static void main(String args[]){
Thread t1=new Thread(new ThreadExample());
t1.start();

Thread t2= new Thread(new ThreadExample());
t2.start();

Thread t3= new Thread(new ThreadExample());
t3.start();

}

}

Q)Difference  Thread.start() & Thread.run() method?
A) Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.

Q) Why do we need run() & start() method both. Can we achieve it with only run method?
A) We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.


Q) Can you declare a static method as synchronized?
A) Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.


Q) & A) Constrcutor in Thread Class : Thread(Runnable threadob,String threadName)

Q) & A) Metods available in the Runnable Interface? run()

Q) & A) What is the data type for the method isAlive() and this method is available in which class? : boolean, Thread

Q) What are all the methods available in the Thread class?
A)isAlive()
join()
resume()
suspend()
stop()
start()
sleep()
destroy()

Q) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
A)wait(),notify() & notifyall() and Object class

Q) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time? : Synchronisation

Q) Thread Priority values
A) MAX-10, MIN-1 NORMAL-5 and Method is setPriority()

Q)Default thread at the time of starting the program?: Main Method

Q) Thread States: new,runnable,blocked & dead

Q) The suspend()method is used to teriminate a thread? : False

Q) The run() method should necessary exists in clases created as subclass of thread? : True

Q) Which method waits for the thread to die ? : join() method

--wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
  wait(),notify(),notifyall() the wait() method only throws IOException

Q)Garbage collector thread belongs to which priority? : low-priority

Q) What is meant by daemon thread? In java runtime, what is it's role?
A) Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Java Exception Handling Programming Questions


Q) What are the two types of Exceptions?
A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?
A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true?
A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method.
In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception.

Q)Can we have a try block without a catch block?
public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}
finally{
System.out.println("finally");
}
}
}

Output:
=======
finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
A) Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Q)Explain try,catch and finally statements in Java ?
The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {
   
} catch (Exception e) {
   
}finally{

}

Example
======

public class JExample {

public static void main(String args[]){
int i=0;
int j=4;

try
{
int k=j/i;
}catch(Exception e)
{
System.out.println("Exception caught");
e.printStackTrace();
}
finally{
System.out.println("finally");
}
}
}

Output:
======
Exception caught
java.lang.ArithmeticException: / by zero
at com.test.JExample.main(JExample.java:11)
finally


Q) If there is common code to be executed  in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort?
A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.
In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){}
4) Have you every created custom exceptions? Explain the scenario?
Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?
A)Validation is the process of making user enter data in a format which the application can handle.
Exception handling is the process when the application logic didn’t work as expected by the Java compiler.
Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.

Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?
A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection.
But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?
A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?
Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions.
Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?
package com.test;

//NullException is the user exception defined
class NullException extends Exception{

int a;

public NullException(int i) {
i=a;
}

public String toString(){
return "Created NullException:"+a;
}
}
public class CustomException
{

public static void Divide(int a,int b) throws NullException{

int k=a/b;
throw new NullException(k);
}
public static void main(String args[]){

try{

CustomException c=new CustomException();
c.Divide(5, 2);
}catch(Exception e){
System.out.println("Main CustomExceptionm:" +e);
}finally{
System.out.println("Finally Exceuting");
}

}
}

Output
=========
Main CustomExceptionm:Created NullException:0
Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?
A) NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.


Q) Can a catch block exist without a try block?
A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?
A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
A) ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.


Q) return statement in try,catch and finally ?
public class ExceptionDemo {

public int chkException(int arr[]){

int k=0;
int t=1,c=2,f=3;
try
{
for(k=0;k<5;k++)
System.out.println("arr Element"+arr[k]);
System.out.println("Try Catch");
return t;
}catch(Exception e){
System.out.println("Failed on exception"+e.getMessage());
System.out.println("Catch Retrun");
return c;
}finally{
System.out.println("Finally Return");
return f;
}
}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();
e.chkException(arr);

}
}

Output
============
arr Element1
arr Element4
arr Element5
Failed on exception3
Catch Retrun
Finally Return

Wednesday, August 22, 2012

Thread Example in Java


public class ThreadExample extends Thread{

public synchronized  void run(){
for(int i=0;i<11;i++)
System.out.print(i);
System.out.println(" ");
}
public static void main(String args[]){
Thread t1=new ThreadExample();
Thread t2=new ThreadExample();
Thread t3=new ThreadExample();

t1.start();
t2.start();
t3.start();

t1.setPriority(MAX_PRIORITY);
System.out.println("Thread 1 Priority"+t1.getPriority());

System.out.println("Thread 1 Group"+t1.getThreadGroup());

System.out.println("State of Thread2"+t2.getState());

}
}

Tuesday, August 21, 2012

Basic String Operations in Java


public class StringOperations {

public static void main(String args[]){
String str1="Hello";
String str2="Ja va";
String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));
System.out.println("String2 at Index 2:"+str2.charAt(2));
System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));
System.out.println("Compare str1 and str3"+str1.compareTo(str3));
System.out.println("String2 contains Ja: "+str2.contains("Ja"));
System.out.println("String is empty ?"+str1.isEmpty());
System.out.println("Sting HashCode"+ str1.hashCode());
System.out.println("Substring of String1"+str1.substring(2, 3));
System.out.println("Remove whitespaces in String2"+str2.trim());
System.out.println("Convert to LowerCase"+str2.toLowerCase());
System.out.println("Replace a with A"+str3.replace('a','A'));
}
}

OutPut:
========
String1 == String3true
String2 at Index 2: 
Compare Str2 and Str32
Compare str1 and str30
String2 contains Ja: true
String is empty ?false
Sting HashCode69609650
Substring of String1l
Remove whitespaces in String2Ja va
Convert to LowerCaseja va
Replace a with AHello

Vector Operations Using Java Programming


import java.util.Iterator;
import java.util.Vector;

public class VectorOperations {

public static void main(String args[]){
Vector vt=new Vector();

vt.add(21);
vt.add(12);
vt.add(57);
vt.add(29);
vt.add(43);

System.out.println("Vector"+vt);

//Adding elements in Vector
vt.add(2, 25);
System.out.println("Vector"+vt);
vt.addElement(23);
System.out.println("Vector"+vt);

//Vector Operations.
System.out.println("Capacity"+vt.capacity());
System.out.println("Conatains 43:"+vt.contains(43));
System.out.println("First element"+vt.firstElement());
System.out.println("Value at Index 4: "+vt.get(4));
System.out.println("Remove value at 3"+vt.remove(3));

vt.add(43);
vt.add(45);
vt.add(46);
vt.add(47);
vt.add(48);
vt.add(49);
vt.add(32);
vt.add(33);
vt.add(34);

System.out.println("Vector Elements afte insertion more than 10 elements");
Iterator it=vt.iterator();
while(it.hasNext())
System.out.print(" "+it.next());
}

}


Output:

Vector[21, 12, 25, 57, 29, 43, 23]
Capacity10
Conatains 43:true
First element21
Value at Index 4: 29
Remove value at 357
Vector Elements afte insertion more than 10 elements
 21 12 25 29 43 23 43 45 46 47 48 49 32 33 34

Queue Operations Using LinkedList in Java



import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;


public class QueueOperations {

public static void main(String args[]){

Queue que=new LinkedList();

//Insert elements into Queue
que.offer(12);
que.offer(25);
que.offer(75);
que.offer(9);

System.out.println("Queue"+que);

//Queue Operations
System.out.println("Queue Peek the elmenet  "+que.peek());
System.out.println("Queue Remove Element "+que.poll());

System.out.println("isEmpty :?"+que.isEmpty());
}
}

Output:
Queue[12, 25, 75, 9]
Queue Peek the elmenet  12
Queue Remove Element 12
isEmpty :?false

Stack Operations Using Java Programming


import java.util.Iterator;
import java.util.Stack;

public class StackOperations {

public static void main(String args[]){
Stack st=new Stack();

//Push the elments into stack
st.push(12);
st.push(9);
st.push(15);
st.push(76);
st.push(55);

//Elements in stack
System.out.println("Stack"+st);

//Pop the Elements
System.out.println("Top of the Stack:"+st.peek());
System.out.println("Pop the element from stack "+st.pop());

//Display elements using iterator
Iterator it=st.iterator();
while(it.hasNext())
System.out.println(it.next());

//Check stack is Empty or not
System.out.println("Stack is empty ?"+st.isEmpty());

}
}

Output:
Stack[12, 9, 15, 76, 55]
Top of the Stack:55
Pop the element from stack 55
12
9
15
76
Stack is empty ?false

Inserting an element into Linked List in C Programming Language


#include<stdlib.h>
typedef struct Node
{
        int data;
        struct Node *next;
}node;


void insert(node *pointer, int data)
{
       while(pointer->next!=NULL)
        {
                pointer = pointer -> next;
        }
        pointer->next = (node *)malloc(sizeof(node));
        pointer = pointer->next;
        pointer->data = data;
        pointer->next = NULL;
}

//Printing the elements in linkedlist.
void print(node *pointer)
{
        if(pointer==NULL)
        {
                return;
        }
        printf("%d ",pointer->data);
        print(pointer->next);
}

int main()
{
        node *start,*temp;
        start = (node *)malloc(sizeof(node));
        temp = start;
        temp -> next = NULL;

         // Inserting elements into linked List
          insert(start,2);
          insert(start,3);
          insert(start,4);

        // Printing the elements in linked list
         print(start->next);


}

Monday, August 20, 2012

Thread Interview Questions in Java


1) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling?
Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc.
Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesn’t exist.

Multiple exceptions in single catch block
catch(FileNotFoundExcpetion fne | Exception e){}

What are the differences between NoClassDefFoundError and ClassNotFoundException?
Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program.
For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.
ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.
For example: The database driver is not found when trying to load the driver using Class.forName() method.

What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?
Ans: ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where e is the reference to the exception being caught. The exception is re-thrown to the client.
This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used.
The use of “throw null;” statement causes NullPointerException to be thrown.
The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.

Java Collection Programming Interview Questions



What is the Difference between Enumeration and Iterator interface?
1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
4. Enumeration act as read-only elements. Iterator we can manipulate the objects also like adding and removing the objects.

Where will you use Hashtable and where will you use HashMap?
The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.

Which one will provide the faster insertion of a new element into the middle positoin. Vector / ArrayList / LinkedList 
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

List - this is an ordered list of objects, insertion order is maintained and retrieval order is in the list order but items can also be random accessed, duplicate items are allowed, generally allow storage of null values (the ones below do), generally fast to iterate and find items by position but slow to do lockups

ArrayList - Unsychronized, nulls allowed (fastest)
Vector - Synchronized, only slightly slower in tests of sizes under 100000
Stack - Synchronized, same speed as Vector, LIFO queue
LinkedList - Unsynchronized, allows two way iteration and modification of items (like a stack or queue)

Set - this a set of items with no duplicates (no two items can compare as equal), ordering is typically inconsistent over multiple set iterations depending on the implementation but you should assume the order is effectively random unless the set specifies ordered iteration, generally ok to iterate and fast to do lookups
HashSet - Unsychronized (fastest), slower than HashMap which it is built on, allows nulls
LinkedHashSet - Unsychronized, ordered by insertion, allows nulls
TreeSet - Unsychronized, ordered by the natural ordering of the items or a comparator provided at construction, allows nulls but there are issues with removing them

Map - Stores key/value pairs (maps keys to values) where the keys must be unique, order of iteration over keys, values, or pairs is highly dependent on the implementation of the map, allowed nulls also vary by implementation, generally very fast to lookup keys and slow to lookup values
LinkedHashMap - Unsychronized, all iterators are ordered based on insertion order of the original key (does not change if a key is reinserted), allows null values but null keys are not allowed
TreeMap - Unsychronized, iterators are ordered by the natural or comparator ordering of the keys, allows null keys and values but the comparator needs to understand them

Reference: http://docs.oracle.com/javase/tutorial/collections/TOC.html