Sunday, June 28, 2015

Important Java collection Interview Questions



1) What is collection in Java?
collection (lowercase c): which represents any of the data structures in which objects are stored and iterated over. More for details see this "Java Collection "

2) Basic Difference between List, Set and Map
List: can contain duplicate elements. A List cares about the index. List implementations are ordered by index position—a position that you determine either by setting an object at a specific index or by adding it without specifying position, in which case the object is added to the end.
Set: it doesn't allow duplicate elements. The equals() method determines whether two objects are identical (in which case only one can be in the set).
Map: is key value pairs.Unique key to a specific value, where both key and value are, of course, objects.Like Sets, Maps rely on the equals() method to determine whether two keys are the same or different.

3) Difference between ArrayList and Vector
  • Thread safe:
    Vector methods are synchronized for thread safety.
    ArrayList methods are not thready safety, so for performance we can use ArrayList (based on the requirement).
  • Vector and ArrayList both implements RandomAccess interface.
  • Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator. While ArrayList can only use Iterator for traversing an ArrayList . 
  • Automatic Increase in Capacity:
    A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList, it increases its Array size by 50%  .
    By default ArrayList size is 10 . It checks whether it reaches the       last  element then it will create the new array ,copy the new data of last array to new array ,then old array     is garbage collected by the Java Virtual Machine (JVM) .
  • Introduction in Java :
    Vector is legacy Collection (i.e. it is from the earliest days of Java).
    ArrayList is available from Java 1.2


4) How to use/make ArrayList in Multithread environment?
Below 2 ways we can use ArrayList in Multithread environment.
i)  Collections.sycnhronizedList(...)
    <T> List<T> java.util.Collections.synchronizedList(List<T> list)

ii) CopyOnWriteArrayList

     java.util.concurrent.CopyOnWriteArrayList

5)  Differences between ArrayList and LinkedList?
ArrayList: This as a grow-able(Dynamic) array. It gives you fast iteration and fast random access. To state the obvious: it is an ordered collection (by index), but not sorted.ArrayList is better to store and fetch data. Choose this over a LinkedList when you need fast iteration but aren't as likely to be doing a lot of insertion and deletion.
LinkedList: A LinkedList is ordered by index position and the elements are doubly-linked to one another. If you modify the list (insertion or deletion of the elements from the list) then go for LinkedList. It is more efficient for manipulation because a lot of shifting is required.LinkedList may iterate more slowly than an ArrayList, but it's a good choice when you need fast insertion and deletion

6) Differences between HashSet and LinkedHAshSet?
HashSet : It is an unsorted, unordered Set. Use this class when you want a collection with no duplicates and you don't care about order when you iterate through it. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance we'll get.
LinkedHashSet A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

7) What is Treeset?
 The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure, and guarantees that the elements will be in ascending order, according to natural order. Optionally, we can construct a TreeSet with a constructor that lets we give the collection our own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

8) What is the difference between HashSet and TreeSet?
HashSet maintains no order whereas TreeSet maintains ascending order (or we can construct the TreeSet with a constructor that lets we give the collection our own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.


9) What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implements Map interface Both looks similar, but they have few differences.
HashMap is not synchronized, so HashMap is better for single threaded environment.   
Hashtable is synchronized, so Hashtable is suitable for multi-threaded environment.
HashMap allows one null key and multiple null values. whereas Hashtable doesn't allow null key and null values.

Monday, April 27, 2015

Create zip/gz/tar files for if the files are older than particular days in UNIX or Linux

 Create zip/gz/tar files for if the files are older than particular days in UNIX or Linux

Problem: In the production servers, disk space is the problem when the log files creating every day for log entries. To overcome this we can backup the log files as a zip or tar or gz files in our unix server.

Solutions:

1) To make a one zip or gz file for files (in the current directory and sub-directory) older than particular period (example: days). 

find /tmp/log/ -mtime +180 | xargs tar -czvPf /tmp/older_log_$(date +%F).tar.gz

Above command looks for files older than 180 days in the current directory and sub-directory and creates gz file with name "".

 

2) To make individual zip or gz file for each files older than particular period (example: days)


files=($(find /tmp/mallik3/ -mtime +"$days"))
for files in ${files[*]}
do
     echo $files
     zip $files-$(date --date="- "$days"days" +%F)_.zip $files
      #       tar cvfz $(files)_$(date --date='-6months' +%F).tar.gz $files
#       rm $files
done


Above command useful for create gz files for each individual files older than particular days. First it finds all files older than particular days in given directory (and sub directory also). And iterates to indivial file and creates the gz file for it.



Will be adding more details to this topic...

Friday, April 24, 2015

Difference between JAVA_HOME, CLASSPATH and PATH



JAVA_HOME: JAVA_HOME and JRE_HOME are not set by Java itself. These are useful for third party applications/programes (example: Maven, Apache Tomcat) expect one of these environment variables to be set to the installation directory of the JDK or JRE. If you are not using software that requires them, you do not need to set JAVA_HOME and JRE_HOME.

Differences between CLASSPATH and PATH
CLASSPATH
PATH
CLASSPATH is an environment variable which contains a list of directories and / or JAR files, which Java will look through when it searches for Java classes to load.
Path is an environment variable used by the operating system where it will look for native executable programs to run.
Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes
PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executables.
Classpath refers to the Developing Environment.
While Path refers to the operating system
You do not normally need to set the CLASSPATH environment variable. Instead of using this environment variable, you can use the -cp or -classpath option on the command line when using the javac and java commands.
You should add the bin subdirectory of your JDK installation (or bin directory of JRE) directory to the PATH, so that you can use the javac and java commands and other JDK tools (or JRE Tools) in a command prompt window.


How to set the path of java (JDK or JRE) temporary in Windows:
To setting up the temporary path of JDK (or JRE), you need to follow these steps:
  .                1. Open command prompt
  1. copy the path of jdk/bin directory
  2. write in command prompt: set Path=%Path%;C:\Program Files\Java\jdk1.6.0_43\bin

C:\Users\myName>javac Sample.java
'javac' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\myName>set Path=%Path%;C:\Program Files\Java\jdk1.6.0_43\bin
C:\Users\myName>javac Sample.java
C:\Users\myName>java Sample
Hello World!
C:\Users\myName>



Setting Path of Java for Windows permanently:
  1. Right click on “My Computers” and open “Properties”
  2. In Windows Vista or Windows 7, go to "Advanced System Settings".  
  3. Go to “Advanced Tab” and click on Environment Variables button.
  4. Select 'Path' under the list of 'System Variables', and press Edit and add your Java bin path (i.e. C:\Program Files\Java\jdk1.6.0_43\bin or if you have only JRE installed in the system C:\Program Files\Java\jre6) after a semicolon
Note: JRE is for running the application or programs (i.e. end user requires only JRES). But for the developers it is required JDK.



Setting Java Path in Linux OS
Setting the path in Linux OS is same as setting the path in the Windows OS. But here we use export tool rather than set. Let's see how to set path in Linux OS:

export PATH=$PATH:/home/ jdk1.6.0_43/bin/

Here, we have installed the JDK in the home directory under Root (/home). 
....

If you would like to know more about Path environment variable please continue to read below section:
More info for Path environment variable:
Whenever you type something into a command prompt, if it is not a system command, it will searches in that directory that you have already added in the PATH variable.
C:\Users\MyName>notepad
It will open the notepad (here "notepad" is not a system command, and searches in the directory "path") This is because of “notepad.exe” file is in “C:\Windows\system32" location. And this path is already set in PATH variable.
C:\Users\mallik>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;….
In command prompt, when you type “eclipse”
C:\Users\MyName>eclipse
'eclipse' is not recognized as an internal or external command, operable program or batch file.
C:\Users\MyName>

This is because of “eclipse” is neither system command nor its path is set into PATH environment variable. So if you want to run eclipse from here then you have to set its path into PATH variable.
After setting eclipse path into PATH environment variable, you can run eclipse from your command prompt at any location.
C:\Users\MyName>set Path=%Path%;C:\software\eclipse-jee-juno-SR2-win32-x86_64\eclipse
C:\Users\MyName>eclipse
C:\Users\MyName>

At this point Eclipse will open because we set in the Path.
After setting eclipse path into PATH environment variable, you can run eclipse from your command prompt at any location. This is temporary to this command prompt only, if you want to set permanently you have to set in the path under system environment variable as explained in the above section "Setting Path of Java for Windows permanently"

More info for Classpath variable: CLASSPATH is used by the JVM that tells the JVM where to find the class libraries, including user-defined classes and libraries to import or interpret at compile time or run time.
The CLASSPATH is a list of locations, where the JVM will search for classes (jars and directories).
If the CLASSPATH is set as
Environment Variable Name = “CLASSPATH”
Environment Variable Value = “D:\classesslocation;D:\jarslocation\sample.jar”
JVM will search Classes in “D:\classesslocation” or in “D:\jarslocation\ sample.jar”

Could not find the main class. Program will exit

        Could not find the main class. Program will exit

Problem: Try to launch any Java application and if we get problem "Could not find the main class. Program will exit" with below dialog.




Analysis: If you are getting above problem. And still JRE is installed in your system. Check below things for the root cause:
  1. Check the "Path" environment variable in your system. Is it having java executable path. And what is the version of Java it is pointing. Found that it is pointing to the JAVA 1.6
  2. Is your classpath pointing to your application jars or .class files?
  3. What is version of Java used to build your source code? Found that it is used Java 1.5 to build the source file.

Solution / Conclusion: This kind of problem will occur if you build /compile the source files with lower version of Java and trying to execute with higher version of Java.

Example: if you build the source files with Java 1.5 and trying to run that program/application with Java 1.6 you will get this problem.