How to Create Sitemap - Make Sitemap Generator

How to make Sitemap or Sitemap Generator

People always search on google to generate sitemap for own website. There are two popular versions of a site map. An XML Sitemap is a structured format that a user doesn't need to see, but it tells the search engine about the pages in a site, their relative importance to each other, and how often they are updated. HTML sitemaps are designed for the user to help them find content on the page, and don't need to include each and every subpage.
            Here, I will not give information how to make sitemap but I will teach you how to make your own sitemap generator, So Web Developers can easily make sitemap.

 Lets Make your own Sitemap Generator

Follow below steps:

Step 1:
Make HTML file with name Sitemap.html
Here is code
 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>Sitemap Ganerator</title>     
   </head>  
   <body>  
     <h1>Sitemap</h1>  
     <table>  
       <tr>  
         <td width="200px">Enter links:</td>  
         <td>  
           <Textarea name="recommend" rows="22" id="txtOutput" cols="100"></Textarea>  
         </td>  
       </tr>  
     </table>  
     <button id="DownloadButton">Create file</button>  
     <div id="generated" style="display:none">  
       <h2>sitemap.xml</h2>  
       <a href="#" id="DownloadLink">Download</a>  
       <textarea id="ResultXml" style="width: 100%; height: 30em" readonly="readonly"></textarea>  
     </div>    
  </body>  
 </html>  

Step 2:
Put below code before </head>. Its JS source files.
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>  
 <script type="text/javaScript" src="sitemap.js"></script>  

Step 3:
Make JavaScript file with name sitemap.js
Here is code
 $(function() {  
         $('#DownloadButton').click(update);  
       });  
       var template = [  
         '<?xml version="1.0" encoding="UTF-8"?>',    '<urlset',  
         'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"',  
         'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',  
         'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9',  
         'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">',  
         '<!-- Code by Rakesh Patil, Protected with DMCA-->',  
         '<?loc?>',  
         '</urlset>'  
       ].join('\r\n');  
       function update() {  
         var $root = $('<XMLDocument />');  
         $(document).ready(function() {  
           var arrayOfLines = $('textarea[name=recommend]').val().split('\n');  
           $.each(arrayOfLines, function(index, item) {  
             $root.append  
                 (  
                     $('<url />').append  
                     (  
                         $('<loc />').append(item),  
                         $('<priority />').append('1'),  
                         $('<changefreq />').append('monthly')  
                         )  
                     );  
             var variables = {  
               'loc': $root.html()  
             };  
             var newXml = template.replace(/<\?(\w+)\?>/g, function(match, name) {  
               return variables[name];  
             });  
             $('#ResultXml').val(newXml);  
             $('#DownloadLink')  
                 .attr('href', 'data:text/xml;base64,' + btoa(newXml))  
                 .attr('download', 'sitemap.xml');  
             $('#generated').show();  
           });  
         });  
       }  
       if (!window.btoa) {  
       btoa = function (input) {  
       var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';  
           var result = '';  
           var chr1, chr2, chr3;  
           var enc1, enc2, enc3, enc4;  
           var i = 0;  
           do {  
       chr1 = input.charCodeAt(i++);  
           chr2 = input.charCodeAt(i++);  
           chr3 = input.charCodeAt(i++);  
      enc1 = chr1 >> 2;  
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);  
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);  
      enc4 = chr3 & 63;  
      if (isNaN(chr2)) {  
       enc3 = enc4 = 64;  
      } else if (isNaN(chr3)) {  
       enc4 = 64;  
      }     
      result += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);  
     } while (i < input.length);     
     return result;  
    };  
   }   

Step 4:
Save all files in one folder and open Sitemap.html in browser. Done.
Now your own sitemap generator is ready to make sitemap for your website.
If any query or problem, free to ask via comment.
Note: Don't use above code to publish on website or blog.

Read More...

Java Filter Problem Solution

           A filter is an object that is used to perform filtering tasks such as conversion, log maintain, compression, encryption and decryption, input validation etc. I'm not going to discuss about Java filter tutorial or javax filter tutorial here, there are many sites and books provide good tutorial for how to use java servlet filter in application.
           One common problem to exclude css, javaScript or any image and icon content with Java Filter in Java Web Application. Its a particular issue when during authentication via filter in java web application. Here I explain how to out from problem with java filter in java web application.

For example if we want to exclude css which in use with before authentication or home page accessible without even being logged in, we can add below code to resolve the issue.
 if(uri.endsWith("css")){  
       this.context.log("Unauthorized access request");  
       res.sendRedirect("Home.html");  
     }else{  
       // pass the request along the filter chain  
       chain.doFilter(request, response);  
     }  
Do same as with javaScript or jQuery file
 if(uri.endsWith("js")){  
       this.context.log("Unauthorized access request");  
       res.sendRedirect("Home.html");  
     }else{  
       // pass the request along the filter chain  
       chain.doFilter(request, response);  
     }  
 we can also use regular expressions or regex
 if(uri.matches(".*(css|js|jpg|jpeg|png)")){  
       this.context.log("Unauthorized access request");  
       res.sendRedirect("Home.html");  
     }else{  
       // pass the request along the filter chain  
       chain.doFilter(request, response);  
     }  

So this is the easy way to make pages or contents becomes accessible without even being logged in with Java Filter in Java Web application
If anyone have any query or problem then free to ask via comment.
Read More...

File Handling using Input-Output Streams in Java

        Java provides an extensive library of classes for managing input and output of all forms of data. These classes are built around a stream model. You can think of a stream as a sequence of characters (in the case of textual data) or bytes (in the case of binary data) that can be accessed in order. A stream can represent many different kinds of sources and destinations, disk files, devices, other programs, etc. Streams support many different kinds of data simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. Data is transferred to devices by streams. There is a better approach created to File handling using input output Stream in Java.
The goal of InputStream and OutputStream is to abstract different ways to input and output: whether the stream is a file, a web page, or the screen shouldn't matter. All that matters is that you receive information from the stream. The java.io package contains a full set of Input and Output streams; Java programs use input streams to read data from some input source and output streams to write data to some output source. Input and output sources can be anything that can contain data: a file, a string, or memory.

Java views a file as a stream of bytes. File ends with end-of-file marker or a specific byte number. File as a stream of bytes associated with an object.
 
Java also associates streams with devices 
  •      System.in, System.out, and System.err 
  •      Streams can be redirected
You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.

Java I/O Stream can be defined as below 3 types:

1. Byte Streams

Programs use byte streams to perform input and output of 8-bit bytes. Byte Streams classes are rooted as
  • InputStream
  • OutputStream
There are many byte stream classes for example FileInputStream and FileOutputStream. Following example shows how to use these classes to copy file.

Example to copy a file
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 public class CopyBytes { public static void main(String[] args) throws IOException  
 {  
   FileInputStream in = null;  
   FileOutputStream out = null;  
   try {  
     in = new FileInputStream(“myfile.txt");  
     out = new FileOutputStream("outagain.txt");  
     int c;  
     while ((c = in.read()) != -1) {  
       out.write(c); }  
   } finally {  
      if (in != null) {  
       in.close();  
     }  
     if (out != null)  
     { out.close(); }  
   }} }  
Important Methods
  • int read() : Reads a byte of data from this input stream
  • int read(byte[] b) : Reads up to b.length bytes of data from this input stream into an array of bytes
  • void write (int b) : Writes the specified byte to this file output stream.
  • void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream.
  • void close() : Closes the file input and output streams and releases any system resources associated with the stream

2. Character Streams

The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set. Root Classes for Character Streams
  • Reader Class
  • Writer Class (both are abstract)
Character streams are often “wrappers” for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

Copy Characters Example
 import java.io.FileReader;  
  import java.io.FileWriter;  
 import java.io.IOException;  
 public class CopyCharacters {  
   public static void main(String[] args) throws IOException {  
   FileReader inputStream = null;  
   FileWriter outputStream = null;  
    try {  
     inputStream = new FileReader(“myfile.txt");  
     outputStream = new FileWriter("characteroutput.txt");  
     int c;  
     while ((c = inputStream.read()) != -1)  
        { outputStream.write(c); }  
     } finally {  
        if (inputStream != null)  
       { inputStream.close();  
       } if (outputStream != null)  
       { outputStream.close();  
   } } } }  
Input and Output Streams
Can read from these streams. Root classes of all input streams:
  • The InputStream Class
  • The Reader Class
Output or sink (destination) streams. Can write to these streams. Root classes of all output streams:
  • The OutputStream Class
  • The Writer Class
Control Flow of an I/O operation
  1. Create a stream object and associate it with a datasource (data-destination)
  2. Give the stream object the desired functionality through stream chaining while (there is more information)
  3. read(write) next data from(to) the stream
  4. close the stream

3. Buffered Streams

The examples shown so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer. Similarly, buffered output streams write data to a buffer. A program can convert an unbuffered stream into a buffered stream using the wrapping.
 inputStream = new BufferedReader(new FileReader("xanadu.txt"));  
 outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));  
Example
There are four buffered stream classes used to wrap unbuffered streams:
  • BufferedInputStream
  • BufferedOutputStream (create buffered byte streams )
  • BufferedReader
  • BufferedWriter (create buffered character streams )
Flushing Buffered Streams
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered. Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format
CopyLine Example
 import java.io.FileReader;  
 import java.io.FileWriter;  
  import java.io.BufferedReader;  
 import java.io.PrintWriter;  
 import java.io.IOException;  
 public class CopyLines { public static void main(String[] args) throws IOException {  
 BufferedReader  inputStream = null;  
 PrintWriter  outputStream = null;  
 try {  
   inputStream = new BufferedReader(new FileReader("xanadu.txt"));  
   outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));  
 String l;  
  while ((l = inputStream.readLine()) != null) {  
   outputStream.println(l); }  
   } finally { if (inputStream != null)  
     { inputStream.close(); } if (outputStream != null)  
     { outputStream.close(); } } } }  
I/O from the Command Line
The Java platform supports three Standard Streams:
  • Standard Input, accessed through System.in;
  • Standard Output, accessed through System.out; and
  • Standard Error, accessed through System.err
These standard streams are byte streams. To use Standard Input as a character stream, wrap System.in in InputStreamReader.

ReadingLine Example
 import java.io.*;  
 public class ReadString {  
   public static void main (String[] args) {  
       System.out.print("Enter your name: ");  
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
    String  userName = null;  
    // read the username from the command-line;  
    try {  
      userName = br.readLine();  
    } catch (IOException ioe) {  
        System.out.println("IO error trying to read your name!");  
        System.exit(1);  
    }  
    System.out.println("Thanks for the name, " + userName);  
   }  
 } // end of ReadString class  

Hope you get better understanding from above article about Java I/O streams.

Read More...

JSch: SCP a File in Java

If you want to upload a file to another computer, SCP is an excellent way to go. And if you want to do it from within a Java program, your best bet is to use the JSch library from JCraft. They've implemented the SSH protocol purely in Java, and it works splendidly. I've written a nice little class that encapsulates the action of sending a file.

Using the class is pretty simple. It goes like this:
 FileSender fs = new FileSender("172.16.40.128", "user", "user");  
 boolean ret = fs.sendFile("/home/sschulte/Desktop/AllPhysics.wmv", "AllPhysics.wmv");  
The constructor takes a host, a username, and a password. The sendFile() method takes a source filename and a destination filename. It returns true if the upload was successful, false if it failed.

I developed it in Netbeans, and in order to use JSch, the first step is to download the JAR and add it as a library in your project. (When I first tried it, I downloaded the ZIP instead, and added the source to my project; this works, but it's not necessary to compile this library along with your project unless you plan to edit it. I didn't.)

Most of the code in this class is taken from the ScpTo example included in the ZIP file. I recommend reading it. Something to pay close attention to, however, is the SSH known_hosts file. Their example file doesn't take this into account, so if you just run their code, you get an unknown host exception and it doesn't work. So be sure to include the following:
 String knownHostsFilename = "/home/sschulte/.ssh/known_hosts";  
 jsch.setKnownHosts(knownHostsFilename);  
(This is, of course, after you instantiate your JSch object.)

I like it, and it works. But it definitely needs a few things before I'm satisfied.
  • Read the known_hosts filename from a config file, rather than compiling it into the code.
  • Have a config file for the host/username/password information, possibly for multiple hosts at once.
  • Throw exceptions for various types of failures, rather that simply returning false.
Read More...

Learn inner classes in Java


Inner class, also called Nested class, is a non-static class which is defined inside another class. Inner classes are nothing but classes that are defined within other classes. The nesting is a relationship between classes, not objects.
They may be defined as public, protected, private, or with package access. They may only be used "in the context" of the containing class (outer class, or enclosing class), unless they are marked as static

Java inner classes have feature that makes them richer and more useful. An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM.

Inner Classes:


  • The outer class (the class containing the inner class) can instantiate as many number of inner class objects as it wishes, inside it’s code.
  • If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  • No inner class objects are automatically instantiated with an outer class object.
  • If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.
  • Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a varible with same name then the outer class’s variable can be accessed.
There are two more types of inner classes, i.e local inner classes & anonymous inner classes. The local inner class are defined within a method. Anonymous inner classes are also defined with in a method but have no name.


Local Inner Classes:


  • Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.
  • Local classes have a great advantage: they are completely hidden from the outside world.
  • They can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local varible has to be declared final.

Anonymous Inner Classes:

When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name.
Such a class is called an anonymous inner class. Usually the inner class extend some interface or extend other class.



  • Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. Or SuperType can be a class; then, the inner class extends that class.
  • An anonymous inner class cannot have constructors because the name of a constructor must be the same as the name of a class, and the class has no name. Instead, the construction parameters are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction parameters.

  • It is recommended to refrain from using them as many programmers find too many anonymous classes hard to read.

Static Inner Classes:


  • Static members of the outer class are visible to the static inner class, what ever their access level be.
  • Non-static members of the outer class are not available, because there is not instance of the outer class.
  • An inner class may not have static members unless the inner class is itself marked as static.
  • Sometimes static nested class are not refered to as inner class at all, as they don’t require outer classes instance.
  • A static inner class is just like any other inner class, but it dose not have the reference to its outer class object that generated it.
  • The outer class can call even the private methods of the inner class.

Example for Inner Classes:

public class OuterClass {
 private int x;
 OuterClass(int x, int y) {
  this.x = x;
  new InnerClass(y).privateDisplay();
 }
 public class InnerClass {
  private int y;
  InnerClass(int y) {
   this.y = y;
  }
  private void privateDisplay() {
   System.out.println("privateDisplay x = " + x + " and y = " + y);
  }
  public void publicDisplay() {
   System.out.println("publicDisplay x = " + x + " and y = " + y);
  }
 }
}

Explanation of above example:
  • OuterClass has one property, x; the inner class InnerClass has one property, y
  • the OuterClass constructor accepts two parameters; the first is used to populate x
  • it creates one InnerClass object, whose y property is populated with the second parameter
  • note that the inner class has free access to the private outer class x element
  • and the outer class has free access to the private inner class privateDisplay() method
The connection between the two classes is handled automatically

Read More...

Learn Overriding in Java


Overriding is nothing but giving the implentation to the method in the derived class.Here method signature is same. Method overriding occurs when sub class declares a method that has the same signature (name, plus the number and the type of its parameters) and return type as a method declared by one of its superclass.
Overriding is happening with in super class and sub class. Overriding is the process where the sub class changes the behavior of super class and updates it according to sub class requirement. There are some rules for method overriding.

o    Access level of the method in the sub class should be same or wider as super class method.
o   The return type and the signature of the method in sub class      should be same as super class.
o    Static method can be overriding.
o    Dynamic binding or late binding happens in method overriding.
o    Final method cannot be overridden.
o    Constructors cannot be overridden. 

Also keep in mind below points about Overriding methods:
  •  late-binding also supports overriding
  •  overriding allows a subclass to re-define a method it inherits from it's superclass
  •  overriding methods:
1.     appear in subclasses
2.     have the same name as a superclass method
3.     have the same parameter list as a superclass method
4.     have the same return type as as a superclass method
5.     the access modifier for the overriding method may not be more    restrictive than the access modifier of the superclass method
  •   if the superclass method is public, the overriding method must be public
  •  if the superclass method is protected, the overriding method may be protected or public
  •  if the superclass method is package, the overriding method may be packagage, protected, or public
  •  if the superclass methods is private, it is not inherited and overriding is not an issue
6.     the throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses

 Example:

class Parent
{
    int num, num1;
    Parent(int num, int num1)
    {
        this.num = num;
        this.num = num1;
    }
    void show()
    {
        System.out.println("The values in num and num1 are: " +num+" " +num1);
    }
}
class Child extends Parent  //inherited class
{
    int count;
    Child(int num, int num1, int num2)
    {
        super(num, num1);
        count = num2;
    }
    void show()
    {
        System.out.println("The values in count is: " +count);
    }
}
class OverrideDemo
{
    public static void main(String args[])
    {
        Child sObj = new Child(5, 10, 15);
        sObj.show();
    }
}
 The program will generate the following output:

     The  values in count is: 15




Read More...

Learn Overloading in Java


Overloading is defining more than one set of statement with same name but different signature. Method overloading means  to have two or more methods with same name  in the same class and its subclass with different arguments and optionally different return type. Which overloaded version of the method to be called is based on the reference type of the argument passed at compile time. As the constructor name should be as class name, Overloading can be apply by writing more than one constructor with different type of parameters and their different order.

Some rules we must know about overloading in Java

  •  Overloaded methods must change the argument list.
  •  Overloaded methods can change the return type.
  •  Overloaded methods can declare new or broader checked exacpetions
  •  Overloaded methods can change the access modifier.
  •  Constructors can be overloaded.
 
Also keep in mind below points about overloaded methods:

  1.    appear in the same class or a subclass
 2.    have the same name but,
 3.    have different parameter lists, and,
 4.    can have different return types   
 
 
Example for Constructor overloading:

public class Person {
    String name;
    int age;
    public Person() {
        // do somthing
    }
    public Person(String name, int age) {
        // do somthing
    }
    public Person(int age, String name) {
        // do somthing
    }
    public Person(int age) {
        // do somthing
    }
    public Person(String name) {
        // do somthing
    }
}
In the above example class Person has five different type of constructor with different parameters and their order.
Example for Method overloading:   
public class Person {
    String name;
    int age;
    public void doStuff() {
        // do something
    }
    public void doStuff(String name) {
        // do something
    }
    public void doStuff(int age) {
        // do something
    }
    public void doStuff(String name, int age) {
        // do something
    }
    public void doStuff(int age, String name) {
        // do something
    }
}

In the above example of method overloading the doStuff() method of Person class is overloaded many time with different parameter and parameter order.

Read More...

Learn Inheritace in Java


Java Inheritance is an object oriented concept that enables deriving new class from an already existing class. To know the concept of inheritance clearly you must have the idea of class and its features like methods, data members, access controls, constructors, keywords this, super etc. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. Inheritance is the mechanism through which we can derived classes from other classes. The derived class is called as child class or the subclass or  we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used.
For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class.
A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.

Types of Java Inheritance are:
  • Single Inheritance – Single Inheritance is a type of Java Inheritance in which the derived class will have only one super class or base class. Single Inheritance is implemented using Java Class.
  • Hierarchical Inheritance – Hierarchical Inheritance is a type of Java Inheritance in which one base class can have many derived classes inherited from it. Hierarchical Inheritance is implemented using Java Class.
  • Multilevel Inheritance – Multilevel Inheritance is a type of Java Inheritance in which the derived class can be derived further by another derived class to any number of levels. Multilevel Inheritance is implemented using Java Class.
  • Multiple Inheritance – Multiple Inheritance is a type of Java Inheritance in which the derived class will have several super classes or base classes. Multiple Inheritance is implemented using Java Interfaces. 
Example: 

class Box {

 double width;
 double height;
 double depth;
 Box() {
 }
 Box(double w, double h, double d) {
  width = w;
  height = h;
  depth = d;
 }
 void getVolume() {
  System.out.println("Volume is : " + width * height * depth);
 }
}

public class MatchBox extends Box {

 double weight;
 MatchBox() {
 }
 MatchBox(double w, double h, double d, double m) {
  super(w, h, d);
  weight = m;
 }
 public static void main(String args[]) {
  MatchBox mb1 = new MatchBox(10, 10, 10, 10);
  mb1.getVolume();
  System.out.println("width of MatchBox 1 is " + mb1.width);
  System.out.println("height of MatchBox 1 is " + mb1.height);
  System.out.println("depth of MatchBox 1 is " + mb1.depth);
  System.out.println("weight of MatchBox 1 is " + mb1.weight);
 }
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0


Read More...

Corrected Interview Quetions and Answers

Anything that simple is too easy to look up. Questions like that are asked to gauge whether you understand the language that you claim to be experienced in. When you gave the wrong answer, that told the interviewer that your understanding is rather shallow. Review these typical interview questions and think about how you would answer them. I am not suggesting that every one should go contracting but by performing well at the interviews you can be in a position to pick the permanent role you like and also be able to negotiate your salary package. Those of you who are already in good jobs can impress your team leaders, solution designers and/or architects for a possible promotion by demonstrating your understanding of the key areas discussed in this book.
You can discuss with your senior team members about performance issues, transactional issues, threading issues (concurrency issues) and memory issues. In most of my previous contracts I was in a position to impress my team leads and architects by pinpointing some of the critical performance, memory, transactional and threading issues with the code and subsequently fixing them. Trust me it is not hard to impress someone if you understand the key areas.

For example:
-Struts action classes are not thread-safe
-JSP variable declaration is not thread-safe
-Valuable resources like database connections should be closed properly to avoid any memory and performance issues 
-Throwing an application exception will not rollback the transaction in EJB.

The other key areas, which are vital to any software development, are a good understanding of some of key design concepts, design patterns, and a modeling language like UML. 
These key areas are really worthy of a mention in your
resume and interviews.

For example:
-Know how to use inheritance, polymorphism and encapsulation. -Why use design patterns? 
-Why is UML important?If you happen to be in an interview with an organization facing serious issues with regards to their Java application relating to memory leaks, performance problems or a crashing JVM etc then you are likely to be asked questions on these topics. 

Read the questions and answers listed; you will also find some strategy suggestions with it.

Q:What is not possible using java class Inheritance?
A:1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).


Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 


Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 

Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.

Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.

Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Read More...