Sunday, October 31, 2010

Generics in Java

HI ,
  An Important link about Generics in Java.

http://www.javabeat.net/articles/33-generics-in-java-50-1.html


what is upper bound in Java Generics?
Ans: 

7.1) Upper Bound

The solution to this situation is the usage of wild-cards along with parametric bounding. Have a look over the following declaration.
List animals = new ArrayList();
It tells that a list is being declared with type being anything (?) that is 
extending the Animal class. Though it looks very similar to the above declaration
 it has some differences. The first thing is that it is now possible for the animals
 reference to point to a list that is holding any sub-type of Animal objects.
List dogs = new ArrayList();
dogs.add(new Dog()); dogs.add(new Dog());
 
animals = dogs;
One important difference is that, it is not possible to add elements to the 
animals list, though the only exception is adding null elements. This is
 called the Upper Bound for the animals list.

Object Serialization

Question : What is Object Serialization ?
Ans :      Object serialization is the process of saving an object's state 
 to a sequence of bytes, as well as the process of rebuilding those bytes 
 into a live object at some future time.


How to make an Object serializable ?
Ans : By implementing the "Serializable Interface".
        An object is marked serializable by implementing the java.io.Serializable
       interface, which signifies to the underlying API that the object can be flattened 
       into bytes and subsequently inflated in the future.


What is Serialization ?
Ans :      Serialization is the process of writing complete state of java object into 
output stream, that stream can be file or byte array or stream associated with 
TCP/IP socket.


What is Marker Interface ?
An:  A Marker Interface is a Interface which may Contain a Method.But a Marker
 Interface should tell a special Information to JVM. that what type of class or object
 it can be.


Example :
 EX. 1) Cloneable is a marker interface with no method which means but
it provide information to the JVM that class's object who implement it
can be cloned.

2) Runnable is also a marker interface with a run() method which provide 
the information to the JVM that class's object which implement this is used
 as a thread.
 
3) while the collection interface doesn't provide any special information to the
 JVM that's why it is not as a Marker interface.

Example for Object Serialization ?
Ans : 
   class Name : PersistentTime.java whose object is serializable.
-----------------------------------------------------------------------------
package newPackage;

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

public class PersistentTime implements Serializable{

 private Date time;
 
 public PersistentTime(){
  
  time = Calendar.getInstance().getTime();
  System.out.println(" Time : "+time);
 }
 public Date getTime(){
  
  return time;
 }
 
}
-------------------------------------------------------------------------------------------
Class Name : SerializeObject.java  using this Serializable the persistentTIme Object.



package newPackage;


import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class SerializeObject {

public static void main(String[] args){
String fileName = "SerialObject.txt";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
PersistentTime pt = new PersistentTime();
try{
fos = new FileOutputStream(fileName);
oos = new ObjectOutputStream(fos);
oos.writeObject(pt);
oos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}


-----------------------------------------------------------------------------------------------------------


Class Name : DeserializeObject.java used to de-serialize the Object.

package newPackage;


import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Calendar;


public class DeserializeObject {

public static void main(String[] args) {
String fileName = "SerialObject.txt";
PersistentTime pt = null;
FileInputStream fis = null;
ObjectInputStream ois = null;

try
{
fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
pt = (PersistentTime)ois.readObject();
ois.close();

}catch(Exception e){
e.printStackTrace();
}
System.out.println(" Seraible time "+pt.getTime());
System.out.println(" Current Time : "+Calendar.getInstance().getTime());
}
}
----------------------------------------------------------------------------------------------------------


Excellent Question : What if a Class having a Super class, and the super class 
implements the Serializable interface, but we don't want the subclass to be serializable.


---------------------------  STOP Serialization ----------------------------------------------


Answer : by creating private Methods , and throw the Exception while serializing an Object.
10 private void writeObject(ObjectOutputStream out) throws IOException
20 {
30 throw new NotSerializableException("Not today!");
40 }
50 private void readObject(ObjectInputStream in) throws IOException
60 {
70 throw new NotSerializableException("Not today!");
80 }

   
Any attempt to write or read that object will now always result in the exception being 
thrown. Remember, since those methods are declared private, nobody could modify 
your code without the source code available to them -- no overriding of those methods 
would be allowed by Java.


What is Transient Keyword?
Ans: The serialization mechanism simply skips over the transient variables. 


What is serialPersistentFields?
Ans : Declaring serialPersistentFields is almost the opposite of declaring some fields
 transient. The meaning of transient = "This field shouldn't be stored by serialization,"
and  serialPersistentFields =  "These fields should be stored by serialization.











Friday, October 29, 2010

Java Interview Questions

1) Can Constructor have a return type?
Ans: We should not , if a constructor have a return type, then that constructor
will become a normal Method.

2)Can we have a Synchronized keyword on a Constructor?
Ans: No, We should allow two threads to create a new Objects at same time.

3) What are the Restrictions on overriding a Method in Java?
Ans :
   1) The Overriding method in the sub class should have the same return type.
   Example :
     Method in Super class:

   protected String overrideme(){
 System.out.println(" I am Over riding in my Sub Class");
 return null;
  }

Override Method in Sub-Class.

 protected void overrideme(){   
  System.out.println(" I am Over riding in my Sub Class");
  
  }
Observation : The Return types are not matched.

Restriction 2 : Cannot reduce the visibility of the override method.

    Method in super class:

  protected String overrideme(){   
 System.out.println(" I am Over riding in my Sub Class");
 return null;
  }

  Method in Sub Class :

private String overrideme(){
System.out.println(" Method Overriding");
return null;
}

Observation : In Sub-class we trying to decrease the visibility from Protected to private.

Restriction 3 :
The overriding method must not throw new or broader checked exceptions.

Example :  Method in Super class : 
public static FileInputStream f1(String fileName)
  throws FileNotFoundException
{
  FileInputStream fis = new FileInputStream(fileName);
  System.out.println("f1: File input stream created");
  return fis;
}

Example in Method in sub class :

public static FileInputStream f1(String fileName)
    throws ClassNotFoundException
  {
    FileInputStream fis = new FileInputStream(fileName);
    System.out.println("f1: File input stream created");
    return fis;
  }
Observation : Here the overriden method in the sub-class throwing the 
different checked exception from the Super class.
It should not throw a different or new checked Exception in sub class.

Note: But these is not the case with un-checked Exceptions.

Question : What is Virtual and Non Virtual in related to C++ in java?
Ans: In java all methods are default Virtual we can make it non-virtual by adding the
keyword final before it.
consider this Example :
package newPackage;

class Base {
 
    // virtual by default
    public  void show() {
       System.out.println("Base::show() called");
    }
}
 
class Derived extends Base {
    public void show() {
       System.out.println("Derived::show() called");
    }
} 
public class ThreadPool {
    public static void main(String[] args) {
        Base b = new Derived();
        b.show();
    }
}
We can make it non virtual by adding final keyword.
final (non-virtual Methods) cannot be overridden.

Question: Explain the Abstraction OOP concept with Example?
Ans:  
Abstraction is the process of reducing the object to it's essence, so that only the 
necessity elements can be represented.

Abstract defines an object in-terms of it's attribute and behavior.

Example of Customer:
Requirements of customer from customer side.

1) customer name, customer id , password.address.account number and branch.
from these requirements we can create a three class.
class1:
customer class: contains customer-id, customer name,password.
class2:
address class : contains country,pin,street.
class3:
account details : contains branch,bank, account number,account status.

Advantages of Abstraction :
To reduce reality complex, and design should be the loosely coupled.
in the above we are segregating the all necessary information into 3 classes, is called 
the loosely coupled.
Abstraction talks more about the design,how we are going to implement.

Example of Abstraction : TV remote, the customer can see only the buttons, but does not 
care about the chip and all.

Abstraction means hiding the complexity of data or unnecessary data.
Abstraction solves the problem in the design.
Abstraction is about ignoring the things that don't matter so you can focus on the things
 that do matter.

Explain the Difference between C++ and Java Programming language?
Ans :  
Differences :
1) java Does not support the keywords : typedef and or preprocessor.
2) Global functions and global data not allowed in Java.
3)In java all classes are inherited from java, there is no significant concept in C++.
4)The interface concept does not support in C++.
5)Java does not support multiple inheritance.
6) Java Does not support goto statement, in the place it support's labeled break and 
continue statements.
7) Java does not support Operator overloading.
8) Unlike c++ java string's are immutable.
9)Conditional expressions in Java must evaluate to boolean rather than to integer, as is
 the case in C++. Statements such as if(x+y)... are not allowed in Java because the conditional expression doesn't evaluate to a boolean.

Similarities :
1) Both java and C++ support the static methods and static variables.
2)Like C++, Java supports constructors that may be overloaded.
3)Like C++, Java allows you to overload functions. However, default arguments are not 
supported by Java. 

Question : What are the Restrictions in overloading a Method?
Answer :  1_)  Must change the argument list.
                 2_)  can change the return type.
                 3_)  can change the access modifier.
                 4_) can declare a new or a border checked Exception.
Note : We cannot Override the static methods.
            We cannot override the final Methods.

Note: Method Overloading cannot be done based only  on the return type.
Note: And Method Overloading cannot be done based only on the Access specifier.
Example :
 public void call(){
}
private void call(){
}
Show's a checked Exception saying that Duplicate Methods.

Cloning in Java

what is cloning in Java?
Ans : Cloning is process of creating a java object using the same another java object.
Example:
 line 10:  Class CloneMyObject
 line 20:{
 line 30:  int x;
 line 40:   int y;
 line 50:  public static void main(String[] args)
 line 60: {
 line 70:      CloneMyObject ob1 = new CloneMyObject();
 line 80:      ob1.x = 500;
 line 90:      ob1.y = 900;
 line 100:    System.out.println("ob1.x = "+ob1.x+" ob1.y = "+ob1.y);
 line 110:    CloneMyObject  ob2 = (CloneMyObject ) ob1.clone();
 line 120:    System.out.println("ob2.x = "+ob2.x+" ob2.y = "+ob2.y);
 line 130: }
 line 140: }
Explanation : In line 110 we are cloning the object of class "CloneMyObject" but
above program will through an Exception :"java.lang.CloneNotSupportedException"
Reason : Because class Doesn't implement the interface marker interface "Cloneable"
So edit the line 10 like this : "Class CloneMyObject implements Cloneable"

Next Observation : In line 110 we are typecasting the created object to the
class  "CloneMyObject."

Do we really need to typecast the new cloned object to class ?
Ans : YES, the method clone is present in the class Object,  that creates
 same like the object, on which the clone method called. and returns 
 the generic object, there we need to Typecast it Explicitly.


Then how come we get rid off it ?
Ans : Easy, we need to override the method "clone()" in your class, 
to return the object of type of your class.
Example: 
             Class MyClassObject
{
    int x ;
    int y;
   pubic static void main(String[] args)
{
   MyClassObject mcb = new MyClassObject();
   mcb.x = 50;
   mcb.y = 90;
   Syso(" "+mcb.x+" "+mcb.y);
   MyClassObject  mcb2 = mcb.clone();
    Syso(" "+mcb2.x+" "+mcb2.y);
}
public MyClassObject  clone()
{
   return new MyClassObject ();
}
}


Explanation : Overriding the same method which is already present
in the super class , is called " Covariant return types" .


what is the Definition of Covariant return type ?
Ans : What this means is that a method in a subclass may return an object 
whose type is a subclass of the type, returned by the method with the same
signature in the superclass. This feature removes the need for excessive type
 checking and casting.


Question : What is Marker Interface ?
Ans: It is used to mark the classes which support certain capability
Question : What are all Market Interfaces in Java?
Ans: Clonable , Serializable , RandomAccess interface , SingleThreadModel.


Question : What is RandomAccess Interface ?
Answer The RandomAccess interface identifies that a particular java.util.List implementation has fast random access. 


Example List.get() method is faster than repeated access using the Iterator.next() 
method, then the List has fast random access.

Good Java links

HI is the Some of the Good links about the Java :

1) http://www.artima.com/intv/blochP.html

2)This link for C-loaning an java Object.
http://www.java-tips.org/java-se-tips/java.lang/covariant-return-types.html

3)This Link about to tell you what is pass by value for Objects.
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
4) Good Links
http://www.careerride.com/Java-types-of-JDBC-drivers.aspx

Monday, October 25, 2010

Multithreading in Java

Question : What is Thread-based Multitasking?
Ans : Concept of executing more than one functionality simultaneously 
belonging  to the same memory domain(i.e., same program) is known as 
Thread based multi Tasking.


Question : How to Implement thread based multitasking in Java ?
Ans : Using Thread Class and Runnable Interface .


Description : The Runnable interface has a Function definition public void run().
For which we need to provide the body,and execute this functionality as a Thread.


Note : Start() method in the Thread class, recognizes the run() method of 
runnable Interface and then the run() method is executed as a Thread.


Example Program :
Class MSD extends Thread
{
   public void run()
{
   for(int i=0; i<40;i++)
{
 Syso("Inside run method");
}
}
public static void main(String args[])
{
   MSD a = new MSD();
   a.start();
for(int i = 45; i <50;i++)
Syso("sekhar");
}
}
Note: Calling a run method with object of the class, execute the run method as
just a normal method instead of Thread.so we should handover this method to
OS , to start execute this as a thread.


Question : How to handover this run() method to OS to execute it as a Thread?
Ans : By calling the start() method in class Thread.


Note: one class can have only one run() method.
So if we want more threads we need to define more classes, one for each thread.


Note: Output of the Thread Program cannot be guessed,it is based on the
 how the OS schedules the each thread.


Note : In java a class cannot extend two classes simultaneously.


Hierarchy of the Thread classes.
Interface : Runnable has method run();


interface Runnable
{
   public void run();
}


and


Class Thread implements Runnable
{
   public void run() { ----- -------- }
}


Question: How to Create  a Thread in a class,without extending the Thread class?
Answer: By Implementing the Runnable interface.


Question : What is start() method Will do ?
Ans: Remember a start() method,is to handover the run() method present
 in the object  on which the start() method is called to the local OS for scheduling.
once the start method is called then JVM allocated the stack to that thread.
and push the thread from "new" state to runnable state.


Question : In Which class the the Start() method presents?
Ans:   start() presents in the Class Thread.


Excellent Question :
Question : How can we make object of one class available to object of another
 class without using extends Keyword.
ANS: use constructor.


Observe the Below Program for better Explanation.


Class ThreadA implements Runnable
{
  public void run()
{
   Syso("Creating thread without extending thread class");
}
public static void main(String[] args)
{
  ThreadA obj = new ThreadA();
  Thread   threadObj = new Thread();
  threadObj .start();
}
}


Description:
we are creating a thread by implementing a Runnable interface, in-order to 
make run() method as a thread we need to have start method. But start method
present on thread class,and run() method present on the class ThreadA.


If we call threadClassObject.start(), the JVM will checks whether any run() is
there on the object threadClassObject. here is there is no run() method on the
object, threadClassObject.It has one run() method that is on the object ThreadA() class.


Question: How come object of one class can access the object of another class.
Ans: As i said earlier, it uses the constructor.


so by passing the object of class ThreadA(),we can access the object of class 
ThreadA.


Thread threadClassObject = new Thread(ThreadAclassObject);


Now thread class object can access the object of ThreadA class and can call the
method run() on the object ThreadA.


This is called Runnable Target.


Question : How to Control the Execution of a Thread?
Ans :
                 A Thread can be suspended in 3 ways.
1) Based on time, by using sleep(non-seconds) .
Note: Sleep() method can through a checked Exception, so we should put sleep()
method in try -- catch block.
2)Conditionally.
Two threads thread t1, thread t2 were present.
we can suspend the execution of thread t2 until thread t1 finishes it's execution.
by using join() function.
3) UN-Conditionally.
Using the non static method suspend() of the thread class.
Note: suspended thread can resume back by using the method resume().
Note: But resume()  and  suspend() methods are deprecated.Instead of those,
wait() and notify() methods of object class came into existence.


Note: Join() Method in Java used for conditional suspension of a thread.
Note:  wait() method works only in synchronized block.


Note: Constructor of thread class is defined to accept object of runnable interface.


Note: Always a notify() should be called before the wait() method.


Note: notify() method resumes only one thread which was already in wait state.


Note: notifyall() method resumes all threads which are in wait state.


Question: If more number of threads present in the wait() state, what order
 in which the notify() method will resume the threads.
Ans: Resuming the threads which are in wait() state is completely depends on OS.


Question: How to Overcome the above problem.
Ans: Assign priorities to threads.


Question: What is the possible priority values for the threads?
Ans : Ranges from 1 to 9 .


Question: How the Os schedules the Threads?
Ans: Os will never schedule the threads depending on the Priority.


Question : What is the default priority of the threads?
Ans: 5,  because all threads are spawn from the main thread only , all threads 
have the default priority of the parents.


Note: As long as the thread JVM executes, the garbage collector will also be 
in Execution.


Question : What is the datatype for the parameter of the sleep() method?
Ans: long.


Question : Which method waits for a thread to die?
Ans: join() method.


Question : What happens when start() method is called on an already running
 thread?
Answer: IllegalStateException is thrown

Question : Which is best approach to create a thread implementing Runnable 
        or extending Thread?
A: Implementing Runnable. Because we still have opportunity to extend another 

class as  well as implement  more interfaces.

Note: If a Class Extends the Thread Class,  then there is no necessity to that
 class  to override the  run() method in thread Class.
Example: Class ThreadA extends Thread
{
    /* public void run(){
   System.out.println("Still Fine Without the run Method");
}*/
}
Question :What is the difference between process and thread?
A thread is a separate path of execution in a program. A Process is a program in execution.

Qns : ThreadPool Implementation in Java?
This Topic is left.
Refer this Article : http://java.sun.com/developer/Books/javaprogramming/threads/chap13.pdf
http://www.informit.com/articles/article.aspx?p=30483&seqNum=6

A Good Article On Threads in Java ..


http://www.java-questions.com/Threads_interview_questions.html

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...