Top 10 Oracle Interview Question and Answer - Database and SQL

These are some interview question and answer asked during my recent interview. Oracle interview questions are very important during any programming job interview. Interviewer always want to check how comfortable we are with any database either we go for Java developer position or C, C++  programmer position .So here I have discussed some basic question related with oracle database. Apart from these questions which is very specific to Oracle database you may find some general questions related to database fundamentals and SQL e.g. Difference between correlated and noncorrelated subquery in database  or truncate vs delete in SQL etc. Some of the most important topics in Oracle Interview questions are SQL, date, inbuilt function, stored procedure and less used features like cursor, trigger and views. These questions also gives an idea about formats of questions asked during Oracle Interview.

How to compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method.  Since both equals and deepEquals is used for array comparison, what is the difference between them becomes important. The short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array,  on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.

How to append text into File in Java – FileWriter Example

Some times we need to append text into File in Java instead of creating new File. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create file and directory in Java and how to read and write to text file in Java and in this Java IO tutorial we will see how to append text into file in Java. We are going to use standard FileWriter and  BufferedWriter approach to append text to File. One of the key point to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of File rather than writing on beginning of the File. In next section we will see complete Java program to append text into File in Java.  By the way you can also use FileOutputStream instead of FileWriter if you would like to write bytes, instead of text. Similar to FileWriter, FileOutputStream constructor also takes a boolean append argument to open connection to append bytes into File in Java.

Difference between equals method and "==" operator in Java - Interview Question

Both equals() and "==" operator in Java is used to compare objects to check equality but the main difference between equals method and  the == operator is that former is a method and later is an operator. Since Java doesn’t support operator overloading, == behaves identical for every object but equals() is method, which can be overridden in Java and logic to compare objects can be changed based upon business rules. Another notable difference between == and equals method is that former is used to compare both primitive and objects while later is only used for objects comparison. At the same time, beginners struggle to find when to use equality operator (==) and when to use equals method for comparing Java objects. In this tutorial, we will see how equals() method and == operator works in Java and what is the difference between "==" and equals method in Java and finally when to use "==" and equals() to compare objects.

How to add, subtract days, months, years, hours from Date and Time in Java

Adding days, hours, month or years to dates is a common task in Java. java.util.Calendar can be used to perform Date and Time arithmetic in Java. Calendar class not only provides date manipulation but it also support time manipulation i.e. you can add, subtract hours, minutes and seconds from current time. Calendar class automatically handles date transition or month transition for example if you ask date after 30 days it will return you date based on whether current month is 30 or 31 days long. Same is true in case of adding and subtracting years, Calendar takes care whether current or following year is a leap year or not. For example 2012 is a leap year and it has February with 29 days, if you ask Calendar day before 365 it will return 24th July (assuming current date 23rd July) which shows it take care of leap year. By the way there are couple of more date and time related articles e.g. How to find current date and time in Java and How to convert Date to String in Java. If you haven’t read them already, It’s worth checking to know more about Date and Time in Java.

Difference between Primary key vs Foreign key in table – SQL database tutorial

The main difference between Primary key and Foreign key in a table is that it’s the same column which behaves as primary key in the parent table and as a foreign key in a child table. For example in Customer and Order relationship, customer_id is the primary key in Customer table but a foreign key in Order table. By the way, what is a foreign key in a table and difference between Primary and Foreign key are some of the popular SQL interview questions, much like truncate vs delete in SQL or difference between correlated and noncorrelated subquery? We have been learning key SQL concepts along with these frequently asked SQL questions and in this SQL tutorial, we will discuss what is a foreign key in SQL and purpose of the foreign key in any table. By the way, this is the third article related to a primary key in SQL, other being difference between primary and unique key and How to find second highest salary in SQL. If you are preparing for any technical job interview where you expect some SQL questions, check out these questions, they are worth preparing.

How to fix java.lang.classcastexception cannot be cast to in Java - cause and solution

As name suggests ClassCastException in Java comes when we try to type cast an object and object is not of the type we are trying to cast into. In fact ClassCastException in Java is one of most common exception in Java along with java.lang.OutOfMemoryError and ClassNotFoundException in Java before Generics was introduced in Java 5 to avoid frequent instances of java.lang.classcastexception cannot be cast to while working with Collection classes like ArrayList and HashMap, which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by using Generics and writing type-safe parameterized classes and method, its good to know real cause of ClassCastException and How to solve it. In this Java tutorial we will see Why java.lang.ClassCastException comes and how to resolve ClassCastException in Java. We will also see how to minimize or avoid ClassCastException in Java by using Generics, as prevention is always better than cure.

Difference between Class and Object in Java and OOPS with Example

Class and Object are two most important concept of Object oriented programming language (OOPS)  e.g. Java. Main difference between a Class and an Object in Java is that class is a blueprint to create different objects of same type. This may looks simple to many of you but if you are beginner or just heard term Object Oriented Programming language it might not be that simple. I have met many students, beginners and programmers who don’t know difference between class and object and often used them interchangeably. Also Java API having classes like java.lang.Object and java.lang.Class also adds more confusion in beginners mind. Both of them are totally different things, class and object in OOPS are concepts and applicable to all Object oriented programming language e.g. C++ or Scala. On the other hand java.lang.Class and java.lang.Object are part of Java API. Along with other OOPS concepts like Abstraction, Encapsulation, Inheritance and Polymorphism, this is also one of the most fundamental of Object oriented programming (OOPS) which needs to be clearly understood before proceeding into serious application programming. Without clear understanding of Class and Object you are more prone to make errors, not able to comprehend an already written program and it would be pretty hard for you to find bugs or fix errors or exceptions in Java code. By the way difference between class and object is also a popular programming interview question, which is quite frequently asked at fresher level interviews.  In this article we will look this on different angles to differentiate Class and object in Java. Once you get hold of key OOPS concepts, I would recommend to read 10 OOPS and SOLID design principles for Java programmer, which is tried and tested design pattern for writing better code.

How to attach source in eclipse for Jars, debugging and code look-up – JDK Example

Attaching source of any Jar in Eclipse e.g. JDK or open source libraries like Spring framework is a good idea because it help during debugging and code development. As a Java programmer at least you should attach the source of JDK in Eclipse IDE to find out more about JDK classes. Though Eclipse IDE is pretty good on code assist, sometimes You want to know what's going inside a library or a JDK method, rather than just reading the documentation. Interview questions like How HashMap works in Java or How substring cause memory leak can only be answered if you are familiar with the source code of these classes.  Once you attach source code of Java or Spring in Eclipse IDE, You can check code with just a single click. Some one may argue for Java decompiler like JAD which can create source from the .class file which is also a smart way to look code for open source library, but decompiled source file is not same as the original source file, as you lost comment and readability. As per my experience attaching source code corresponding to JAR file is much better than decompiling a class file using JAD decompiler. 

How to find middle element of LinkedList in Java in one pass in Java

How do you find middle element of LinkedList in one pass is a programming question often asked Java and non-Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating the factorial, where Interviewer sometimes also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure i.e. In the case of singly LinkedList, each node of Linked List contains data and pointer, which is the address of next Linked List and the last element of Singly Linked List points towards the null. Since in order to find middle element of Linked List you need to find the length of LinkedList, which is counting elements till end i.e. until you find the last element of Linked List. What makes this data structure Interview question interesting is that you need to find middle element of LinkedList in one pass and you don’t know the length of LinkedList. This is where candidates logical ability puts into the test,  whether he is familiar with space and time trade off or not etc.

Recursion in Java with example – Programming Techniques Tutorial

Recursion is one of the tough programming technique to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview. If you are new in Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion than this tutorial is for you. In this programming tutorial, we will see a couple of example of recursion in Java programs and some programming exercise which will help you to write recursive code in Java e.g. calculating Factorial, reversing String and printing Fibonacci series using recursion technique. For those who are not familiar with recursion programming technique here is the short introduction: "Recursion is a programming technique on which a method call itself to calculate result". It's not as simple as it look and mainly depends upon your ability to think recursively. One of the common trait of recursive problem is that they repeat itself, if you can break a big problem into small junk of repetitive steps then you are on your way to solve it using recursion.

What is Referential Integrity in Database or SQL - MySQL Example Tutorial

Referential Integrity is set of constraints applied to foreign key which prevents entering a row in child table (where you have foreign key) for which you don't have any corresponding row in parent table i.e. entering NULL or invalid foreign keys. Referential Integrity prevents your table from having  incorrect or incomplete relationship e.g. If you have two tables Order and Customer where Customer is parent table with primary key customer_id and Order is child table with foreign key customer_id. Since as per business rules you can not have an Order without a Customer and this business rule can be implemented using referential integrity in SQL on relational database. Referential Integrity will cause failure on any INSERT or UPDATE SQL statement changing value of customer_id in child table, If value of customer_id is not present in Customer table. By the way What is Referential Integrity in SQL is also an important SQL question similar to finding second highest salary in SQL or difference between truncate and delete  and should be prepared well before going for any job interview, where knowledge of SQL is one of the requirement.

How to create thread safe Singleton in Java - Java Singleton Example

Thread safe Singleton means a Singleton class which returns exactly same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of class will remain in Java program at any time. In our last post 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java. Prior to Java 5 double checked locking mechanism is used to create thread-safe singleton in Java which breaks if one Thread doesn't see instance created by other thread at same time and eventually you will end up with more than one instance of Singleton class. From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern. I personally  don't prefer that way as there are many other simpler alternatives to write thread-safe singleton is available available like using static field to initialize Singleton instance or using Enum as Singleton in Java. Let’s see example of both ways to create thread-safe Singleton in Java.

Oracle 12c Pagination Query - SQL Example for Java Programmer

Many time we need SQL query which returns data page by page i.e. 30 or 40 records at a time, which can be specified as page size. In fact, Database pagination is a common requirement of Java web developers, especially dealing with largest data sets.  In this article, we will see how to query Oracle 10g database for pagination or how to retrieve data using paging from Oracle. Many Java programmer also uses display tag for paging in JSP which supports both internal and external paging. In case of internal paging, all data is loaded into memory in one shot and display tag handles pagination based upon page size but it only suitable for small data where you can afford those many objects in memory.

How to convert milliseconds to Date in Java - tutorial example

Do you want to convert milliseconds to Date in Java ? Actually java.util.Date is internally specified in milliseconds from epoch. So any date is number of millisecond passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds. Knowing the fact that Date is internally maintained in milliseconds allows you to store date in form of millisecond in Server or in your Class because that can be effectively expressed with a long value. In fact many experienced Java programmer store Date as long value while writing Immutable class which requires Date, one of the reason for that is Date being mutable and long value of Date can be very handy. By the ways this is next in Date related article, we have already discussed How to convert String to Date and How to get current month, year and day of week from Date in Java. If you haven’t read them already, you may find them useful. In this Java tutorial we will see example of converting millisecond into Date in Java.

3 Example to print array values in Java - toString and deepToString from Arrays

Printing array values in Java or values of array element in Java would have been much easier if  arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of array then you don't have much choice than for loop until Java 1.4. Things has been changed since Java 5 because it introduced two extremely convenient methods for printing values of both primitive and object arrays in Java. Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print values of any array. Main difference between Arrays.toString() and Arrays.deepToString  is that deepToString is used to print values of multidimensional array which is far more convenient than nesting of multiple for loops. In this Java tutorial we will see 3 different ways of printing array values in Java or value of element from Array in Java.

How to check if a number is a palindrome or not in Java - Example

How to check if a number is a palindrome or not is a variant of  popular String interview question how to check if a String is a palindrome or not. A number is said to be a palindrome if number itself is equal to reverse of number e.g. 313 is a palindrome because reverse of this number is also 313. On the other hand 123 is not a palindrome because reverse of 123 is 321 which is not equal to 123, i.e. original number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse number in Java. Since in most of interview, you are supposed to solve this question without taking help from API i.e. only using basic programming construct e.g. loop, conditional statement, variables, operators and logic. I have also seen programmer solving this question by first converting integer to String and than reversing String using reverse() method of StringBuffer and than converting String back to Integer, which is not a correct way because you are using Java API. Some programmer may think that this is just a trivial programming exercise but it’s not. Questions like this or Fibonacci series using recursion can easily separate programmers who can code and who can’t. So it’s always in best interest to keep doing programing exercise and developing logic.

Inner class and nested Static Class in Java with Example

Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular question is difference between inner class and nested static class , some time also refereed as difference between static and non static nested class in Java. One of the most important question related to nested classes are Where should you use nested class in Java? This is one of the tricky Java question, If you have read Effective Java from Joshua Bloch than in one chapter he has suggested that if a class can only be useful to one particular class, it make sense to keep that inside the class itself  otherwise declare it as top level class. Nested class improves Encapsulation and help in maintenance. I actually look JDK itself for examples and if you look HashMap class, you will find that Map.Entry is a good example of nested class in Java. 

How to add, modify and drop column with default value, NOT NULL constraint – MySQL database Example

How to add column in existing table with default value is another popular SQL interview question asked for Junior level programming job interviews. Though syntax of SQL query to add column with default value varies little bit from database to database, it always been performed using ALTER keyword of ANSI SQL. Adding column in existing table in MySQL database is rather easy and straight forward and we will see example of SQL query for MySQL database which adds a column with default value. You can also provide constraints like NULL or NOT NULL while adding new column in table. In this SQL tutorial  we are adding third column in a table called Contacts which contains name and phone of contacts. Now we want to add another column email with default value "". We will use ALTER command in SQL to do that. By the way this is next in our SQL tutorials e.g. How to join three tables in SQL and SQL query to find duplicate records in table. If you haven’t read them yet, then you may find them useful.

What is Type Casting in Java - Casting one Class to other class or interface Example

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass object but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. Which means you can not call a method which is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in next section.

How to create auto incremented identity column in SQL Server, MySQL, Sybase and Oracle ?

Automatic incremented ID, Sequence or Identity columns are those columns in any table whose value is automatically incremented by database based upon predefined rule. Almost all databases e.g. Microsoft SQL Server, MySQL, Oracle or Sybase supports auto incremented identity columns but in different ways like Oracle provides SEQUENCE object which can be used to generate automatic numbers, Microsoft SQL Server upto 2008 version provides IDENTITY() functions for similar purpose. Sybase also has IDENTITY function but little different than SQL Server and MySQL uses auto_incremented keyword to make any numeric column auto incremented. As first normal form advised about primary keys which is used to uniquely identity row and if there is no natural column or combination of column exists to act as primary key, mostly database developer use auto incremented surrogate keys which is used to uniquely identify each row. In this SQL tutorial we will see how to generate auto incremented ID column in Microsoft SQL Server, Oracle 11g, MySQL and Sybase ASE Server. By the way this SQL article is continuation of my earlier post on SQL and database like difference between truncate and delete in SQL and Finding second highest salary in MySQL and SQL Server. If you haven't got chance to read them than I suggest they are worth looking.

How to parse or convert String to long in Java - 4 Examples

How to convert a string to long in Java is one of those frequently asked questions by a beginner who has started learning Java programming language and not aware of how to convert from one data type to another. Converting String to long is similar to converting String to Integer in Java, in-fact if you know how to convert String to Integer than you can convert String to Long by following same procedure. Though you need to remember few things while dealing with long and String first of all long is primitive type which is wrapped by Long wrapper class and String is an Object in Java backed by character array. Before Java 5 you need to take an extra step to convert Long object into long primitive but after introduction of autoboxing and unboxing in Java 5, Java language will perform that conversion for you. This article is in continuation of our previous conversion tutorial like how to convert String to Double in Java or how to convert String to Enum in Java. In this Java tutorial we will learn 3 different ways to convert String to long by code example and we will also analyze pros and cons of each approach.

How to fix org.apache.log4j.Logger Error in Java org.apache.log4j.Logger error says that instance of org.apache.lo4j.Logger is not Serializable. This error comes when we use log4j for logging in Java and create Logger in a Serializable class e.g. any domain class or POJO which we want to store in HttpSession or want to serialize it. As we know from 10 Java Serialization interview question that, if you have a non serializable class as member in a Serializable class, it will throw Exception.

Look at the below code :

public class Customer implements Serializable{

private Logger logger =  Logger.getLogger(Customer.class)



If instance of Customer will be stored in HttpSession or Serialized externally it will throw " org.apache.log4j.Logger" because here logger instance is neither static or transient and it doesn't implement Serializable or Externalzable interface.

How to solve org.apache.log4j.Logger

How to fix org.apache.log4j.Logger Error in JavaSolving org.apache.log4j.Logger  is simple, you have to prevent logger instance from default serializabtion process, either make it transient or static. Making it static final is preferred option due to many reason because if you make it transient than after deserialization logger instance will be null and any logger.debug() call will result in NullPointerException in Java because neither constructor not instance initializer block is called during deserialization. By making it static and final you ensure that its thread-safe and all instance of Customer class can share same logger instance, By the way this error is also one of the reason Why Logger should be declared static and final in Java program. Just make following code change to fix org.apache.log4j.Logger in Java.

public class Customer implements Serializable{

private static final Logger logger =  Logger.getLogger(Customer.class)



That's all on how to fix org.apache.log4j.Logger in Java. We have seen what cause org.apache.log4j.Logger, it's because Logger class is not Serializable but we also learned that there is no point serializing Logger instance and better to make Logger static and final.

Further Learning
Java Fundamentals, Part 1 and 2
Core Java for the Impatient - Covers Java SE 8
Understanding and Solving Java Memory Problems

Other Serialization and troubleshooting articles from Javarevisited Blog

How to Create and Evaluate XPath Expression in Java - Tutorial and Example

You can use XPathExpression from javax.xml.xpath package to create and execute XPATH expression in Java.  Java API provides javax.xml.xpath  package, which contains classes like Xpath, XpathFactory to work with XPATH and XML documents. By the way this is third article on Xpath, In last couple of tutorials e.g. XPATH examples to select values using attributes and my XPATH notes for Java programmer, we have seen basics of Xpath expression from XML and Java point of view.  Anyone who has work with XML technologies in Java knows importance of XPATH, it is one the most useful technology to retrieve selected data from XML files. XPATH is like SQL which is used to retrieve data from relational database. Many back-office and middle-office Java application which transfers data in form of XML documents makes extensive use of  XPATH expression to retrieve value for printing or for decision making. Though there are lot of open source XML libraries are available to assist with Java and XML development e.g. XML Beans. I personally prefer to use standard Java API if  functionality is available there. In this Java tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is critical for programming flow.

How to Split String in SQL Server and Sybase

Some time we need to split a long comma separated String in Stored procedure  e.g. Sybase or SQL Server stored procedures. Its quite common to pass comma delimited or delimiter separated String as input parameter to Stored procedure and than later split comma separated String into multiple values inside stored proc. This is not just case of input parameter but you can also have comma separated string in any table data. Unfortunately there is no split() function in Sybase or SQL Server 2005 or 2008 which can directly split string based on delimiter just like in Java string split method. Fortunately Sybase Adaptive Server and Microsoft SQL server has functions like CHARINDEX and PATINDEX which can be used to split comma separated String. This is next on our SQL tutorials after seeing SQL query to find duplicate records in table and How to find 2nd and Nth maximum salary in SQL.

How to get current date, month, year and day of week in Java program

Here is quick Java tip to get current date, month, year and day of week from Java program. Java provides a rich Date and Time API though having thread-safety issue but its rich in function and if used locally can give you all the date and time information which you need for your enterprise Java application. In last Java tutorial on Date and Time API we have seen how to get current date and time from different timezone using DateFormat and SimpleDateFormat classes and in this post we will get some more details like current month, year, day of week etc by using java.util.Calendar class.  Just keep in mind that Calendar instance should not be shared between multiple threads. Calendar class in Java provides different fields to get different information e.g. Calendar.DATE gives you current date while Calendar.MONTH gives you current month based on what type of Calendar you are using, which depends upon locale.

How to create and modify Properties file form Java program in Text and XML format

Though most of the time we create and modify properties file using text editor like notepad, word-pad or edit-plus, It’s also possible to create and edit properties file from Java program., which is used to configure Log4J based logging in Java and which is used to specify configuration parameters for database connectivity using JDBC are two most common example of property file in Java. Though I have not found any real situation where I need to create properties file using Java program but it’s always good to know about facilities available in Java API. In last Java tutorial on Properties we have seen how to read values from properties file on both text and XML format and in this article we will see how to create properties file on both text and XML format. Java API’s java.util.Properties class provides several utility store() methods to store properties in either text or xml format. Store() can be used to store property in text properties file and  storeToXML() method can be used for creating a Java property file in XML format.

How to Count Occurrences of a Character in String - Java Programming Exercise Example

Write a program to count the number of occurrences of a character in String is one of the common programming interview questions not just in Java but also in other programming languages like C or C++.  As String in a very popular topic on programming interviews and there are lot of good programming exercise on String like "count number of vowels or consonants in String", "count number of characters in String" , How to reverse String in Java using recursion or without using StringBuffer etc, it becomes extremely important to have solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test candidate's coding ability i.e. whether he can convert logic to code or not.

How to read input from command line in Java using Scanner

Java 5 introduced a nice utility called java.util.Scanner which is capable of reading input form command line in Java. Using Scanner is a nice and clean way of retrieving user input from console or command line. The scanner can accept InputStream, Reader or simply path of the file from where to read input. In order to read from the command line, we can pass into Scanner's constructor as a source of input. The scanner offers several benefit over classical BufferedReader approach, here are some of the benefits of using java.util.Scanner for reading input from command line in Java:

How to remove duplicates elements from ArrayList in Java

You can remove duplicates or repeated elements from ArrayList in Java by converting ArrayList into HashSet in Java. but before doing that just keep in mind that Set doesn't preserver insertion order which is guaranteed by List, in fact that’s the main difference between List and Set in Java. So when you convert ArrayList to HashSet all duplicates elements will be removed but insertion order will be lost. Let’s see this in action by writing a Java program to remove duplicates from ArrayList in Java. In this Java collection tutorial we will see both approach of deleting duplicates from ArrayList e.g using Hashset and LinkedHashSet and compare order of elements in final ArrayList which contains no duplicates. If you are not very familiar of What is an ArrayList and HashSet in Java collection framework, I suggest reading Java ArrayList Example and 10 HashSet Example in Java. These articles contains good introduction of most common used collection in Java i.e. ArrayList and HashSet.

How to find second highest or maximum salary of Employee in SQL - Interview question

How to find second highest or second maximum salary of an Employee is one of the most frequently asked SQL interview question similar to finding duplicate records in table and when to use truncate vs delete. There are many ways to find second highest salary based upon which database you are using as different database provides different feature which can be used to find second maximum or Nth maximum salary of employee. Well this question can also be generalized with other scenario like finding second maximum age etc. In this SQL tutorial we will see different example of SELECT SQL query to find second highest salary independent of databases or you may call in ANSI SQL and other SQL queries which uses database specific feature to find second maximum salary.

XPath Tutorial - How to select elements in XPATH based on attribute and element value example

In this XPATH tutorial we will see example of selecting elements based upon its value or attribute value. We will see how to select between two elements based upon value of its child elements or based upon value of its attribute. XPATH is an important concept to understand if you are working with XML files. Most of Back-office platform relies on XML files for transporting data from one system to other and if you are working on any back-office or middle office system in Java or .NET, its important to know about XPATH and be able to use XPATH to select data from XML. Some time back I have shared my XPATH notes for Java programmer and this example shows true power of XPATH as how convenient its to made selective decision. For those who are completely new in XML and XPATH, XPATH is great xml tool which allows you to query XML document and select or retrieve selective data much like SQL but if you are new to XPATH or haven't had much experience with XML tool and technology than you will struggle to find correct syntax of XPATH for your different need.

Constructor Chaining in Java - Calling one constructor from another using this and super

Constructor Chaining in Java
In Java, you can call one constructor from another and it’s known as constructor chaining in Java. Don’t confuse between constructor overloading and constructor chaining, former is just a way to declare more than one constructor in Java. this and super keyword is used to call one constructor from other in Java. this() can be used to call another constructor of same class while super() can be used to call a constructor from super class in Java. Just keep in mind that this() in reality calls no argument constructor of the same class while this(2) calls another constructor of the same class which accepts one integer parameter. Similarly super() can be used to call no argument constructor of super class and super with parameter can be used to call other overloaded constructors of parent class. Calling one constructor from other is called constructor chaining in Java, which we saw while discussing constructor overloading in Java

How to escape String literal in Java using Eclipse IDE

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash etc. This problem is more prominent when you are pasting large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forward slash on closing tags. It’s very hard to manually escape all those characters and its pretty annoying as well. While writing JUnit test for XML documents, parsing and processing I prefer to have whole XML file as String in Unit test, which pointed me to look for that feature in Eclipse. As I said earlier in my post Top 30 Eclipse keyboard shortcuts, I always look to find new shortcut and settings in Eclipse which help to automate repetitive task. Thankfully Eclipse has one setting which automatically escapes text as soon as you paste it. This is even more useful if you prefer to copy file path and just paste it, Since windows uses forward slash it automatically escape that instead of you going manually and escaping them. By default this setting is disabled in Eclipse IDE and you need to enable it.

Invalid initial and maximum heap size in JVM - How to fix

I was getting "Invalid initial heap size: -Xms=1024M" while starting JVM and even after changing maximum heap size from 1024 to 512M it keep crashing by telling "Invalid initial heap size: -Xms=512m , Could not create the Java virtual machine". I check almost everything starting from checking how much physical memory my machine has to any typo in JVM parameters, only to find out that instead of M, I had put MB there. Java accepts both small case and the capital case for Kilo, Mega, and Gigs. you can use m or M, g or G etc but never used MB, GB or KB.  Similar problem can occur with maximum heap size specified by -Xmx. Also from Java 6 update 18, there is change on default heap size in JVM.  

SQL query to copy, duplicate or backup table in MySQL, Oracle and PostgreSQL database

Many times we need to create backup or copy of tables in database like MySQL, Oracle or PostgreSQL while modifying table schema like adding new columns, modifying column or dropping columns. Since its always best to have a backup of table which can be used in any event. I was looking for an easy way to create exact copy or duplicate tables which must be same in schema as well as in data, similar to creating copy of folder. Luckily there is an easy SQL query "CREATE table table_name AS" which allows you to create exact copy of table by executing just one SQL query. Yes, you read it correctly, no tool is required to create backup of table you just need to execute an SQL query. This is simply awesome given its importance and best part of this SQL query is that it works in almost all the database. I have tested it in MySQL and Oracle but t it should work perfectly find in other databases like PostgreSQL, SQL Server and DB2 as well. This SQL query tip is in continuation of my earlier SQL query examples like SQL query to find duplicate rows in a table and SQL query to join three tables in MySQL .

How to sort HashMap by key and value in Java - Hashtable, Map Example Tutorial

Sorting HashMap in Java is not as easy as it sounds because unfortunately Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Map like Hashtable, HashMap, and LinkedHashMap. TreeMap is an already a sorted Map so we don't need to sort it again. Why we need to sort HashMap in Java, Why can't we use TreeMap in place of HashMap is the question appears in most Java programmer's mind when they asked to sort HashMap in Java. Well, TreeMap is way slower than HashMap because it runs sorting operation with each insertion, update and removal and sometimes you don't really need an all time sorted Map, What you need is an ability to sort any Map implementation based upon its key and value. In the last couple of articles, we have seen How to loop or traverse Map in Java and in this Java tutorial we will see a couple of ways to sort HashMap in Java.

Does Java pass by value or pass by reference - Interview Question

Does Java is pass by value or pass by reference is one of the tricky Java question mostly asked on fresher level interviews. Before debating whether Java is pass by value or pass by reference lets first clear what is pass by value and what is pass by reference. This question has its origin on C and C++ where you can pass function parameter either value or memory address, where value is stored (pointer). As per Java specification everything in Java is pass by value whether its primitive value or objects and it does make sense because Java doesn't support pointers or pointer arithmetic, Similarly multiple inheritance and operator overloading is also not supported in Java. This question becomes confusing when interviewer ask about how object is passed in Java ? Answer to this question is simple whenever a method parameter expect object, reference of that object is passed. Many programmer confuses reference with pointers here which is not correct, reference is a kind of handle which is used to locate object or change object, but it doesn’t allows any pointer arithmetic i.e. you can not increase or decrease memory address and locate a different object using reference in Java.

Mapping network drive in Windows XP and 7 – net use command Example

Mapping network drive in Windows XP or Windows 7 is much easier and faster by using command line than by doing it on Windows explorer. If you have been working in Windows environment with bunch of Windows 2000 or 2003 servers and your job requires frequent access, copy or paste from local machine to those remote machine than mapping them as network drive is the best option. You can use mapped network drive as any other folder which makes job of copy paste very simple. Though windows provides multiple ways to map network drive, I prefer to use command line i.e. "net use" command to map my windows network drives. This works in Windows XP and should work in Windows 7 without any fuss, its way faster than accessing every singlet node on network to reach desired fast and In order to use this you just need to change of network drive. In our last post on Windows operating system we have seen How to find IP address from hostname and this article we will see how to map remote host as network drive in windows XP. Any way enough talking, let's see command to map network drive in windows:

Inversion of Control and Dependency Injection design pattern with real world Example - Spring tutorial

Inversion of Control and Dependency Injection is a core design pattern of Spring framework. IOC and DI design pattern is also a popular design pattern interview question in Java. As the name suggest Inversion of control pattern Inverts responsibility of managing the life cycle of the object e.g. creating an object, setting their dependency etc from application to a framework, which makes writing Java application even more easy. The programmer often confused between IOC and DI, well both words used interchangeably in Java world but Inversion of Control is a more general concept and Dependency Injection is a concrete design pattern. Spring framework provides two implementations of IOC container in the form of Application Context and BeanFactory which manages life-cycle of bean used by Java application. As you may know, necessity is the mother of invention, it benefits to first understand problem solved by IOC and Dependency Injection design pattern. This makes your understanding more clear and concrete.