Showing posts with label JAVA SE. Show all posts
Showing posts with label JAVA SE. Show all posts

Setup your Java Development Environment in Windows 7


I have been receiving a lot of requests over the time, from students and people willing to experiment with the Java language, on providing a simple guide on how to setup a Java development environment , similar to the one I’ve written a year ago for Mac users. See here and here. So, this post is mainly addressed to people new to Java development, that seek information about setting up their Windows (7 or similar) environment, with all the basic tools and settings, in order to start writing Java code and experiment with various tools and technologies in the Java ecosystem.


I am pretty sure there are numerous similar resources out there, I just thought to add one more. Hope you find it handy. It is really easy, so don’t be afraid of the this post’s size, I just tried to elaborate on some simple steps, but for sure it is not rocket science


and you don’t have to be a ‘hacker’ in order to complete all the steps. You may not need all the tools below, so it is not necessary to have them all installed at once.
Index


1. Setup Java JDK and JAVA_HOME (this is a must)

2. Setup Apache Ant and ANT_HOME (optional)

3. Setup Apache Maven and MAVEN_HOME (optional)

4. Setup SVN (subversion) support, using TortoiseSVN (optional)

5. Setup Git using Git Extentions (optional)

6. Setup a Java IDE, Netbeans or Eclipse (this is a must)
1. Setup Java JDK and JAVA_HOME


I assume that you have not installed any related tool before, and your system is ‘clean‘ from Java and other Java development tools. So I guess, if you open a Command Prompt and you type ‘java -version’ you will get something like the following.





We need to install the Java Development Toolkit aka JDK, which is bundled with the Java Runtime Environment. At this moment, that I am writing this post the latest JDK versions is JDK 7u17 (update 17 that is). All you have to do is head to the main download page provided by Oracle (here) , and download the latest version that you will find. The direct link for the JKD 7u17 is here.Start the installer and go through the steps.


Tip: One small tip or let’s say a deviation from the installer that I prefer, is to change the installation path provided by the program to something easier to remember or even type in the command line tool. So instead of installing the JDK to ‘C:\Program Files\Java\jdk7_17‘ etc, i always choose something that looks like the following, ‘C:\Java\jdk17‘.


I do the same when the installer prompts me to install the JRE (java run time) and I provide the following path ‘C:\Java\jre7‘. When it is complete, I open a new command line and I re-type ‘java -version‘ as before. As you can see the installer has already done a good job and I have java in my environment. (You may use the ‘where‘ command to find out which executable is loaded on the Path – (similar to ‘which‘ in Unix) ).




We are almost there, we just need to set, one more environment variable, that is very important by many tools that are based on Java or require Java to work. It is the famous JAVA_HOME variable and you must have heard it or seen it in various tutorials and setup resources. It is easy though! Open your Advance System Settings ( Press Start , type in the search box ‘View Advanced System Settings‘, open it, select the tab ‘Advanced‘ and press the button in the bottom called ‘Environment Variables’). Add a new system variable as it is illustrated below. The name is JAVA_HOME and the path is actually the path our JDK installation, in my case ”C:\Java\jdk17‘.



Press OK, and open a new Command prompt ( it is required). Type ‘echo %JAVA_HOME%‘ and you are done.




Congrats you have successfully set up the java run time and the jdk environment! Let’s move on.
2. Setup Apache Ant and ANT_HOME


Apache Ant is a popular build tool used in many Java projects and it is still needed in many cases when you need to setup some servers or complex projects. You can find more about Ant here. Installing Ant is easy, there is no fancy installer just a zip file you need to extract somewhere and add a similar varible like JAVA_HOME (see above) called ANT_HOME. At the time being, the latest version of Apache Ant is, 1.8.4. and can be downloaded here. After downloading the zip file, I choose to extract the contents to a similar path like before ‘C:\ant184‘. (make sure that c:\ant184 is the root folder and then you have all the sub-folders like c:\ant184\bin’. So, now we must set our ANT_HOME variable and add the ‘ant’ executable to our windows Path so that we can invoke it in our command line by typing ‘ant’. Setting ANT_HOME is similar to JAVA_HOME, add a new system variable named ANT_HOME and value the path where you have the ant zip extracted in my case ‘C:\ant184‘. See below





In order to add the ‘ant’ command to our executable path we need to update the PATH system variable, in the very same window, as illustrated below, just hit ‘Edit’. Go to the end of the line and add a new entry (all the entries are separated with ‘;’ ). The path for the ant executable is ‘C:\ant184\bin‘ but we will use the ANT_HOME variable in order to be more flexible so we will add, %ANT_HOME%\bin”. See the image below.





You are done, open a new Command Prompt, and type ‘ant -version‘, or ‘echo %ANT_HOME%‘ you should get similar results are illustrated in the image below.





Congrats, you have successfully installed Apache Ant! Some Java IDE’s have Apache Ant already pre-bundled (as we will see in a later section) but I truly believe it is better to be installed manually,it is cleaner and easier to maintain, update.
3. Setup Apache Maven and MAVEN_HOME


Apache Maven is very popular tool among java developers, it does many things and has many uses. It is a building tool, a library dependency tool, a software project management and comprehension tool as it is indicated in the tool’s site. You may find more about maven here. The installation of maven is similar to Apache’s Ant, just a zip extracted somewhere and setting up a couple of variables + updating the system path. The latest version at the moment is 3.0.5 and can be downloaded here. There is already a short and handy setup guide provided in Maven’s site (see here), I am going to write similar steps. After downloading the zip file, I choose to extract the contents to a similar path like before ‘C:\maven305‘. (make sure that c:\maven305 is the root folder and then you have all the sub-folders like c:\maven305\bin’. So, now we must set our MAVEN_HOME variable and add the maven executable to our windows Path so that we can invoke it in our command line by typing ‘mvn‘. Setting MAVEN is similar to JAVA_HOME or ANT_HOME, just add a new system variable named MAVEN_HOME and value the path where you have the ant zip extracted in my case ‘C:\maven305‘.


See below.





In order to add the ‘mvn’ command to our executable path we need to update the PATH system variable like we did previously, in the very same window, as illustrated below, just hit ‘Edit’. Go to the end of the line and add a new entry (all the entries are separated with ‘;’ ). The path for the maven executable is ‘C:\maven305\bin‘ but we will use the MAVEN_HOME variable in order to be more flexible so we will add, %MAVEN_HOME%\bin”. See the image below.





You are done, open a new Command Prompt, and type ‘mvn -version‘, or ‘echo %MAVNE_HOME%‘ you should get similar results are illustrated in the image below.





Congrats, you have successfully installed Apache Maven 3!Some Java IDE’s have Apache Maven already pre-bundled (as we will see in a later section) but I truly believe it is better to be installed manually,it is cleaner and easier to maintain,use or update.
4. Setup Subversion (version control) using Tortoise SVN


Subversion is a popular versioning system among Java developers. You may find further information about it here. There are numerous subversion clients that you may install in your computer. The original subversion command line client can be found here (for windows). All of the Java IDE’s come with support of SVN either with pre-bundled clients or plug ins. I tend to use the clients offered by my IDE but I always want to have an extra client that gives me extra flexibility on certain things. I think that tortoise svn is an excellent choice for Windows users, it has full SVN support and excellent integration with the Windows file system.

You find the latest version of the client here, current is 1.7.11 (compatible with SVN 1.7.8). Download the executable and follow the steps. The only addition on the default settings is that I select to install the command line tools as well, as illustrated in the image below.




After completing the installation you can access Tortoise, using your right click in any folder, like the image below.





As I have already pointed out, most of the Java IDE’s around offer SVN integration, out of the box but is always a good thing to have an extra client, in your windows shell. Tortoise is a great one, you can actually work with tortoise and skip your IDE’s integration if you like so! If you don’t like Tortoise and you want to consider yet another client then I suggest you have a look on the free edition of SmartSVN.
5. Setup Git (version control) using Git Extentions


Git, is another version control system that is becoming very popular among developers in general. In many cases it is replacing SVN, so there is a high chance you might be required to work with it, or work in projects that store their code on a remote Git repository or contribute to an open source project at GitHub. You may find more about Git here.


Git is the new kid on the block on popular versioning systems, so some tools or support still may not be so user friendly comparing to tools and clients of SVN. Git is also encouraging users to interact with it, using the command line interface. The stand alone git installation for windows can be found here. This will install the git client and support tools and you may start experiments with it, using the command line. If you want a more UI friendly way, then you may choose one of the free clients. (so, don’t install the standalone client).


My choice at the time being is Git Extentions, which can be found here. The nice thing about Git Extentions is that with one downloadyou get the native git client and all the nice UI tools, similar to Tortoise featured in the previous section. So you can just download the git extensions msi package, and follow the installer’s step – just make sure to enable (when you are prompted to do so) the mygit support. See the image below.





I have disabled any visual studio support, since i am not going to to install this particular IDE. On the next step, I select Putty to be installed as my ssh client.




On the related prompt of the Git installer, about altering your System’s Path, I always select the second one, so that the ‘git’ command is added to my command line exec path. See the image below.



Continue with the rest of the installation and the various tools installed. The provided, default selections are safe to use.



As you can see, by the end you are going to have the related icons, copied in your Desktop. Congrats you have full Git support on your development environment! Double click on the Git Extentions icons and set the final details like language of use and username / email to be used while interacting with git repositories.
6. Pick your Java IDE : )


Up until now we have installed a variety of tools towards setting up our Java Development environment. Since the JDK is already installed (from step one) we could actually jump to coding just by using our text editor of choice (NotePad++, TextPad, NotePad, Ultra Edit etc) and invoking the javac and java commands from the command line. It is good to know that this is an option but I would highly recommend you start doing your experiments using a real IDE, and there are a lot of them in the Java development world and are considered very very powerful.
Netbeans


If you are a total newbie and you have just started using or learning Java, then your first stop, according to my opinion should be Netbeans. It is one of the best Java IDE’s around, used by many professional java developers all around the world and is really targeting towards ease of use and productivity from the very beginning. You can find Netbeans (currently latest version 7.3) here. If you are about to work with some more advanced java stuff like the Java Enterprise edition (aka Java EE) then I think you should try downloading and install Netbeans with Java EE support and not the simple version. Upon installation it will prompt you about the bundled Java EE container (aka application server) that can install for you. My choice is GlassFish.


See the image below.




Continue with the rest of the installer prompts, your already existing JDK installation from step 1 should be picked accordingly by the setup script and be used by the IDE as well. The image below illustrates a fresh install of Netbeans running.




If you are looking for a quick guide or tutorial on using Netbeans, have a look here or have a look on numerous videos on youtube, here.
Eclipse


Eclipse is along with Netbeans, one of the most famous Java IDE’s in the whole Java development community. It’s user (installation base) might be larger comparing to Netbeans and is usually the IDE of choice for hard core Java developers. I am currently an Eclipse user as well, but I personally don’t find it a good fit for someone that is now starting to ‘play‘ with Java. There is a large community behind it, (as with Netbeans) numerous resources and support forums. It is not that hard, but if you are a new developer and you are still trying to make your way into basic stuff there is some possibility that you lose your way and get disappointed, something that we don’t want.


I don’t want the above paragraph to be the start of a flame war especially for hard cord eclipse users, I am actually an eclipse user myself, I just think that Netbeans is more ‘newbie’ user friendly, and it is critical that new java developers don’t get disappointed after trying to complete their first assignment or task in Java.The latest version of Eclipse currently is Eclipse 4.2 SR2 (codename Juno), and the downloads page can be found here. You can either select the Eclipse for Java or JEE developers download, depending on your assignments/tasks or interest. Eclipse does not pre- install any servers or support tools as such. All the extra functionality should be added afterwards through the Plugin system that offers. (See Eclipse Market place). Eclipse does not have any installer, it comes as a zip file, all you have to do, is download the zip and extract the contents (like we did with Ant, or Maven). I usually pick a simple folder, like in previous section e.g ‘C:\eclipseJuno42′ . Open the folder and you will find the executable (eclipse.exe). You should have something like the image below.




Install JAVA JDK

How to install JAVA JDK in windows. Pls view this video, this may be vary with window versions.


Java example

1. Factorial finding
public class Fact {
        public static int factorial(int n) {
            if (n==0)
                  return 1;
           else
                 return n * factorial(n-1);
        }
        public static void main(String argv[]) {
             int x;
             x=9;
             System.out.println(“Factorial of “+x+” is “+factorial(x));
        }
}

2. Divisible by number
public class Divisor{
          public static void main(String[] args){
               int a = 10;
               int b = 2;
               if ( a % b == 0 ){
                      System.out.println(a + ” is divisible by “+ b);
              }else{
                      System.out.println(a + ” is not divisible by ” + b);
              }
         }
}

3. Compound Interest
public class CompoundInterest {
            public static void main(String[] args) {
               double principal;
               double rate;
               double interest;
               principal = 17000;
               rate = 0.07;
               interest = principal * rate;
               principal = principal + interest;
               System.out.print(“The interest earned is $”);
               System.out.println(interest);
               System.out.print(“The value of the investment after one year is $”);
               System.out.println(principal);
          }
}

4. Printing Square of number
public class PrintSquare {
        public static void main(String[] args) throws Exception {
             int square = 0;
             int userInput = 0;
             userInput = Integer.parseInt(args[0]);
             square = userInput * userInput ;
             System.out.print(“The square of “+userInput+” is “+square);
        }
}

5. Sum of Numbers
     import java.util.*;
      public class SumNo{
            public static void main(String args[]){
                  Scanner console = new Scanner(System.in);
                  System.out.print(“Type a number: “);
                  int num1 = console.nextInt();
                  System.out.print(“Type a number: “);
                  int num2 = console.nextInt();
                  System.out.print(“Type a number: “);
                  int num3 = console.nextInt();
                  int sum = num1 + num2 + num3;
                  System.out.println(“The sum is ” + sum);
             }
      }

6. Finding even/odd numbers
public class EvenOdd{
       public static void main(String[] args) {
             for (int i = 1; i <= 20; i++) {
                  if (i % 2 == 0) {
                     System.out.println(i + ” is even”);
                  } else {
                     System.out.println(i + ” is odd”);
                  }
             }
       }
}

7. Finding Prime Number
public class PrimeNo {
         public static void main(String[] args) {
             for(int i=0;i<100;i++){
                  if(countFactor(i)==2){
                    System.out.println(i);
                  }
              }
          }
         public static int countFactor(int num){
              int cnt = 0;
              for(int j = 1; j <= num; j++) {
                 if (num % j == 0) {
                     cnt++;
                 }
               }
                return cnt;
           }
 }

8.Counting the charectors
public class CountChar {
      public static void main(String[] args) {
           String str = “mississippi”
           int tot = cntCh(str);
           System.out.println(“Total count :”+tot);
      }
      public static int cntCh(String str) {
          int count = 0;
          for (int i = 0; i < str.length(); i++) {
             if (str.charAt(i) == ‘s’) {
                  count++;
              }
         }
        return count;
      }
}

9. Printing Time and Date format
import java.util.*;
     public class TimeDateFormat {
         public static void main(String args[]) {
             Formatter fmt = new Formatter();
             Calendar cal = Calendar.getInstance();
             // Display standard 12-hour time format.
             fmt.format(“%tr”, cal);
             System.out.println(fmt);
             // Display complete time and date information.
             fmt = new Formatter();
             fmt.format(“%tc”, cal);
             System.out.println(fmt);
             // Display just hour and minute.
             fmt = new Formatter();
             fmt.format(“%tl:%tM”, cal, cal);
             System.out.println(fmt);
             // Display month by name and number.
             fmt = new Formatter();
             fmt.format(“%tB %tb %tm”, cal, cal, cal);
            System.out.println(fmt);
      }
}

10. Find In Line
import java.util.*;
        public class FindInLine{
            public static void main(String args[]) {
            String instr = “Name: Tom Age: 28 ID: 77″
            Scanner conin = new Scanner(instr);
            // Find and display age.
            conin.findInLine(“Age:”); // find Age
            if(conin.hasNext())
                 System.out.println(conin.next());
            else
                  System.out.println(“Error!”);
         }
 }

11.File Read / Write
import java.util.*;
import java.io.*;
public class ScanMixed {
public static void main(String args[])
throws IOException {
int i;
double d;
boolean b;
String str;
// Write output to a file.
FileWriter fout = new FileWriter(“test.txt”);
fout.write(“Testing Scanner 10 12.2 one true two false”);
fout.close();
FileReader fin = new FileReader(“Test.txt”);
Scanner src = new Scanner(fin);
while(src.hasNext()) {
if(src.hasNextInt()) {
i = src.nextInt();
System.out.println(“int: ” + i);
}
else if(src.hasNextDouble()) {
d = src.nextDouble();
System.out.println(“double: ” + d);
}
else if(src.hasNextBoolean()) {
b = src.nextBoolean();
System.out.println(“boolean: ” + b);
}
else {
str = src.next();
System.out.println(“String: ” + str);
}
}
fin.close();
}
}

Explain JIT

Just-In-Time Compilers
The simplest tool used to increase the performance of your application is the Just-In-Time (JIT) compiler. A JIT is a code generator that converts Java bytecode into native machine code. Java programs invoked with a JIT generally run much faster than when the bytecode is executed by the interpreter. The Java Hotspot VM removes the need for a JIT compiler in most cases however you may still find the JIT compiler being used in earlier releases.
The JIT compiler was first made available as a performance update in the Java Development Kit (JDK) 1.1.6 software release and is now a standard tool invoked whenever you use the java interpreter command in the Java 2 platform release. You can disable the JIT compiler using the -Djava.compiler=NONE option to the Java VM. This is covered in more detail at the end of the JIT section.
How do JIT Compilers work?
JIT compilers are supplied as standalone platform-dependent native libraries. If the JIT Compiler library exists, the Java VM initializes Java Native Interface (JNI) native code hooks to call JIT functions available in that library instead of the equivalent function in the interpreter.
The java.lang.Compiler class is used to load the native library and start the initialization inside the JIT compiler.
When the Java VM invokes a Java method, it uses an invoker method as specified in the method block of the loaded class object. The Java VM has several invoker methods, for example, a different invoker is used if the method is synchronized or if it is a native method.
The JIT compiler uses its own invoker. Sun production releases check the method access bit for value ACC_MACHINE_COMPILED to notify the interpreter that the code for this method has already been compiled and stored in the loaded class.
When does the code become JIT compiled code?
When a method is called the first time the JIT compiler compiles the method block into native code for this method and stored that in the code block for that method.
Once the code has been compiled the ACC_MACHINE_COMPILED bit, which is used on the Sun platform, is set.

Exception Drill

1. What is an Exception ?
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.
2. What is a Java Exception ?
A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.
3.Where does Exception stand in the Java tree hierarchy ?          java.lang.Object
         java.lang.Throwable
         java.lang.Exception
         java.lang.Error
4.What are checked exceptions ?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
5.What are runtime exceptions ?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
6.What is the difference between error and an exception ?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
7.How to create custom exceptions ?
Your class should extend class Exception, or some more specific type thereof.
8.If I want an object of my class to be thrown as an exception object, what should I do ?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
9.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object ?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
10.How does an exception permeate through the code ?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
11.What are the different ways to handle exceptions ?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
12.What is the basic difference between the 2 approaches to exception handling.
1 try catch block and
2 specifying the candidate exceptions in the throws clause ?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
13.Is it compulsory to use the finally block  ?
It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.
14.How are try, catch and finally block organized  ?
A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.
15.What is a throw in an Exception block ?
“throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
throw new NullPointerException(“thrownException”);
16.What is the use of throws keyword ?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
type method-name(parameter-list) throws exception-list {
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne.”);
17.Is it necessary that each try block must be followed by a catch block ?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
18.If I write return at the end of the try block, will the finally block still execute ?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
19.If I write System.exit (0); at the end of the try block, will the finally block still execute ?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
20.What are Checked and UnChecked Exception ?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
21.Give me some examples of Checked Exceptions and Unchecked Exceptions ?
Unchecked Exceptions.
         ArithmeticException
         ArrayIndexOutOfBoundsException
         ClassCastException
         IndexOutOfBoundsException
         IllegalStateException
         NullPointerException
         SecurityException 
Checked Exception
        ClassNotFoundException
        CloneNotSupportedException
        IllegalAccessException
        InstantiationException
        InterruptedException
        NoSuchFieldException
        NoSuchMethodException
22. What are Chained Exceptions ?
The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.
Throwable getCause( )
Throwable initCause(Throwable causeExc)

Collections Drill – II

1.What is meant by compatible equals() and hashCode() methods ? In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value.
2.Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a Properties list ? Technically speaking you can. However, you have to make sure you only add key-value pairs where both are strings. If you add something other than a String, the listing, loading, and saving methods won’t work as expected.
Like the Stack/Vector subclass relationship, Properties/Hashtable should be a has-a relationship, not an is-a/subclass relationship.
3.When I wrap a collection to be read-only or synchronized, why can’t I call any of the collection methods via reflection without getting an IllegalAccessException ? When you wrap a collection through the static methods of the Collections class, this creates an instance of a package-private (default access) class. Because you don’t have access to these classes, you can’t call their methods via reflection (though you can call their methods directly through the appropriate interface).
4.What is a weak reference and what are they used for ? Normally the Java garbage collector plays safe. It will only free up the memory used by an object when that object can no longer be accessed by the program. Once an object become impossible to reach it is eligible for collection, and eventually its memory will be reclaimed.
This eliminates one of the most common programming errors in some other languages (like C++), where code accidentally tries to access an object that has been freed. Unfortunately it can lead to another problem, where you leave open a potential access route to an object that you don’t need any more. Memory fills up, and the program slows down or reports an “Out of Memory” error.
To avoid this, you can be very careful to close off access paths to an object once you have finished using it. Java 2 introduces another alternative, the weak reference. Weak references provide access to an object without preventing it from being freed. When you use a weak reference you have to accept that the object referred to may have disappeared, which results in the reference being automatically set to null. On the other hand, the weak reference will not hold the object in memory once it is inaccessible via normal references (or via “soft” references – see below). Weak references are not appropriate in all circumstances, but sometimes they can make code easier to write and understand.
The most common use of weak references is indirect – they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.
Other specialist references are soft references (which inhibit collection until memory runs short), and phantom references (used for cleanup when objects are freed).
5.What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as opposed to using a pair of arrays (one for keys, the other for values) with brute-force key searches ?
Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make sense to forgo the convenience of the HashMap to avoid the associated overhead?
Well, is there really that much of a performance loss using a HashMap? There is no synchronization penalty (unless you impose your own). You can tune the sizing by adjusting the initial size and load factor. Plus, do you really want to be responsible for “rolling your own” code to handle the dynamic resizing of the key and value arrays, inserting/removing data from these arrays, optimizing the searching algorithm, etc. Yuck!
In general, the performance hit associated with using a general purpose Map (such as the HashMap) is far outweighed by the benefits of using a simple interface backed by a tested algorithm.
The only reason I could see wanting to use arrays is to guaruntee the type of your key/values to add type checking and avoid casting. Still, if this is a critical aspect of your application, you can wrap your HashMap in another object to provide type-safety, and the casting overhead should be minimal.
Another alternative to creating a custom solution is to explore other collection classes, such as ObjectSpaces’s JGL Libraries. There may be something there that would suit your needs.
So, to answer your question, I would say that the fewer the key-value pairs you have, the more reason you have to use a HashMap. Since the fewer the keys, the faster the search, why not use it for 2-5 key-value pairs. I would think that only when you get to many pairs (tens of thousands) and there is a performance problem you should consider an alternative. Basically, exhaust your search of tried-and-true collections before you try a custom solution. Let other people create these collections so you can focus on your application.
6.How does ArrayList increase its capacity ? Unlike Vector where you can specify a capacity increment, ArrayList doesn’t support this. Instead, ArrayList will increase capacity by about a half when it runs out of space. The refernece implementation uses the forumla:
newCapacity = (oldCapacity * 3)/2 + 1
though, this isn’t part of the class definition so others can implement it differently.
7.What is the default initial size for a Hashtable / HashMap ? This depends on what version of Java you are using. For JDK 1.2, the size was 101. For JDK 1.3, the size changed to 11.
8.How do you create a multi-dimensional List ?
Since the elements of a List are objects, in order to make the List multi-dimensional, each object in the outer list needs to be a List, too. For instance, …
List list = new ArrayList(10);
for (int i=0; i<10; i++) {
list.set(i, new LinkedList());
}
Then just fill up each inner list with items.
9.In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys ?
You can pass a Comparator to the TreeMap constructor to use a sorting order other than the natural order.
10.What are the differences between HashMap and Hashtable ? Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.
The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn’t. You can add it, but it isn’t there by default.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t. If you change the map while iterating, you’ll know.
And, a third difference is that HashMap permits null values in it, while Hashtable doesn’t.
For new code, I would tend to always use HashMap.
11.What are the differences between Vector and ArrayList? Which is best to use ? Vector and ArrayList are very similar. Both of them represent a ‘growable array’, where you access to the elements in it through an index.
ArrayList it’s part of the Java Collection Framework, and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.
The main difference is that Vector it’s a synchronized object, while ArrayList it’s not.
While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.
Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList.
12.How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age. Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example:
public interface Person {
public String getName();
public int getAge();
}
public interface PersonComparator {
public int compare(Person p1, Person p2);
}
public class AgeComparator implements PersonComparator {
public int compare(Person p1, Person p2) {
if (p1.getAge() == p2.getAge()) return 0;
return p1.getAge() > p2.getAge() ? 1 : -1;
}
}
public class NameComparator implements PersonComparator {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}
This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.
13.Does the equals() method of an array do element-level checking ? If you have two arrays in memory with the same elements, and ask first.equals(second), this does not do an element-by-element comparison. Instead, it behaves just like Object’s equals() method, essentially asking if the variables point to the same place in memory:
int a[] = {1, 2, 3};
int b[] = {1, 2, 3};
// This prints false
System.out.println(a.equals(b));
To check for equality of two arrays, use Arrays.equals().
// This prints true
System.out.println(Arrays.equals(a,b));
14.How can I retrieve the items in my HashSet / HashMap in the order they were added ?
Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order.
15.How do you sort an ArrayList (or any list) of user-defined objects ? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).
16.How can you get the hash code for an instance of a class if the class overrode hashCode() ?
The System class method identityHashCode() allows you to get this information:
int code = System.identityHashCode(anObject);
17.How can I easily shift the elements in a List / Vector such that all the elements rotate n elements ?
The Java 1.4 API adds a rotate() method to the Collections class: rotate(List list, int distance) that will shift the elements for you.
18.What’s the most optimum way of swapping two elements in a List ? The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with:
list.set(index1, list.set(index2, list.get(index1)));
This works because the set() method returns the original element.
19.What’s the purpose of the IdentityHashMap ?
The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
20.How do I convert an old-style Enumeration to something in the Collections Framework ?
Prior to Java 1.4, any conversion had to be manually done. With the introduction of 1.4, you can call Collections.list(enumeration) to automatically convert the Enumeration to an ArrayList.
21.How do I retrieve the values of a Hashtable/HashMap in sorted order ?
Basically, you can’t directly do this. What you can do is get the Collection of values() back from the map and create a sorted collection, or maintain two maps, one in each direction, and keep the second map sorted by being a TreeMap. Which you use depends on the frequency you must sort the elements.
22.How can I add a Collection to another Collection ? The java.util.Collection interface includes an addAll(Collection c) method to add one collection to another.
23.How can I use two iterators to go through a collection ?
Just get a separate iterator for each loop:
Collection l = …;
for(Iterator i = l.iterator(); …) {
for(Iterator j = l.iterator();…) {
}
}
24.How do I traverse a map backwards ?
Just keep getting the last key and the head map before it:
if (!map.isEmpty()) {
Object last = map.lastKey();
boolean first = true;
do {
if (!first) {
System.out.print(“, “);
}
System.out.print(last);
last=map.headMap(last).lastKey();
first=false;
} while (last != map.firstKey());
System.out.println();
}
25.How do I traverse a sorted set backwards ?Just keep getting the last element and the head set before it:
if (!set.isEmpty()) {
Object last = set.last();
boolean first = true;
do {
if (!first) {
System.out.print(“, “);
}
System.out.print(last);
last=set.headSet(last).last();
first=false;
} while (last != set.first());
System.out.println();
}
26.How can I go through an Iterator mulitple times ?
There is no direct support for this. You’ll need to create your own caching mechanism. For instance, as you go through the Iterator the first time, add the elements to a LinkedList. Then, you can just get an Iterator from the LinkedList for the second pass through.
27.What’s new to the Collections Framework in Java 1.4 ?
There are three new implementations:
          LinkedHashSet
          LinkedHashMap
          IdentityHashMap
         One marker interface:
         RandomAccess
        And six new utility methods for the Collections class:
        rotate(List list, int distance)
        replaceAll(List list, Object oldVal, Object newVal)
        indexOfSubList(List source, List target)
        lastIndexOfSubList(List source, List target)
       swap(List list, int i, int j)
       list(Enumeration e)
28.How can I add an array of objects to a collection ? First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList).
29.Is Vector’s clone method thread-safe ? Sure it is, since it is a Vector which is thread-safe.
30.How do I load property settings with the Properties class ? java.util.Properties objects can load values from a file using the method load(InputStream).
Here is the code you need:
Properties props = new Properties();
props.load(new FileInputStream(“propertyfile.properties”));
String value = props.getProperty(“propertyname”);
//Just a trick: in a web archive (war) you can get the InputStream inside the war archive using
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(“it/package/application.properties”);
This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat.
31.How do I save properties settings with the Properties class ? Try this:
Properties prop = new Properties();
FileOutputStream output = new FileOutputStream(“Test.properties”);
prop.store(output,”my testproperties”);
output.flush();
output.close();
You’ll need to catch an IOException.
32.What happens if two threads perform a get of one hashmap at the same time ?
Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.
For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is thread-safe.
Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.
33.How can I convert a Collection to an Array then back to a Collection ? The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an Object[] type.
The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException.
import java.util.*;
public class G{
public static void main(String[] args){
List<String> sun = new ArrayList<String>();
sun.add(“Feel”);
sun.add(“the”);
sun.add(“power”);
sun.add(“of”);
sun.add(“the”);
sun.add(“Sun”);
String[] s1 = sun.toArray(new String[0]); //Collection to array
for(int i = 0; i < s1.length; ++i){
String contents = s1[i];
System.out.print(contents);
}
System.out.println();
List<String> sun2 = Arrays.asList(s1); //Array back to Collection
for(String s2: sun2){
String s3 = s2; System.out.print(s3);
}
//sun2.add(new String(“Hello”)); // throws UnsupportedOperationException
}
}
34.How can I create a Collection based on another Collection ?Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List.
The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation.
ArrayList(Collection<? extends E> c)
LinkedList(Collection<? extends E> c)
Vector(Collection<? extends E> c)
TreeSet(Collection<? extends E> c)
Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues.
For example the ArrayList created will contain the same elements in the same order as the first ArrayList created.
List<String> slist = new ArrayList<String>();
slist.add(“g”);
slist.add(“a”);
slist.add(“d”);
slist.add(“a”);
slist.add(“f”);
slist.add(“e”);
slist.add(“c”);
slist.add(“b”);
for(String s : slist){
System.out.print(s + “\t”);
}
System.out.println();
List<String> s2list = new ArrayList<String>(slist);
for(String s : s2list){
System.out.print(s + “\t”);
}
When creating a Set based on an existing List the Set will be void of duplicates.
List<String> slist = new ArrayList<String>();
slist.add(“g”);
slist.add(“a”);
slist.add(“d”);
slist.add(“a”);
slist.add(“f”);
slist.add(“e”);
slist.add(“c”);
slist.add(“b”);
for(String s : slist){
System.out.print(s + “\t”);
}
System.out.println();
Set<String> s2set = new TreeSet<String>(slist);
for(String s : s2set){
System.out.print(s + “\t”);
}
35.How can I define my own Comparable type so that it can be naturally sorted within a List ?
When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it’s natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical.
Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException.
public interface Comparable<T>{
public int compareTo(T o);
}
The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method.
import java.util.*;
public final class Alpha implements Comparable<Alpha>{
public static void main(String[] args){
List<Alpha> alpha = new ArrayList<Alpha>();
alpha.add(new Alpha(“z”));
alpha.add(new Alpha(“g”));
alpha.add(new Alpha(“k”));
alpha.add(new Alpha(“q”));
alpha.add(new Alpha(“a”));
alpha.add(new Alpha(“b”));
alpha.add(new Alpha(“o”));
alpha.add(new Alpha(“v”));
alpha.add(new Alpha(“c”));
Collections.sort(alpha);
System.out.println(alpha);
}
private String letter;
public Alpha(String letter){
if(letter == null){throw new NullPointerException();}
this.letter = letter;
}
public String toString(){return letter;}
public boolean equals(Alpha a){
if(!(a instanceof Alpha))
return false;
return letter.equals(a.letter);
}
public int compareTo(Alpha a){
int i = letter.compareTo(a.letter);
return i;
}
}
More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order.
import java.util.*;
public final class Car implements Comparable<Car>{
public static void main(String[] args){
Car[] cararry = {new Car(“Toyota”,”Celica”), new Car(“Honda”,”Civic”),
new Car(“Ford”,”Mustang”), new Car(“Lexus”,”ES”), new Car(“Acura”,”Integra”),
new Car(“Honda”,”Accord”), new Car(“Acura”,”RL”), new Car(“Toyota”,”Avalon”)
};
List<Car> car = Arrays.asList(cararry);
Collections.sort(car);
System.out.println(car);
}
private String brand;
private String model;
public Car(String brand, String model){
if(brand == null || model == null){throw new NullPointerException();}
this.brand = brand;
this.model = model;
}
public String toString(){return brand + ” ” + model;}
public boolean equals(Car car){
if(!(car instanceof Car))
return false;
boolean samebrand = brand.equals(car.brand);
return samebrand != true ? samebrand: model.equals(car.model);
}
public int compareTo(Car car){
int i = brand.compareTo(car.brand);
return(i != 0 ? i : model.compareTo(car.model));
}
}
36.What are Generics and how can I use them ?
One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. A generic type is defined using one or more type variables with it’s contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as.
public interface List<E>{
public add(E e);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}
Type Safe Collections
So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned.
Set s = new SortedSet();
s.add(new String(“Java”));
String j = (String) s.get(0); // cast required;
// java 5
Set<String> s = new SortedSet<String>();
s.addElement(new String(“String Type”));
String s = s.get(0); // no cast required!
Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime.
String s = “Java, write once run anywhere”
List l = new ArrayList();
l.add(new String(“Java”));
Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException!
// Using Generics the compiler catches
String s = “Java. Write once run anywhere!”
List<String> l = new ArrayList<String>();
l.add(new String(“Java”));
Integer i = l.get(0);
Generics and Subtyping
Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.
List<Object> l = new ArrayList<String>();
As a rule. If X is a superclass or superinterface of Y and E is a generic type declaration then it not the case that E<X> is a supertype of E<Y>. So if E<Object> is not a super type of E<String> then what is the super type of E<String>? Read on and find out!
Wild Cards
Wild Cards represent what is called “the unknown type”. Essentially they can be thought of as the supertype of any Collection. Wildcards allow some flexibility in certain situations where it is needed that a type be abstracted out. For instance what if we define the following method, printSet(Collection<Object> x). We just saw in the previous example that E<Object> is not the super type of E<String> or any other type for that matter. In this case we can change the printSet’s parameter to Collection<?>. This allows us to pass in E<X> where X is any type.
public void printElements(Collection<?> c){
for(Object o: c){
System.out.println(o);
}
}
When working with wildcards it is always legal to read and assign the contents to an Object type
List<String> l = new ArrayList<String>();
l.add(new String(“Java”));
Object o = getElement(l, 0); // legal
public Object getElement(List<?> l, int index){
Object o = null;
try{
o = l.get(0);
}catch(IndexOutOfBoundsException e){
//…….
}
return o;
}
assigning values is another matter. The add() method takes an argument of type E which is the type that the Collection is to hold. Any type wishing to be added to the Collection would have to be of the same type. Since<?> represents an unknown type it is impossible to determine what the type parameter of the collection represents.
Bounded Wildcards
A Bounded Wildcard allows as type to be constrained. Bounded Wildcards are useful when there is some type of partial knowledge about the type arguments. While it is still illegal to try and add an element to a unknown Collection with a bounded type they come in handy in other situations. One use is to be able to pass not only types into a method but sub-types also. In doing this we are able to implement polymorphic behavior.
import java.util.*;
class Printer{
public void print(String s){
for(int i = 0; i < s.length(); i++){
System.out.print(s.charAt(i));
}
}
}
class ReversePrinter extends Printer{
public void print(String s){
for(int i = s.length() – 1 ; i >= 0; i–){
System.out.print(s.charAt(i));
}
}
}
public class G{
public static void main(String[] args){
String s = “Nothing like a good cup of Java in the morning!”
List<Printer> l = new ArrayList<Printer>();
l.add(new Printer());
printElements(l,s);
List<ReversePrinter> rl = new ArrayList<ReversePrinter>();
rl.add(new ReversePrinter());
printElements(rl,s);
}
public static void printElements(List<? extends Printer> l, String s){
Printer printer = l.get(0);
printer.print(s);
System.out.println();
}
}
37.How can I shuffle the elements of a Collection ?
The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.
static void shuffle(List<?> list)
static void shuffle(List<?> list, Random rnd)
The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness.
import java.util.*;
public class ShuffleTest{
public static void main(String[] args){
List<String> sl = new ArrayList<String>();
sl.add(“One”);
sl.add(“Two”);
sl.add(“Three”);
sl.add(“Four”);
sl.add(“Five”);
sl.add(“Six”);
for(String s: sl){
System.out.println(s);
}
System.out.println();
Collections.shuffle(sl);
for(String s: sl){
System.out.println(s);
}
}
}
38.How can i tell if two Collections contain the same elements or have no elements in common ?
Two methods are needed in this case.
boolean containsAll(Collection<?> c)
boolean disjoint(Collection<?>c1 Collection<?>c2)
Since containsAll(Collection<?> c) is defined within the Collection interface all concrete implementations will be able to use this method. disjoint(Collection<?>c1 Collection<?>c2) is defined within the Collections class.
Using both of these methods is pretty straightforward. containsAll(Collection<?> c) is an instance method so naturally it must be invoked on an object. disjoint(Collection<?>c1 Collection<?>c2) is defined as Static within the Collections class so all that is needed is to invoke it using the class name ie Collections.disjoint(Collection<?>c1 Collection<?>c2)
39.How can I traverse a List backwards ?
In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.
ListIterator<E> listIterator()
Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods.
boolean hasPrevious()
E previous()
Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods.
boolean hasNext()
E next()
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class {
public static void main(String[] args){
List<String> slist = new ArrayList<String>();
slist.add(“1″);
slist.add(“2″);
slist.add(“3″);
slist.add(“4″);
ListIterator i = slist.listIterator();
while(i.hasNext()){
System.out.print(i.next());
}
System.out.println();
while(i.hasPrevious()){
System.out.print(i.previous());
}
}
}
40.How can I get a sorted list of keys that are contained within a Map ? The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it’s elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface.
/* TreeMap used. Keys stored in ascending order */
Map<String,String> book = new TreeMap<String,String>();
book.put(new String(“Java”),new String(“A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms.”));
book.put(new String(“C#”),new String(“An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles.”));
book.put(new String(“Python”),new String(“A simple, high-level interpreted language by Guido van Rossum”));
book.put(new String(“LISP”),new String(“A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.”));
Set words = book.keySet();
for(Iterator i = words.iterator();i.hasNext();){
System.out.print(i.next() + “\t”);
}
41.How can I create a read only Collection ? Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.
Collection<T> unmodifiableCollection(Collection<? extends T> c)
List<T> unmodifiableList(List<? extends T> list)
Set<T> unmodifiableSet(Set<? extends T> s)
SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
import java.util.*;
public class Unmod{
public static void main(String[] args){
List<String> strlist = new ArrayList<String>();
strlist.add(“C”);
strlist.add(“B”);
strlist.add(“A”);
Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist);
// unmodstrlist.add(“G”); throws UnsupportedOperationException
Set<String> strset = new TreeSet<String>();
strset.add(“C”);
strset.add(“B”);
strset.add(“A”);
Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset);
// unmodstrset.add(“G”); throws UnsupportedOperationException
}
public static Collection<String> makeUnmodifiable(Collection<String> c){
return(Collections.unmodifiableCollection(c));
}
}
42.Is there a way determine how many times an Object occurs within a Collection ? The Collections class provides a method which returns the number of times an Object appears within a given Collection.
public static int frequency(Collection<?> c, Object o)
If a null Collection is passed in then a NullPointerException is thrown.
import java.util.*;
public class Freq {
public static void main(String[] args){
List<Integer> password = new ArrayList<Integer>();
password.add(new Integer(4));
password.add(new Integer(6));
password.add(new Integer(8));
password.add(new Integer(4));
password.add(new Integer(9));
Integer passwordelement = new Integer(4);
System.out.println(passwordelement + ” appears “
+ getFrequency(password,passwordelement) + ” times within password”);
}
private static int getFrequency(Collection c, Object o){
return(Collections.frequency(c,o));
}
}
43.What is the easiest way to obtain a Map Entry ? The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface.
Set<Map.Entry<K,V>> entrySet();
The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry.
K getKey()
V getValue()
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Iterator;
public class Emps{
public static void main(String[] args){
Map<String,String> empmap = new TreeMap<String,String>();
empmap.put(“956544″,”Bob Jones”);
empmap.put(“132485″,”Phil Harris”);
empmap.put(“102161″,”Kamal Uganda”);
empmap.put(“226545″,”Bill Russel”);
empmap.put(“116423″,”Dorris Smith”);
Set s = empmap.entrySet();
for(Iterator i = s.iterator();i.hasNext();){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ” : ” + me.getValue());
}
}
}
44.How can I find the maximum element contained within a Collection ? Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class.
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
This method returns the maximum element of the given Collection according to the natural ordering of it’s elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface.
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Max{
public static void main(String[] args){
Collection<Byte> numl = new ArrayList<Byte>();
numl.add(new Byte(“2″));
numl.add(new Byte(“6″));
numl.add(new Byte(“3″));
numl.add(new Byte(“1″));
numl.add(new Byte(“5″));
numl.add(new Byte(“4″));
System.out.print(“Max element is ” + getMax(numl));
}
public static Byte getMax(Collection<Byte> c){
return Collections.max(c);
}
}
If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided.
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Max{
public static void main(String[] args){
Collection<Num> numl = new ArrayList<Num>();
numl.add(new Num(“2″));
numl.add(new Num(“6″));
numl.add(new Num(“3″));
numl.add(new Num(“1″));
numl.add(new Num(“5″));
numl.add(new Num(“4″));
System.out.print(“Max element is ” + getMax(numl).getNum());
}
public static Num getMax(Collection<Num> c){
return Collections.max(c);
}
}
class Num implements Comparable<Num>{
private String i;
public Num(String i){
this.i = i;
}
public int compareTo(Num num){
int x = i.compareTo(num.i);
return x;
}
public String getNum(){
return i;
}
}
45.How can I create an immutable List consisting of n Copies of an Object ? nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the returned List. Both attempts will throw UnsupportedOperationExceptions.
public static <T> List<T> nCopies(int n, T o)
import java.util.List;
import java.util.Collections;
public class NCopiesTest{
public static void main(String[] args){
List<String> slist = Collections.nCopies(5, “Java Blend”); //immutable list!
slist.add(“Moca Blend”); // throws UnsupportedOperationException!
String selement = slist.remove(0); // throws UnsupportedOperationException!
}
}
46.What is the difference between a Stack and a Queue ? First things first. Where can Stacks and Queue’s be found? Java provides a Stack class, which can be found within the java.util namespace. Within the same namespace you will find a Queue interface. All concrete Queue implementations can be located within the java.util.concurrent package.
What is a Stack?
Java’s Stack class extends the Vector class. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). The Stack class provides operations that allow testing for zero elements, inspection of it’s top most element, removal of it’s top most element, and the addition of elements.
boolean empty() Tests if this stack is empty.
E peek() Looks at the object at the top of this stack without removing it from the stack.
E pop() Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item) Pushes an item onto the top of this stack.
int search(Object o) Returns the 1-based position where an object is on this stack.
What is a Queue?
A Queue is also a Collection of Objects similar to a Stack. Queues typically order the elements contained within in FIFO order but this is not always the case. Elements that are inserted into a Queue are inserted at the tail end as opposed to a Stack where the elements are pushed into it at the head. Looking at the Queue interface the operations are similar to what a Stack provides.
E element() Retrieves, but does not remove, the head of this queue.
boolean offer(E o) Inserts the specified element into this queue, if possible.
E peek() Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
E poll() Retrieves and removes the head of this queue, or null if this queue is empty.
E remove() Retrieves and removes the head of this queue.
So what are the differences between Queues and Stacks?
Besides how each order their elements there really isn’t much difference. Both provided pretty much the same operations. The big difference is that one is a concrete implementation (Stack) while the other is an interface (Queue) thus implying that additional functionality is provided by the concrete classes that implement the Queue interface such as blocking, and synchronization.
47.How can I insert an element into a List ? In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index > size() an exception will be thrown.
import java.util.*;
public class Insert{
public static void main(String[] args){
List<String> slist = new ArrayList<String>();
slist.add(new String(“Java”));
slist.add(new String(“Write”));
slist.add(new String(“run”));
slist.add(new String(“anywhere!”));
slist.add(2,new String(“once”));
for(String s:slist){
System.out.println(s);
}
}
}
48.How do I make a copy of an array ?The clone() in Clonable interface allows to make a copy of the array. In the previous case i.e. arraycopy() we must mention the source array,the source offset(starting position),the destination array,the destination offset(Starting position),and the final one is the number of elements to be copied.This method is useful when you copy a part of the array to a new one. But when we need to copy a whole array to another,then we need not mention all the arguments and have a tough time instead we go for clone() method.In case of the clone() we need to mention the source array and destination array. eg: Array a2=a1.clone(); here the elements of the Array a1 is copied to the Array a2.If we add new elements in Array a1 it will not be reflected in a2.For doing so we need to use the Object refrences.
49.What is the purpose of the CopyOnWriteArrayList and CopyOnWriteArraySet collections ?
Synchronized operations are costly and if you aren’t modifying a collection much, it is best not to synchronize all collection accesses. The CopyOnWriteXXX collections avoid concurrent modification issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store. Think of CopyOnWriteArrayList as a thread-safe version of ArrayList without the syncrhonized access limitations. CopyOnWriteArraySet acts as like a Set, backed by a CopyOnWriteArrayList.
50.What implementations of the Deque interface does Java offer ? ArrayDeque offers an array backed deque. LinkedList offers a linked list version. LinkedBlockingDeque offers an optionally bounded blocking version.
51.Why do I keep getting an UnsupportedOperationException thrown when I try some collection operations ? Several methods of the collection interfaces are considered optional. If an unsupported operation is called, that is when you’ll see the UnsupportedOperationException thrown. The javadoc for a collection implementation should document which methods are optional.
53.Is it better to use a for-each loop or an Iterator with a collection ?
It depends on what you need to do. The remove() method of an Iterator is the safe way to remove elements from an underlying collection. You can’t safely remove elements with a for-each loop. For just “visiting” each element, either way works.
54.How can I detect if a duplicate is added to a Set ? The add() method returns a boolean. If the set did not previously contain the element, true is returned. If the set previoulsy did contain the element, false is returned. Of course, you can also check with the contains() method to see if the element is contained in the Set first.
55.What is a multimap ? A multimap is a map where a single key can map to multiple values.(And a value can be associated with multiple keys.)
54.How do I create a multimap in Java ? Typically a Map maps a key to a single value. To have a multimap, the values of a Map should be a List instead. Thus there can be multiple values in the List associated with a single key.
56.What is the natural ordering of a Boolean? Does FALSE come first or second ? Boolean.FALSE < Boolean.TRUE
57.What does Class<String> mean ? Class<String> is the generics way of writing String.class. It allows you to improve type safety.
58.What type of data structure would you use to store java objects (Element) with the following requirements ? I.
Created/loaded only once
Elements are frequently read by multiple threads
No updates (add/remove) to the data structure are required once loaded
Order is not important
Random object access is required by a unique key search.
Answer: HashMap
II.
Created once
Elements are added / removed in a multi threaded environment
Elements are frequently read in a multi threaded environment
Order is not important
Random object access is required by a unique key search.
Answer: HashTable is synchronized
III.
Created/loaded only once
Elements are frequently read in a multi threaded environment
Elements are added / removed in a multi threaded environment
Elements are frequently read in a multi threaded environment
Order is important
Random object access is require based on an index
Duplicate objects allowed
Answer: Vector is synchronized
IV.
Created once
Order is important
Random object access is require based on an index
Elements are frequently read in a multi threaded environment
Answer: ArrayList