Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Producer-Consumer Problem in Java | Java Thread interview question for Experinced developer

The producer-consumer problem is one of the most frequently encountered problems when we attempt multi threaded programming. While not as challenging as some of the other problems in multi-threaded programming, an incorrect implementation of this problem can create a mess of your application. Produced items will be left unconsumed, starting items will be skipped, consumption depends on whether the production began earlier or later than consumption attempts etc. To add to this you might notice the anomalies long after it has actually happened and most importantly like almost all multi-threaded programs, this one is hard to debug and reproduce too.
So in this post I thought I would attempt to solve this problem in Java with the help of Java' awesome java.util.concurrent package and its classes.
First of all, let us see the characteristics of the producer-consumer problem:
  • Producer(s) produce items.
  • Consumer(s) consume the items produced by the producer(s).
  • Producer(s) finish production and let the consumers know that they are done.
Note that in this producer-consumer problem the producer is running on a different thread than the ones on consumer. This setup makes sense in two cases:
  • The steps to do the consumption of the item produced in independent and not dependent on other items.
  • The time to process the items is larger that the time to produce them.
The term "larger" in the second point is used a bit loosely. Consider the case where producer reads a line from a file and the "consumption and processing" is just to log the line in a special format back to a file then the use of a producer consumer problem solution can be considered a case of over-engineering a solution. However if for each of those lines the "consumption and processing" step is to make a HTTP GET/POST request to a web-server and then dump the result somewhere then we should opt for a producer-consumer solution. In this case I am assuming that all the data to do a GET/POST is available in the line (item) itself and we are not dependent on previous/next lines.
So let us first take a look at the characteristics of the producer-consumer problem solution that I have posted below:
  • There can be multiple producer.
  • There will be multiple consumers.
  • Once the production of new items is done the producer(s) will let the consumers know so that the consumer will exit after the last item is consumed and processed.
It is interesting to note that to solve this problem at a generic level we can address only the consumer side and not the producer side. This is because the production of items might be done at any time and there is very little that we can do in a generic way to control the production of items. We can, however control the consumer's behaviour while accepting items from producer(s). Having laid out the rules let us take a look at the consumer contract:


  1. package com.maximus.producerconsumer;  
  2.   
  3. public interface Consumer  
  4. {  
  5.  public boolean consume(Item j);  
  6.    
  7.  public void finishConsumption();  
  8. }   

Here the consumer can be shared between multiple producers of similar items; by similar items I mean producer that produces objects of type "Item". The definition if Item is as follows:


  1. package com.maximus.consumer;  
  2.   
  3. public interface Item  
  4. {  
  5.  public void process();  
  6. }  
Now we take a look at an implementation of the Consumer interface:

  1. package com.maximus.consumer;  
  2.   
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5. import java.util.concurrent.BlockingQueue;  
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8. import java.util.concurrent.LinkedBlockingQueue;  
  9.   
  10. public class ConsumerImpl implements Consumer  
  11. {  
  12.  private BlockingQueue< Item > itemQueue =   
  13.   new LinkedBlockingQueue< Item >();  
  14.    
  15.  private ExecutorService executorService =   
  16.   Executors.newCachedThreadPool();  
  17.    
  18.  private List< ItemProcessor > jobList =   
  19.   new LinkedList< ItemProcessor >();  
  20.    
  21.  private volatile boolean shutdownCalled = false;  
  22.     
  23.  public ConsumerImpl(int poolSize)  
  24.  {  
  25.   for(int i = 0; i < poolSize; i++)  
  26.   {  
  27.    ItemProcessor jobThread =   
  28.     new ItemProcessor(itemQueue);  
  29.      
  30.    jobList.add(jobThread);  
  31.    executorService.submit(jobThread);  
  32.   }  
  33.  }  
  34.    
  35.  public boolean consume(Item j)  
  36.  {  
  37.   if(!shutdownCalled)  
  38.   {  
  39.    try  
  40.    {  
  41.     itemQueue.put(j);  
  42.    }  
  43.    catch(InterruptedException ie)  
  44.    {  
  45.     Thread.currentThread().interrupt();  
  46.     return false;  
  47.    }  
  48.    return true;  
  49.   }  
  50.   else  
  51.   {  
  52.    return false;  
  53.   }  
  54.  }  
  55.    
  56.  public void finishConsumption()  
  57.  {  
  58.   shutdownCalled = true;  
  59.     
  60.   for(ItemProcessor j : jobList)  
  61.   {  
  62.    j.cancelExecution();  
  63.   }  
  64.     
  65.   executorService.shutdown();  
  66.  }  
  67. }  

Now the only point of interest is the ItemProcessor that the consumer internally uses to process the incoming items. ItemProcessor is coded as follows:

  1. package com.maximus.consumer;  
  2.   
  3. import java.util.concurrent.BlockingQueue;  
  4. import java.util.concurrent.TimeUnit;  
  5.   
  6. public class ItemProcessor implements Runnable  
  7. {  
  8.  private BlockingQueue< Item> jobQueue;  
  9.    
  10.  private volatile boolean keepProcessing;  
  11.     
  12.  public ItemProcessor(BlockingQueue< Item > queue)  
  13.  {  
  14.   jobQueue = queue;  
  15.   keepProcessing = true;  
  16.  }  
  17.    
  18.  public void run()  
  19.  {  
  20.   while(keepProcessing || !jobQueue.isEmpty())  
  21.   {  
  22.    try  
  23.    {  
  24.     Item j = jobQueue.poll(10, TimeUnit.SECONDS);  
  25.       
  26.     if(j != null)  
  27.     {  
  28.      j.process();  
  29.     }  
  30.    }  
  31.    catch(InterruptedException ie)  
  32.    {  
  33.     Thread.currentThread().interrupt();  
  34.     return;  
  35.    }  
  36.   }  
  37.  }  
  38.    
  39.  public void cancelExecution()  
  40.  {  
  41.   this.keepProcessing = false;  
  42.  }  
  43. }   
The only challenge above is the condition in the while loop. The while loop is so written to support the continuation of the consumption of items even after the producer(s) have finished production and has notified the consumer that production is finished. The above while loop ensures that consumption of all the items is done before the threads exit.This will be the case when producers run faster that consumers.

The above consumer is thread-safe and can be shared multiple producers such that each producer may concurrently call consumer.consume() without bothering about synchronization and other multi-threading caveats. Producers just need to submit an implementation of the Item interface whose process() method will contain the logic of how the consumption will be done.

As a bonus for reading the post I put forward a test program that demonstrates how to use the above classes:



  1. package com.maximus.consumer;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStreamReader;  
  7.   
  8. public class Test  
  9. {  
  10.  public static void main(String[] args) throws Exception  
  11.         {  
  12.          Consumer consumer = new ConsumerImpl(10);  
  13.            
  14.          BufferedReader br =   
  15.           new BufferedReader(  
  16.           new InputStreamReader(  
  17.           new FileInputStream(  
  18.           new File(args[0]))));  
  19.            
  20.          String line = "";  
  21.            
  22.          while((line = br.readLine()) != null)  
  23.          {  
  24.           System.out.println(  
  25.            "Producer producing: " + line);  
  26.           consumer.consume(new PrintJob(line));  
  27.          }  
  28.            
  29.          consumer.finishConsumption();  
  30.         }  
  31. }  
  32.   
  33. class PrintJob implements Item  
  34. {  
  35.  private String line;  
  36.    
  37.  public PrintJob(String s)  
  38.  {  
  39.   line = s;  
  40.  }  
  41.    
  42.  public void process()  
  43.  {  
  44.   System.out.println(  
  45.    Thread.currentThread().getName() +   
  46.    " consuming :" + line);  
  47.  }  
  48. }  
The above consumer can be tweaked in a host of different ways to make it more flexible. We can define what the consumer will do when production is done. It may be tweaked to allow batch processing but I leave that to the user. Feel free to use it and twist it in whatever way you want.

Most common error : java.lang.UnsupportedClassVersionError: when is it thrown by a JVM & how to resolve it | Experinced level java interview question

UnsupportedClassVersionError is (evidently a descendant of the Error class in Java) which subclasses java.lang.ClassFormatError which in turn subclasses java.lang.LinkageError (which is a direct subclass of java.lang.Error). This error is thrown in the cases when the JVM (Java Virtual Machine) attempts to read a class file and finds that the major and minor version numbers in the particular class file are not supported. This happens in the cases when a higher version of Java Compiler is used to generate the class file than the JVM version which is used to execute that class file. Please do notice that this is not true vice-versa which means you can comfortably use a higher version of JVM to run a class file compiled using an earlier version of Java Compiler. Let’s understand why? We'll see below a valid Java program and subsequently an alert and a stack trace of the error which are thrown as a result of the above explained situation which causes UnsupportedClassVersionError. FYI: The output

public class TestFinally {

      public static void main(String[] args) {
             
            try{
                  try{
                        throw new NullPointerException ("e1");
                  }
                  finally{
                        System.out.println("e2");
                  }
            }
            catch(Exception e){
                        e.printStackTrace();
            }
      }
}



The error alert and the stack trace if the right JVM is not used



java.lang.UnsupportedClassVersionError: TestFinally (Unsupported major.minor version 49.0)
      at java.lang.ClassLoader.defineClass0(Native Method)
      at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
      at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
      at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
      at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
      at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
      at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)


The minor and major version numbers are represented by the major_version and minor_version items respectively in a Java Class File structure. A combination of these two unsigned integers (both of length 2 bytes each) determines the particular version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m.

As per Java VM Spec, “A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.” For example: Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.

Major version number of the class file formats of the popular Java versions are: J2SE 6.0 = 50, J2SE 5.0 = 49, JDK 1.4 = 48, JDK 1.3 = 47, JDK 1.2 = 46, JDK 1.1 = 45. Now you understand what in our example “major.minor version 49.0” signifies? It simply means we have used J2SE 5.0 for compiling the source code as the class file format is 49.0 where major_version is ‘49’ and minor_version is ‘0’.

Errors are never detected at compile time. This is quite easier to understand in this case – how can the compiler have the information at the time of compilation about which version of JVM would be used execute the compiled class file? It can't, right? So is the case with other errors as well. This is the reason why all the Errors are unchecked. The error alert also rightly shows that it's a JVM Launcher error.

How to resolve UnsupportedClassVersionError?


Whenever you encounter this error, do check if you’re using an earlier version of JVM to execute the class file than the corresponding version of compiler you used to compile the source code. The example shown here was compiled using Java 5.0 compiler, but when I tried to run using JVM 1.4, I got the above error. I just needed to switch either to a JVM version 5.0 or above OR needed to switch to a Java Compiler of JDK 1.4 or below (you of course need to make sure the source code is compatible with the corresponding version of the compiler otherwise you’ll start getting other compiler errors).

A higher JVM version doesn’t cause a problem in most of cases unless the class file format is quite old (and hence doesn’t lie in the supported range as specified by Sun for that particular JVM version ... as discussed above). But, it’s always a good practice to have both the Compiler and the JVM of the same version.

How to get name of a Class in Java from within a static method | Fresher level java interview Question

One of our regular visitors (Ranvijay) had asked it a couple of days back. Though, the code is pretty straightforward, I think it might help few others if posted as an article.

One of the many possible ways of finding the name of the class in Java from within a static method is by using a static nested class, which will have a public instance method returning the class name of the enclosing class (in our case the class where we have the particular static method).


public class GetClassNameInStaticMethod {

public static void main(String[] args) {
 // Calling a Static Method
 System.out.println("Current Class Name: " + getCurClassName());
}
public static String getCurClassName(){
 return (new CurClassNameGetter()).getClassName();
}

//Static Nested Class doing the trick
public static class CurClassNameGetter extends SecurityManager{
 public String getClassName(){
  return getClassContext()[1].getName();
 }
}
}

Output

Current Class Name: GetClassNameInStaticMethod

Java : Connecting to an HTTP Web Service from VBA Excel via a Proxy Server

Though MSDN suggests using stubs generated from the WSDL by MS Soap Toolkit for connecting to an HTTP Web Service from within VBA Excel, but it might not work as you would like it to, especially for a SOA-compliant web service and particularly in the cases where you need to access the service via a Proxy Server.

I have used the SOAP Connector called 'httpConnector30' successfully to connect to an HTTP Web Service without any issues. This connector is a part of the Microsoft SOAP Library named MSSOAPLib30 and you got to make sure that this library is referenced in your Excel installation. If it's not already there in your excel, just add the corresponding DLL and you're done.

Using httpConnector30 is different from consuming a Web Service by creating the stubs using MS Soap Toolkit. 'httpConnector30' requires you to specify the actual Web Service URL whereas the toolkit asks you the WSDL url and creates stubs accordingly, which you use in your VBA code. I personally think using 'httpConnector30' is easier and more straightforward if you have the service url.

Before we jump on to the code listed below, let's understand what all the code does broadly:-

    Instantiating the SOAP Connector
    Setting up the Proxy Server and Port (if access needed via Proxy)
    Setting up the Web Service URL (not WSDL url)
    Setting up Timeout period for the service call
    Setting up the SOAP Action i.e., the actual method to be called
    Beginning SOAP Message and getting connector's Input Stream
    Building up the SOAP Request (as per your Web Service definition)
    Sending the SOAP Message (this is where the service call is made)
    Initializing the SOAP Reader and reading the SOAP Response

Note: in the below code I have not shown the exception handling blocks, which you should include to grab and handle the potential errors gracefully. For example: you should first check the 'connector' as 'Not Nothing' before trying to load the 'reader' with connector's output stream.

Additionally, I've assumed that the first node (except the generic envelope and body) of the SOAP Response is actually a List and hence I've put a loop to iterate through it. 'Set response = reader.RPCResult.childNodes' actually sets the 'response' to the first node of the SOAP Response as read from the reader (which itself is loaded with the connector's output stream).

Just to make your service consumption code robust and independent of the Response Structure changes (like addition of new nodes and/or reordering of nodes), in your client code, you should iterate through all the SOAP Response nodes and compare the current node name with your Service Response node names (you can get them in the service WSDL) and subsequently handle the particular node, say inside an if-block. This will make sure that your code doesn't fail abruptly in case Service Response Structure changes. For example: it will avoid any code failure say because you had written it assuming the first node in the response was a List and let's say the service response structure changes make it the second node in the response - maybe because the service provider needed to add another field in the response and also wished to make that the first field. I know the service provide will certainly let the client developers know about the changes, but if you make your code flexible to such possible changes, nothing like it... right?


Public Sub HTTPConnectivityTest()
 
   'Instantiating the SOAP Connector
   Dim connector As New MSSOAPLib30.HttpConnector30
 
   'Setting up the Proxy Server and Port
   connector.Property("ProxyServer") = "fully-qualified-proxy-server-or-IPAddress:Port"

 
   'Setting up the Web Service URL
   connector.Property("EndPointURL") = "http://web-service-server:port/webservices/SampleService.v1"
 
   'Setting up Timeout period for the service call
   connector.Property("Timeout") = 2000 '2 minutes
 
   'Setting up the SOAP Action i.e., the actual method to be called
   connector.Property("SoapAction") = "urn:getSampleData"
 
   'Beginning SOAP Message
   connector.BeginMessage
 
   'Initializing SOAP Serializer with connector's input stream
   Dim writer As New MSSOAPLib30.SoapSerializer30
   writer.Init connector.InputStream

   'Building the SOAP Request - envelope and body
   writer.startEnvelope              ' <SOAP-ENV:Envelope>
   writer.startBody                  ' <SOAP-ENV:Body>

   'Populating the SOAP Request with actual input parameters
   writer.startElement "SampleServiceRequest", "service namespace", , "s3"   ' <SampleServiceRequest>
 
   writer.startElement "inputParam1"   ' <inputParam1>
   writer.writeString "param1 value"    ' value of inputParam1
   writer.endElement                 ' </inputParam1>

   writer.startElement "inputParam2"   ' <inputParam2>
   writer.writeString "param2 value"        ' value of inputParam2
   writer.endElement                 ' </inputParam2>

   writer.startElement "inputParam3"   ' <inputParam3>
   writer.writeString "param3 value"        ' value of inputParam3
   writer.endElement                 ' </inputParam3>

   'Populating list-type parameter
   writer.startElement "paramList"   ' <paramList>

    'Adding node #1 to the list-type param
    writer.startElement "paramListNode"    ' <paramListNode>
     writer.startElement "nodeParam1"          ' <nodeParam1>
      writer.writeString "value1"                    ' value of nodeParam1
     writer.endElement                          ' </nodeParam1>
 
     writer.startElement "nodeParam2"          ' <nodeParam2>
      writer.writeString "value1"                    ' value of nodeParam2
     writer.endElement                          ' </nodeParam2>
    writer.endElement                          ' </paramListNode>

    'Adding node #2 to the list-type param
    writer.startElement "paramListNode"    ' <paramListNode>
     writer.startElement "nodeParam1"          ' <nodeParam1>
      writer.writeString "value2"                    ' value of nodeParam1
     writer.endElement                          ' </nodeParam1>
 
     writer.startElement "nodeParam2"          ' <nodeParam2>
      writer.writeString "value2"                    ' value of nodeParam2
     writer.endElement                          ' </nodeParam2>
    writer.endElement                          ' </paramListNode>
 
   'Population of list-type param ends here
   writer.endElement                          ' </paramList>

   'Finishing the SOAP Request
   writer.endElement                 ' </SampleServiceRequest>
   writer.endBody                    ' </SOAP-ENV:Body>
   writer.endEnvelope                ' </SOAP-ENV:Envelope>
 
   'Sending the SOAP Message (this is where the service call is made)
   connector.EndMessage
 
   'Defining SOAP Reader and initializing it with connector's output stream
   Dim reader As New MSSOAPLib30.SoapReader30
   reader.Load connector.OutputStream
 
   'Parsing the SOAP Response
   Dim response As MSXML2.IXMLDOMNodeList

   'Setting the response to the first node of the SOAP Response
   Set response = reader.RPCResult.childNodes
   Dim node As MSXML2.IXMLDOMNode

   'Iterating through the first node of SOAP Response knowing it is a list
   For Each node In response
    Dim nodeName As String
    Dim nodeValue As String
 
    nodeName = node.nodeName
    nodeValue = node.nodeTypedValue
 
    'Showing the Node Name and Value on Alert Boxes
    MsgBox node.nodeName & ": " & node.nodeTypedValue
   Next node
End Sub

Java concept : Abstract Class and Interface Interview Questions Answers in Java

 Abstract class and interface is very popular in any object oriented programming language or Java interview, and there are always one or more questions from this. Interface is more common, because of its popularity among designers but questions from abstract class also pops up now and than. Interview questions from abstract class is more common on junior level or you say under 2 years experience of  Java programmers, while interface related questions are mostly asked on senior level Java interview e.g. 4 or 6 years of experience. They are mostly asked along with other Java design pattern questions, e.g. Decorator pattern or Factory pattern . Any way, in this article we will see mix of these interview questions from abstract class and interface. All questions has been asked in various Java interviews and difficulty level for these question is easy for most of Java developer. It’s mostly fact based questions, but some questions like difference between abstract class and interface in Java, and when to prefer abstract class over interface can be really tricky.


Frequently asked Abstract class and Interface questions in Java

Java abstract class and interface interview Question answersHere is my list of questions, this not only explains rules related to abstract class but also shares some tricky questions about using abstract class and interface. If you have asked any question on this topic, which you don’t see in this list, than please share with us as comment


1) Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class,  constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation. Also even if you don’t provide any constructor, compiler will add default no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.

2) Can abstract class implements interface in Java? does they require to implement all methods?
Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods,  concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly. It’s best of both world, you can get advantage of interface for declaring type, and flexibility of abstract class to implement common behavior at one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.


3) Can abstract class be final in Java?

No, abstract class can not be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class from being extended. In real world also, abstract signifies incompleteness, while final is used to demonstrate completeness. Bottom line is, you can not make your class abstract and final in Java, at same time, it’s a compile time error.

4) Can abstract class have static methods in Java?
Yes, abstract class can declare and define static methods, nothing prevents from doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in a object oriented design, because static methods can not be overridden in Java. It’s very rare, you see static methods inside abstract class, but as I said, if you have very good reason of doing it, then nothing stops you.


5) Can you create instance of abstract class?

No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract,  you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.

6) Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance. By the way, it’s debatable whether you should have abstract method inside abstract class or interface. In my opinion, abstract class should have abstract methods, because that’s the first thing programmer assumes, when he see that class. That would also go nicely along principle of least surprise.

7) Difference between abstract class and interface in Java?
This is the most important and one of the classic Java Interview question. I don’t know, how many times I have seen this question at all most all levels of Java interviews. One reason, which makes this question interesting is ability to produce example. It’s easy to answers questions on core OOPS concepts like Abstraction, Encapsulation, Polymorphism and Inheritance, but when it comes to subtle points like this, candidate more often fumbled. You can see this post for all syntactical difference between abstract class and interface, but it deserve a post on it’s own.

8) When do you favor abstract class over interface?
This is the follow-up of previous interview questions on abstract class and interface. If you know syntactical difference, you can answer this question quite easily, as they are the one, which drives the decision. Since it’s almost impossible to add a new method on a published interface, it’s better to use abstract class, when evolution is concern. Abstract class in Java evolves better than interface. Similarly, if you have too many methods inside interface, you are creating pain for all it’s implementation, consider providing an abstract class for default implementation. This is the pattern followed in Java collection package, you can see AbstractList provides default implementation for List interface.

9) What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration.  All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

                public void abstract printVersion();

Now, In order to implement this method, you need to extend abstract class and override this method.

10) Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.

Java Clone() concept | how clone work in java | java clone interivew question answer

First of all Java clone() method has given in Object class with below
protected Object clone() throws CloneNotSupportedException

with above definition some time in interview question you will found like
  • Why clone() method has given in Object class
  • What is the reason behind to make clone() method protected
  • What meaning of CloneNotSupportExeption
  • What is Shallow cloning and deep cloning

Definition
Clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Use of Cloneable interface
 
We get CloneNotSupportedException if we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface. This interface is a marker interface and the implementation of this interface simply indicates that the Object.clone() method can be called on the objects of the implementing class.

Java clone() concept


1. Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.  The assignment of one reference to another merely creates another reference to the same object.
2.  When you don't want to modify the method caller's (or original) object.
 Different analysis on same set of data in an Object. Rather than fetching the data again and again, populate object once and clone it for a new analysis.
 Games - walls, doors, cars graphics - clone the object, change the params.
3.For any class to able to be cloned .clone() - it MUST implement java.lang.Cloneable interface. Otherwise is .clone is used, it throws java.lang.CloneNotSupportedException at runtime.
  It is a marker interface - which simply tells JVM that the Object.clone() method can be called on the objects of this or sub classes.
4. Shallow Copy - see clone() method in below code
 This is a result of the default cloning functionality provided by the Object.clone()
 When this is used, it copies the primitives and the references. Only references are copied to new cloned Object. Actual referenced object remains as it. That means, the member references in original and cloned object - point to same object.
 
5.  Deep Copy - see deepClone() method in below code
 Copy the actual member objects along with primitives and member references.
 We need to override the clone() method in order to achieve it. But need to make sure that member Objects that we are trying to copy, should also implement Cloneable, only then then can be cloned.
 
 
public class Clones {
public static void main(String[] args) throws CloneNotSupportedException {
Person p1 = new Person("AAA", 123, 100, 200);
System.out.println("Original");
System.out.println(p1.salary.basic);
Person p2 = (Person) p1.deepClone();
//p2.name = "BBB";
//p2.salary.basic = 2222;
System.out.println(p1.equals(p2));
System.out.println("Clone");
System.out.println(p2.salary.basic);
System.out.println("Original");
System.out.println(p1.salary.basic);
}
}
// cloneable class implements Cloneable
class Person implements Cloneable {
public String name = null;
public int id = 0;
public Salary salary = null;
public Person(String name, int id, int basicSal, int bonusSal) {
this.name = name;
this.id = id;
// using Object type member to test for cloning
Salary sal = new Salary();
sal.basic = basicSal;
sal.bonus = bonusSal;
this.salary = sal;
}
// shallow copying
protected Object clone() throws CloneNotSupportedException {
// This is default cloning provided by the Object.clone()
return super.clone();
}
// deep copying
protected Object deepClone() throws CloneNotSupportedException {
// The clone() method produces an Object, which must be recast to the proper type
Person p = (Person) super.clone();
// In deep cloning, we also clone the member objects, but for this to work - //member objects should be Cloneable
p.salary = (Salary) p.salary.clone();
return p;
}
}
// member object of Person class as Cloneable. If it was not, then deep cloning //would not have been possible
class Salary implements Cloneable {
public int basic = 0;
public int bonus = 0;
public int getSalary() {
return basic + bonus;
}
// implementing clone()
protected Salary clone() throws CloneNotSupportedException {
Salary s = (Salary) super.clone();
return s;
}
}
// Cloneables with final fields - not meant go together. No error, but when try //to change, it cribs.
// The only solution is to remove the final modifier from the field, giving up //the benefits the modifier conferred.