Friday, May 24, 2013

Difference between Deep Copy and Shallow Copy in Java Object cloning

Shallow copy and deep copy is related with cloning process so before go into the deep of shallow and deep copy we need to understand what is clone in java. Clone is nothing but the process of copying one object to produce the exact object, which is not guaranteed. We all know in Java object is referred by reference we can not copy one object directly to another object. So we have cloning process to achieve this objective. Now one question arise in mind why we need this process so the answer is whenever we need local copy of the object to modify the object in some method but not in method caller.  So we can define Cloning as “create a copy of object  .I think now we are some how clear about the cloning but there  is more on it depending upon how we are doing this copy, we can divide cloning in two types.
  • Shallow Copy
  • Deep Copy
Before going into the deep of shallow and deep copy we need to understand how we achieve cloning in java.

How will you achieve cloning in java?

Difference between deep cloning vs shallow cloning in JavaIn Java everything is achieved through class, object and interface .By default no Java class support cloning but Java provide one interface called Cloneable, which is a marker interface and by implementing this interface we can make duplicate copy of our object by calling clone() method of  java.lang.Object class. This Method is protected inside the object class and Cloneable interface is  a marker interface and this method also throw  CloneNotSupportedException if we have not implement this interface and try to call clone() method of Object class.  By default any clone() method gives shallow copy of the object i.e. if we invoke super. clone() then it’s a shallow copy but if we want to deep copy we have to override the clone() method and make it public and give own definition of making copy of object. Now we let’s see  what is shallow and deep copy of object in Java programming language.

Shallow Copy

Whenever we use default implementation of clone method we get shallow copy of object means it create new instance and copy all the field of object to that new instance and return it as object type we need to explicitly cast it back to our original object. This is shallow copy of the object. clone() method of the object class support shallow copy of the object. If the object contains primitive as well as non primitive or reference type variable In  shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references gets copied and not the referred objects themselves. That's why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects are there then there is no difference between shallow and deep copy in Java.

Deep Copy

Whenever we need own meaning of copy not to use default implementation we call it as deep copy, whenever we need deep copy of the object we need to implement according to our need. So for deep copy we need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class. After that we override the clone() method in all those classes even in the classes where we have only primitive type members otherwise we would not be able to call the protected clone() method of Object class on the instances of those classes inside some other class. It’s typical restriction of the protected access.

Difference between Shallow and Deep Copy in Java

I think now we know what is deep and shallow copy of object in Java, let see some difference between them so that we can get some more clarity on them.
  •  When we call Object.clone(), this method performs a shallow copy of object, by copying data field by field, and if we override this method and by convention first call super.clone(), and then modify some fields to "deep" copy, then we get deep copy of object. This modification is done to ensure that original and cloned object are independent to each other.

  • In shallow copy main or parent object is copied, but they share same fields or children if fields are modified in one parent object other parent fields have automatic same changes occur,but in deep copy this is not the case.

  • If our parent object contains only primitive value then shallow copy is good for making clone of any object because in new object value is copied but if parent object contains any other object then only reference value is copied in new parent object and both will point to same object so in that case according to our need we can go for deep copy.

  • Deep copy is expensive as compare to shallow copy in terms of object creation, because it involves recursive copying of data from other mutable objects, which is part of original object.

This is all about deep copy and shallow copy of objects in Java. Now the question comes when we use shallow copy and when go for deep copy , so answer would be  simple that if the object has only primitive fields or Immutable objects, then obviously we will go for shallow copy, but if the object has references to other mutable objects, then based on the requirement, shallow copy or deep copy can be chosen. Means  if the references are not modified anytime, then there is no point in going for deep copy, We can go for shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

Hope this article will help to make clear about deep and shallow copy of cloning process.

Related Java Interview Questions articles from Java67 Blog
Difference between ConcurrentHashMap vs HashMap in Java

Saturday, May 18, 2013

Reading input and password from command line in Java using java.io.Console - Example tutorial

Java6 added a new utility class for reading input data from character based devices including command line. java.io.Console can be used to read input from command line, but unfortunately it doesn't work on most of IDE like Eclipse and Netbeans. As per Javadoc call to System.Console() will return attached console to JVM, if it has been started interactive command prompt or it will return null if JVM has been started using a background process or scheduler job. Anyway java.io.Console not only provides way to read input from command prompt or Console but also reading passwords from console without echoing it. Console.readPassword() method reads password and returns a character array and password is masked during entering so that any peeping tom can not see your password while you are entering it. here is a code example of How to read password and input from command prompt or console using java.io.Console. By the way apart from Console, you can also use Scanner or BufferedReader to read input from command prompt, as shown in this example.

Saturday, April 27, 2013

10 Frequently asked SQL Query Interview Questions



In this article I am giving example of some SQL query which is asked when you go for interview who is having one or two year experience on this field .whenever you go for java developer position or any other programmer position interviewee expect that if you are working from one or two years on any project definitely you come across to handle this database query, so they test your skill by asking this type of simple query.

Question 1: SQL Query to find second highest salary of Employee

Answer : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );
 

See How to find second highest salary in SQL for more ways to solve this problem.

Question 2: SQL Query to find Max Salary from each department.

Answer :

SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID.
 

Question 3:Write SQL Query to display current date.

 Ans:SQL has built in function called GetDate() which returns current timestamp.

SELECT GetDate();
 

Question 4:Write an SQL Query to check whether date passed to Query is date of given format or not.

Ans: SQL has IsDate() function which is used to check passed value is date or not of specified format ,it returns 1(true) or 0(false) accordingly.

SELECT  ISDATE('1/08/13') AS "MM/DD/YY";
 

It will return 0 because passed date is not in correct format.

Question 5: Write a SQL Query to print the name of distinct employee whose DOB is between 01/01/1960 to 31/12/1975.

Ans:
SELECT DISTINCT EmpName FROM Employees WHERE DOB  BETWEEN ‘01/01/1960’ AND31/12/1975’;

Question 6:Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.


Answer : SELECT COUNT(*), sex from Employees  WHERE  DOB BETWEEN ‘01/01/1960 ' AND ‘31/12/1975’  GROUP BY sex;

Question 7:Write an SQL Query to find employee whose Salary is equal or greater than 10000.

Answer : SELECT EmpName FROM  Employees WHERE  Salary>=10000;

Question 8:Write an SQL Query to find name of employee whose name Start with ‘M’

Ans: SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of whether it was stored as JOE, Joe, or joe.

Answer : SELECT  * from Employees  WHERE  upper(EmpName) like upper('joe%');

Question 10: Write a SQL Query to find  year from date.

Answer :  SELECT YEAR(GETDATE()) as "Year";

Hope this article will help you to take a quick practice whenever you are going to attend any interview and not have much time to go into the deep of each query.

Other Interview Questions posts from Java67 Blog

Wednesday, April 17, 2013

An Example of Overriding Equals, HashCode and CompareTo method in Java

Though modern IDE like Eclipse, IntelliJ or Netbeans allows you to generate equals, hashCode and compareTo methods for your value classes, it's equally important, you know how to do that by hand. By overriding equals and hashcode method by yourself, you know how they work, what kind of errors you can get, and most importantly, it's expected form you, as a Java programmer in any core Java interview. More often, you would see a coding question in Java, which ask you to override equals(), hashcode(), compare() and compareTo() methods for a value class. Since I have already shared some tips on How to override compareTo method in Java, and couple of example of writing your own comparator in Java, here I am sharing another simple example of overriding equals and hashCode methods. If you know rules of overriding equals and hashCode, you might know that, whenever you override equals, you must have to override hashCode, otherwise your object will not behave properly on various collection classes e.g. Map or Set, which uses equals, compareTo, hashCode to implement there invariants e.g. Set implementations should not allow any duplicates.

Sunday, March 31, 2013

How to Split String in Java with Example using Regular Expression

String class provides split() method to split String in Java, based upon any delimiter, e.g. comma, colon, space or any arbitrary method. split() method splits string based on delimiter provided, and return a String array, which contains individual Strings. Actually, split() method takes a regular expression, which in simplest case can be a single word. split() is also overloaded method in java.lang.String class and its overloaded version takes a limit parameter which is used to control how many times pattern will be applied during splitting process. if this limit is positive n, then pattern will be applied at most n-1 times, if it's negative or zero than split operation is applied any number of time. For example, if we split String "First,Second,Third" on comma and provide limit as 2 then pattern will run one time, and split() will return String array with 2 Strings, "First" and "Second,Third". Since this method accepts a Java regular expression, it throws PatternSyntaxException, if syntax of regular expression is invalid.

Saturday, March 23, 2013

How to replace String in Java - character substring replaceAll example

String class in Java provides several methods to replace characters, CharSequence and substring from String in Java. Since String is immutable in Java, every time you performance an operation on String either replacement or removing white space from String, it generates a new String object. There are four overloaded method to replace String in Java :

replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)

Out of these, 2nd one which takes a CharSequence is added on Java 1.5. CharSequence is actually a super interface for String, StringBuffer and StringBuilder in Java, which means you can pass any of String, StringBuffer or StringBuilder Object as argument to this replace method. replaceFirst() and replaceAll() are very powerful and accepts regular expression. replaceFirst() only replace first match, while replaceAll replaces all matches with replacement String provided.

Tuesday, March 12, 2013

Difference between wait vs notify vs notifyAll in Java

wait, notify, and notifyAll methods are used for inter thread communication in Java. wait() allows a thread to check for a condition, and wait if condition doesn't met, while notify() and notifyAll() method informs waiting thread for rechecking condition, after changing state of shared variable. One good example of how wait and notify method works is Producer consumer problem, where one thread produces, and wait if bucket is full; and other thread consumes and wait if bucket is empty. Both Producer and Consumer thread, notify each other as well. Producer thread notifies consumer thread after inserting an item in shared queue, while consumer thread notify producer, after consuming item from queue. Though Both notify() and notifyAll()  are used to notify waiting threads, waiting on shared queue object, but there are some subtle difference between notify and notifyAll in Java. Well, when we use notify(), only one of the sleeping thread will get notification, while in case of notifyAll(), all sleeping thread on that object will get notified. This concept confuses many Java programmers, both beginners and experienced alike, Infact this is one of three question which is very popular on wait and notify concept, along with why wait and notify is defined in Object class and why wait and notify called from synchronized method. In this article we will focus on difference between wait, notify, and notifyAll method in Java.

Java67 Headline Animator