Sunday, 31 March 2013

OCJP Exam Details, Syllabus, Book and Dumps.

OCJP Exam Details, Syllabus, Book and Dumps.


 OCJP stands for Oracle Certified Java Programmer. This is the basic certification in the field of java. Say, you want to be an Android programmer, J2EE programmer or in any other Java technology, this certification is the most basic one. For many other certifications OCJP is kind of  prerequisite. Believe me it's  good to have it in your resume in early stages of your career.
              The latest version of OCJP is OCJP 6, which is for jdk version 6. The syllabus for OCJP is basic or say core java only. There are many books  in the market for OCJP preparation. But  "Sun Certified Programmer For Java 6 Study Guide" by Kathy Sierra is simple and good one. Yes! That book with thinking statue on it's front cover.
You can download soft copy of that book from here.
             The exam is for 150 minutes with 72 questions. Passing score is just 61%. There used to be drag and drop questions, even you will find many in books and dumps. I said “there used to be”, because I think recently these kind of questions have been removed from the exam. But it’s good to be on safer site and prepare few of their type.


The syllabus for scjp is as follows :
  1.  Declaration and access control
  2.  Object declaration
  3.  Assignments
  4.  Operators
  5.  Flow control, exceptions and assertions
  6.  String ,I/O, formatting and parsing
  7.  Generics and collections
  8.  Inner classes
  9.  Threads
           These are just names of the chapters from the book which covers all the syllabus. Actually you need not to worry about exact syllabus, as that is generally stated in very vague form which is very unclear from exam point of view. At first glans this seems too easy, but tiny details of java covered in the syllabus are quite tricky and interesting to learn.
             I would suggest you to read this book and solve questions from it for detailed knowledge of the language. But if you don't have that much time or interest in it, you also can read dumps for OCJP. You can also solve these dumps after reading the book, just for extra fun.
You can download dumps for OCJP 6 from here.
                                        


                                               ALL THE BEST                                                                      


Java (JVM) Memory Types

Java has only two types of memory when it comes to JVM. Heap memory and Non-heap memory. All the other memory jargons you hear are logical part of either of these two.

Heap Memory

Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.

Non-heap Memory

It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.

Method Area

As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.
The above three (heap memory, non-heap memory and method area) are the main jargon when it comes to memory and JVM. There are some other technical jargon you might have heard and I will summarize them below.

Memory Pool

Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.

Runtime Constant Pool

A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area.jvm memory

Java Stacks or Frames

Java stacks are created private to a thread. Every thread will have a program counter (PC) and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for methods and dispatch exceptions. This is used in the place of registers.

Memory Generations

HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into and they are called young generation and old generation.

Young Generation

Young generation memory consists of two parts, Eden space and survivor space. Shortlived objects will be available in Eden space. Every object starts its life from Eden space. When GC happens, if an object is still alive and it will be moved to survivor space and other dereferenced objects will be removed.

Old Generation – Tenured and PermGen

Old generation memory has two parts, tenured generation and permanent generation (PermGen). PermGen is a popular term. We used to error like PermGen space not sufficient.
GC moves live objects from survivor space to tenured generation. The permanent generation contains meta data of the virtual machine, class and method objects.

Discussion:

Java specification doesn’t give hard and fast rules about the design of JVM with respect to memory. So it is completely left to the JVM implementers. The types of memory and which kind of variable / objects and where they will be stored is specific to the JVM implementation.

Key Takeaways

  • Local Variables are stored in Frames during runtime.
  • Static Variables are stored in Method Area.
  • Arrays are stored in heap memory.

References:

Difference between forward and sendRedirect

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.
‘session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.

When can we use forward and when can we use sendRedirect?

Technical scenario: redirect should be used
  1. If you need to transfer control to different domain
  2. To achieve separation of task.
For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.

Example for forward and sendRedirect based on real world

Consider the real world scenario, the milk man comes and asks for monthly payment to you in your house. Here house is the container and you are a resource existing in the container. Milk man is the client or browser.
He asks for the monthly payment to you, this is the request made by the browser to resource A. If you go inside your house and ask your mother (another resource B inside the same container) for the cash and come back and deliver to milkman this is called forward.
If you ask the milkman to speak himself to your mother inside your house or you ask the milkman to speak to your father who is in his office (different domain) then this is called redirect.

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency.

Eclipse Shortcuts

Editors are an integral part of a programmer’s life. If you have good proficiency in using an editor thats a great advantage. It comes very handy to debug. Traditional notepad and SOPs (System.out.println) are the way we start learning a language but that is not sufficient, so beginners start using an IDE and most importantly know the shortcuts.
For java developers there is a huge list and some popular areEclipse, Netbeans, IntelliJ Idea. I use Eclipse as my IDE and vim as a light weight editor.

This article is for those who use or intend to use Eclipse as IDE. Keyboard shortcuts are very important for comfortable and quick editing. I have abridged the following list of eclipse shortcuts from my own experience and literature.
There is a huge list of eclipse shortcuts available but I have listed only the most essential ones that you may need daily

File Navigation – Eclipse Shortcuts

  • CTRL SHIFT R – Open a resource. You need not know the path and just part of the file name is enough.
  • CTRL E – Open a file (editor) from within the list of all open files.
  • CTRL PAGE UP or PAGE DOWN – Navigate to previous or next file from within the list of all open files.
  • ALT <- or ALT -> – Go to previous or next edit positions from editor history list.

Java Editing – Eclipse Shortcuts

  • CTRL SPACE – Type assist
  • CTRL SHIFT F – Format code.
  • CTRL O – List all methods of the class and again CTRL O lists including inherited methods.
  • CTRL SHIFT O – Organize imports.
  • CTRL SHIFT U – Find reference in file.
  • CTRL / – Comment a line.
  • F3 – Go to the declaration of the variable.
  • F4 – Show type hierarchy of on a class.
  • CTRL T – Show inheritance tree of current token.
  • SHIFT F2 – Show Javadoc for current element.
  • ALT SHIFT Z – Enclose block in try-catch.

General Editing – Eclipse Shortcuts

  • F12 – Focus on current editor.
  • CTRL L – Go to line number.
  • CTRL D – Delete a line.
  • CTRL <- or -> – Move one element left or right.
  • CTRL M – Maximize editor.
  • CTRL SHIFT P – Go to the matching parenthesis.

Debug, Run – Eclipse Shortcuts

  • CTRL . or , – Navigate to next or previous error.
  • F5 – Step into.
  • F6 – Step over.
  • F8 – Resume
  • CTRL Q – Inspect.
  • CTRL F11 – Run last run program.
  • CTRL 1 – Quick fix code.

Search – Eclipse Shortcuts

  • CTRL SHIFT G – Search for current cursor positioned word reference in workspace
  • CTRL H – Java search in workspace.

Saturday, 30 March 2013

Differentiate JVM JRE JDK JIT


   Java Virtual Machine (JVM) is an abstract computing machine. Java Runtime Environment (JRE) is an implementation of the JVM. Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.
JVM becomes an instance of JRE at runtime of a java program. It is widely known as a runtime interpreter. The Java virtual machine (JVM) is the cornerstone on top of which the Java technology is built upon. It is the component of the Java technology responsible for its hardware and platform independence. JVM largely helps in the abstraction of inner implementation from the programmers who make use of libraries for their programmes from JDK.
Diagram to show the relations between JVM JRE JDK
Diagram to show the relations between JVM JRE JDK

JVM Internals

Like a real computing machine, JVM has an instruction set and manipulates various memory areas at run time. Thus for different hardware platforms one has corresponding implementation of JVM available as vendor supplied JREs. It is common to implement a programming language using a virtual machine. Historicaly the best-known virtual machine may be the P-Code machine of UCSD Pascal.
A Java virtual machine instruction consists of an opcode specifying the operation to be performed, followed by zero or more operands embodying values to be operated upon. From the point of view of a compiler, the Java Virtual Machine (JVM)is just another processor with an instruction set, Java bytecode, for which code can be generated. Life cycle is as follows, source code to byte code to be interpreted by the JRE and gets converted to the platform specific executable ones.

Sun’s JVM

Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE. Sun’s JRE is availabe as a separate application and also available as part of JDK. Sun’s Java Development Tool Kit (JDK) comes with utility tools for byte code compilation “javac”. Then execution of the byte codes through java programmes using “java” and many more utilities found in the binary directory of JDK. ‘java’ tools forks the JRE. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JVM for other languages

A JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a Java virtual machine (JVM). That is, any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java virtual machine (JVM). Attracted by a generally available, machine-independent platform, implementors of other languages are turning to the Java virtual machine (JVM) as a delivery vehicle for their languages. PHP with Quercus is such an example.

Just-in-time Compiler (JIT)

JIT is the part of the Java Virtual Machine (JVM) that is used to speed up the execution time. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Servlet Jsp communication


getServletConfig().getServletContext().getRequestDispatcher(“jspfilepathtoforward”).forward(request, response);
The above line is essence of the answer for “How does a servlet communicate with a JSP page?”
When a servlet jsp communication is happening, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or on object itself.
Following is a servlet and JSP source code example to perform Servlet JSP communication. Wherein an object will be communicated to a JSP from a Servlet.

Following are the steps in Servlet JSP Communication:

1. Servlet instantiates a bean and initializes it.
2. The bean is then placed into the request
3. The call is then forwarded to the JSP page, using request dispatcher.
Example Servlet Source Code: (ServletToJSP.java)
public class ServletToJSP extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//communicating a simple String message.
		String message = "Example source code of Servlet to JSP communication.";
		request.setAttribute("message", message);

		//communicating a Vector object
		Vector vecObj = new Vector();
		vecObj.add("Servlet to JSP communicating an object");
		request.setAttribute("vecBean",vecObj);

		//Servlet JSP communication
		RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp");
		reqDispatcher.forward(request,response);
	}
}
Example JSP Source Code: (javaPapers.jsp)
<html>
<body>
<%
	String message = (String) request.getAttribute("message");
	out.println("Servlet communicated message to JSP: "+ message);

	Vector vecObj = (Vector) request.getAttribute("vecBean");
	out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
%>
</body>
</html>

Wednesday, 27 March 2013

Why String has been made immutable in Java?

Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.

Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.


As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.


Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java.
I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.

With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).

String Constructors in Java

Strings are almost unavoidable in any kind of application. The String class in Java provides a number of ways for creating instances of String class. This includes the overloaded constructors, de-serialization and string literals. Here we will see all the overloaded constructors which are present in the String class in Java:



String()
Initializes a newly created String object so that it represents an empty character sequence.

String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(byte[] ascii, int hibyte)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a charset name or that use the platform's default charset.

String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

String(byte[] ascii, int hibyte, int offset, int count)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a charset name or that use the platform's default charset.

String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.

String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.

String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument.

String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.

How to add comments to code

Adding comments to code is an important part of writing Java programs. Though it is recommended to add as many comments as possible in your code but still there are some best practices which if followed really make code commenting a useful affair not only for the developer himself but also fellow developers.

Here in this tutorial, I will list down some tips and guidelines for writing the code comments in a Java program:

1) Add comments for each ending block so that it is clear which code block is going to end.

While(...){
if (abc==xyz)
{
for(...) {
} //for
} //if
} //while

2) Format the comments so that they are properly aligned and break to next line if exceed the viewable area. This helps in getting rid of extra scrolling just to view the comments.

3) Use proper language and avoid frustating comments like:
a) //Finally got it
b) //hahahaha
c) //you can't escape from me

4) Comment out the code which could be reused in future but could not be implemented this time.

5) Focus on why part of the code and explain the need of code you are going to write.

6) Usually the bug id is also added when you are working on some enhancement/bug so that other developers can get the need for the code.

Tuesday, 26 March 2013

Java Annotations

       Annotation is code about the code, that is metadata about the program itself. In other words, organized data about the code, embedded within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
We have basic java comments infrastructure using which we add information about the code / logic so that in future, another programmer or the same programmer can understand the code in a better way. Javadoc is an additional step over it, where we add information about the class, methods, variables in the source code. The way we need to add is organized using a syntax. Therefore, we can use a tool and parse those comments and prepare a javadoc document which can be distributed separately.

Javadoc facility gives option for understanding the code in an external way, instead of opening the code the javadoc document can be used separately. IDE benefits using this javadoc as it is able to render information about the code as we develop. Annotations were introduced in JDK 1.5

Uses of Annotations

Annotations are far more powerful than java comments and javadoc comments. One main difference with annotation is it can be carried over to runtime and the other two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing.

In java we have been passing information to compiler for long. For example take serialization, we have the keyword transient to tell that this field is not serializable. Now instead of having such keywords decorating an attribute annotations provide a generic way of adding information to class/method/field/variable. This is information is meant for programmers, automated tools, java compiler and runtime. Transient is a modifier and annotations are also a kind of modifiers.
More than passing information, we can generate code using these annotations. Take webservices where we need to adhere by the service interface contract. The skeleton can be generated using annotations automatically by a annotation parser. This avoids human errors and decreases development time as always with automation.
Frameworks like Hibernate, Spring, Axis make heavy use of annotations. When a language needs to be made popular one of the best thing to do is support development of frameworks based on the language. Annotation is a good step towards that and will help grow Java.

When Not to Use Annotations
  • Do not over use annotation as it will pollute the code.
  • It is better not to try to change the behaviour of objects using annotations. There is sufficient constructs available in oops and annotation is not a better mechanism to deal with it.
  • We should not what we are parsing. Do not try to over generalize as it may complicate the underlying code. Code is the real program and annotation is meta.
  • Avoid using annotation to specify environment / application / database related information.
Annotation Structure

There are two main components in annotations. First is annotation type and the next is the annotation itself which we use in the code to add meaning. Every annotation belongs to a annotation type.
Annotation Type:
@interface <annotation-type-name> {
method declaration;
}
Annotation type is very similar to an interface with little difference.
  • We attach ‘@’ just before interface keyword.
  • Methods will not have parameters.
  • Methods will not have throws clause.
  • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.
  • We can assign a default value to method.
Meta Annotations

Annotations itself is meta information then what is meta annotations? As you have rightly guessed, it is information about annotation. When we annotate a annotation type then it is called meta annotation. For example, we say that this annotation can be used only for methods.
@Target(ElementType.METHOD)
public @interface MethodInfo { }
Annotation Types
  1. Documented
    When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.
  2. Inherited
    This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
  3. Retention
    This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Developer {
      String value();
    }
    • Class
      When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file.
    • Runtime
      The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation. I have give an example below.
    • Source
      This annotation will be removed at compile time and will not be available at compiled class.
  4. Target
    This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.
    @Target(ElementType.FIELD)
    public @interface FieldInfo { }
Built-in Java Annotations

@Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java.
Apart from these meta annotations we have the following annotations.
@Override
When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. This is not mandatory to use @Override when we override a method. But I have seen Eclipse IDE automatically adding this @Override annotation. Though it is not mandatory, it is considered as a best practice.
@Deprecated
When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning.
@SuppressWarnings
This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation.

Custom Annotations

We can create our own annotations and use it. We need to declare a annotation type and then use the respective annotation is java classes.
Following is an example of custom annotation, where this annotation can be used on any element by giving values. Note that I have used @Documented meta-annotation here to say that this annotation should be parsed by javadoc.
/*
 * Describes the team which wrote the code
 */
@Documented
public @interface Team {
    int    teamId();
    String teamName();
    String teamLead() default "[unassigned]";
    String writeDate();    default "[unimplemented]";
}
Annotation for the Above Example Type
... a java class ...
@Team(
    teamId       = 73,
    teamName = "Rambo Mambo",
    teamLead = "Yo Man",
    writeDate     = "3/1/2012"
)
public static void readCSV(File inputFile) { ... }
... java class continues ...
Marker Annotations

We know what a marker interface is. Marker annotations are similar to marker interfaces, yes they don’t have methods / elements.
/**
 * Code annotated by this team is supreme and need
 * not be unit tested - just for fun!
 */
public @interface SuperTeam { }
... a java class ...
@SuperTeam public static void readCSV(File inputFile) { ... }
... java class continues ...
In the above see how this annotation is used. It will look like one of the modifiers for this method and also note that the parenthesis () from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted.

Single Value Annotations

There is a chance that an annotation can have only one element. In such a case that element should be named value.
/**
 * Developer
 */
public @interface Developer {
    String value();
}
... a java class ...
@Developer("Popeye")
public static void readCSV(File inputFile) { ... }
... java class continues ...
How to Parse Annotation

We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation.
Example:
package com.javapapers.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
  String value();
}
package com.javapapers.annotations;
public class BuildHouse {
  @Developer ("Alice")
  public void aliceMethod() {
    System.out.println("This method is written by Alice");
  }
  @Developer ("Popeye")
  public void buildHouse() {
    System.out.println("This method is written by Popeye");
  }
}
package com.javapapers.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotation {
  public static void main(String args[]) throws SecurityException,
      ClassNotFoundException {
    for (Method method : Class.forName(
        "com.javapapers.annotations.BuildHouse").getMethods()) {
      // checks if there is annotation present of the given type Developer
      if (method
          .isAnnotationPresent(com.javapapers.annotations.Developer.class)) {
        try {
          // iterates all the annotations available in the method
          for (Annotation anno : method.getDeclaredAnnotations()) {
            System.out.println("Annotation in Method '" + method
                + "' : " + anno);
            Developer a = method.getAnnotation(Developer.class);
            if ("Popeye".equals(a.value())) {
              System.out.println("Popeye the sailor man! "
                  + method);
            }
          }
        } catch (Throwable ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}
Output:
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.aliceMethod()' : @com.javapapers.annotations.Developer(value=Alice)
Annotation in Method 'public void com.javapapers.annotations.BuildHouse.buildHouse()' : @com.javapapers.annotations.Developer(value=Popeye)
Popeye the sailor man! public void com.javapapers.annotations.BuildHouse.buildHouse()

apt / javac for Annotation Processing

In previous version of JDK apt was introduced as a tool for annotation processing. Later apt was deprecated and the capabilities are included in javac compiler. javax.annotation.processing and javax.lang.model contains the api for processing.

What are the steps performed while loading a java class?

                                         Every user defined class is loaded into the memory whenever it is referred.
On the other hand, the system classes present in the java package are loaded when the JVM starts up.

The steps followed while loading a Java class are:

1) Check if the class has been already loaded by any of the parent class-loaders. Since JVM has a hierarchy of class-loaders, particular class could be loaded at any earlier point of time by using the System, Classpath or User defined class loaders.

2) If the class is yet to be loaded then create static variables and execute static code blocks. The execution order of static blocks is same as the order in which they are defined.

3) If the class is to be loaded because it is referenced while creating an instance of that class then all the super class constructors are executed before executing this class's constructor. This is because HotSpot places "super();" statement as the first line of each constructor, but this can be changed by explicitly placing a class to some other constructor with or without arguments.

The above statements can be verified by executing the following program:



public class Test {


static {
System.out.println("hi");
}

public Test() {
this(2);
System.out.println("Constructor 1");
}

public Test(int a) {
System.out.println("Constructor 2");
}

public static void main(String[] args) {
System.out.println("main");
Test t = new Test();
t.a();
}

static {
System.out.println("hi 2");
}

public void a() {
System.out.println("aa");
}

static {
System.out.println("hi 3");
}
}




Output:
hi
hi 2
hi 3
main
Constructor 2

What is StringTokenizer class?

The StringTokenizer class helps in generating tokens of strings based on a delimiter. The constructor

of StringTokenizer class accepts a string and a delimiter as its input and then splits the supplied string by using the delimiter.



Please note that StringTokenizer class has issues with ASCII characters. So test before relying on this class.

e.g.

import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {
        StringTokenizer st = new StringTokenizer("abc,def", ",");
        while(st.hasMoreTokens()) {
            System.out.println(st.nextToken());
        }
    }
}
Output:

abc

What is the need of byte code in Java?

Though some programs can be made to run to specific hardware platforms by using platform specific

compiler/interpreter, but this requires that the programmer understands the platform before writing

the program and hence needs to write program specific to each platform.

The use of ByteCode results in common code for each platform and hence the programmer is releived of the responsibility to know the platform on which his program will run.

The Virtual Machine which is designed to be specific for each platform and runs the ByteCode seamlessly on any platform for which a Java Virtual Machine (JVM) is available.
 
 

What is the difference between yield and sleep methods?

Yield:

1) It causes the high priority threads to pause execution and give the low priority threads a chance to execute.
2) The thread going into waiting queue because of yield method release any locks held by them.

Sleep:

1) It causes the thread on which it is invoked to go into waiting state for some time interval.
2) The thread going into waiting queue because of yield method doesn't release any locks held by it.

Static method hiding

              Consider the following code:

public class And
{
public static void m(){}
And(){}
public static void main(String[] args) {
And2 a=new And2();a.m();// ya this doesnt work..so i was wrong all way
}
}
class And2 extends And
{
public static void m(){}
}

Here the same method m() is being defined in two classes. The second class is not overriding the m()

method in super class but is hiding it. This means that the JVM will not decide which method to

invoke based on the object in hand but rather based on the type of reference in hand. If the reference

 is of type "And" then And's version will be called and if the reference is of type "And2" then And's

version of static method

Tips to clear SCJP Exam

1) Give yourself atleast 3 months for preparation

2) Study at least one book preffered:K&B

3) Try writing the programs with experiments

4) Be very clear about overloading and overriding rules

5) Give 10-20 SCJP mock exams. Some are available on this blog at:
SCJP Mock exam archive

6) Be clever in ommiting options

7) Every question will have 2 fixed options (Compilation error and exception at runtime)

8) Look carefully to find how many choices are to be marked

9) Go on to solve questions that have less to read and easy to answer as by the end of SCJP exam you will be getting exhausted and loosing patience

10) First guess which concept is being tested and then bring out all the facts about that concept from the back of your mind.

11) There is an option to Mark the question so that before closing the test you can easily find which question you want to review. For each question you have doubt, check the checkbox labeled Mark at the top left corner.

Happy SCJP Cracking.
Leave your comments about this post.

Method overriding rulesin Java

Method overriding rulesin Java:-

1) The signature including the number and type of arguments for the overriding method should be same.

2) The return type should be same.

3) The access modifier should not be more limiting than superclass method.

4) The overriding method should not throw exceptions other than those thrown by the method in the super class.

Thread pool in java

Thread pool in java:- 

   In large scale application, multithreading is commonly used to execute independent 

tasks. Now imagine 100 classes extending the Thread class (or implementing the 

runnable interface) and each one having its own run method and you are asked to write

those run methods. Obviously, you need to repeat the same code and managing that
 code even becomes more difficult.

A very simple solution to this is to build a thread pool where in you will have a queue 

of objects on which the run method will be called. Any pre-pocessing will be done in 

the objects own member methods. Its only that the tasks will be added to the queue 

and an infinite loop will look for yet to run threads and will run them. You need two

 queues, one containing the threads that are currently running and other containing those yet to be run.

These queues can be LinkedLists.

1) Maximum and minimum number of threads pending for execution can be controlled.

2) Maximum alive time for each thread can be controlled

3) Many other business requirements in terms of multithreading can be achieved at a central point.

4) Your application’s multithreading is segregated which makes it look decent and well managed and gives a good impression to the reviewer.

5) Your life becomes much easier.

How to achieve it:
1) Create a class to maintain the threadpool information like the read and running queues, the variables for max and min number of threads, time to keep a thread alive

2) A class which contains the loop to check for threads in the running and ready queues and make a decision whether to invoke a particular thread or not.

The main

Valid main declarations are:
public static void main (String args[]) {}
public static void main (String[] args) {}
public static void main (String []args) {}
static public void main(String[] args) {}

Note:The return type of main should always be void

Default values of instance variable

Object Reference---null
byte---0
short---0
int---0
long---0L or 0l
float---0.0F or 0.0f
double---0.0D or 0.0d
boolean---false

All Java JDBC tips

1) There are three levels of JDBC API

2) The getConnection method is synchronized

3) Multiple SQL exceptions are chained

4) Type 1 are the JDBC-ODBC drivers

5) Type 2 are the Native API driver

6) Type 3 driver JDBC calls are first translated to DBMS independent net protocol and then translated to DBMS specific protocol

7) Type 4 drivers are pure java classes that directly interact with the DBMS and are quite fast.

8) DataSource interface was introduced in JAVA 2.0 and supports connection pooling, distributed tansactions

9) Datasource uses JNDI to find the datasource on the server and bind itself to it.

10) The context interface provides the facility to look up, bind and unbind the datasource

11) The JDBC url has three parts: jdbc::

12) The Statement object can be used to pass the SQL commands to the database (con.createStatement())

13) The prepared statement can be passed parameters and hence can be used with different values and is usually faster than statement. (con.prepareStatement)

14) The callable statement can be used to call stored procedures. (con.prepareCall)

15) The different versions for execute method are:
a. executeUpdate(String sql) – Statements which return a count
b. executeQuery(String sql) – Statements which return a single resultset
c. execute(String sql) – Statements which return multiple resultsets (Advanced Funda)

16) While using the statement object, the query is passed when it is executed

17) When using prepared statement, the query is passed when creating the statement object from connection object. This helps in pre-compilation

18) The callable statement also passes the call statement while creating the statement object from the connection object.

19) Callable statement extends prepared statement

20) Callable statement can also take output parameters too. But that parameter must be registered using registerOutParameter() method before calling the execute method. E.g callstmt.registerOutParameter(3, java.sql.Types.VARCHAR); if the third parameter is supposed to be the OUT parameter.

21) The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement completes when the last row of the ResultSet has been retrieved or the ResultSet has been closed. In advanced cases, a single statement may return multiple results as well as output parameter values. Here, the commit occurs when all results and output parameter -values have been retrieved.

Diffrence between hashtable and hashmap?

1) Hashtable and Hashmap are different in the sense that Hashmap is synchronized and permits nulls as keys as well as values. Hashtable requires non-null values for keys as well as values.
a. In case iteration performance is important, keep the capacity/size of hashmap small because the time for iteration is proportional to the capacity + size. However, get() and put() have constant time performance.

b. The load factor and initial capacity effect the performance of the hashmap. When the number of entries in the hashmap exceed the product of load factor and current capcity, the hashmap is rehashed so as to have twice the number of buckets. A value of 0.75 for load factor is good tradeoff between time and space cost.

c. The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

d. The parameterized constructors are allow for specifying the initial capacity and/or load factor.

e. The hashmap is not synchronized for structural changes (addition and deletion of keys) and not for operations like updating the value for a key. Collections.synchronizedMap should be used for synchronized access.

f. The iterator returned is fail-fast i.e. as soon as the map is structurally modified using other than iterator’s remove method, the iterator throws ConcurrentModificationException. However, the fail-fast behaviour is not guaranteed.

g. The put method returns null if either there was no such key in the map or the value associated with the key was null or it returns the previous value associated with key, if it exists in the map.

h. Similar is the case with get(), it returns null if either there is no key with name specified or the key explicitly maps to null. The containsKey can be used to distinguish these two cases.

10 tricky java interview questions

Here are some Java interview questions which are  un-common

1) What is the performance effect of a large number of import statements which are not used?
Ans: They are ignored if the corresponding class is not used.


2) Give a scenario where hotspot will optimize your code?
Ans: If we have defined a variable as static and then initialized this variable in a static block then the Hotspot will merge the variable and the initialization in a single statement and hence reduce the code.

3) What will happen if an exception is thrown from the finally block?
Ans: The program will exit if the exception is not catched in the finally block.


4) How does decorator design pattern works in I/O classes?
Ans: The various classes like BufferedReader , BufferedWriter workk on the underlying stream classes. Thus Buffered* class will provide a Buffer for Reader/Writer classes.


5) If I give you an assignment to design Shopping cart web application, how will you define the architecture of this application. You are free to choose any framework, tool or server?
Ans: Usually I will choose a MVC framework which will make me use other design patterns like Front Controller, Business Delegate, Service Locater, DAO, DTO, Loose Coupling etc. Struts 2 is very easy to configure and comes with other plugins like Tiles, Velocity and Validator etc. The architecture of Struts becomes the architecture of my application with various actions and corresponding JSP pages in place.

6) What is a deadlock in Java? How will you detect and get rid of deadlocks?
Ans: Deadlock exists when two threads try to get hold of a object which is already held by another object.


7) Why is it better to use hibernate than JDBC for database interaction in various Java applications?
Ans: Hibernate provides an OO view of the database by mapping the various classes to the database tables. This helps in thinking in terms of the OO language then in RDBMS terms and hence increases productivity.

8) How can one call one constructor from another constructor in a class?
Ans: Use the this() method to refer to constructors.

9) What is the purpose of intern() method in the String class?
Ans: It helps in moving the normal string objects to move to the String literal pool


10) How will you make your web application to use the https protocol?
Ans: This has more to do with the particular server being used  than the application itself. Here is how it can be done on tomcat:

50 java Questions

      The following are the most commonly asked questions in a Java interview. These are all actual exam question which I have been asked in various interviews (around 20 interviews) and are in fact have been asked repeatedly in those interviews be it telephonic or f2f interviews. Even now I also ask questions from these topics and you can expect to be asked 5-10 questions out of these.

I am not providing answers for these as it will be reinventing of wheel. You can Google these questions as it is and find answers to them. Don't forget to write sample programs around each of these question. I am sure you will come to know more if you practice yourself.

1) What are the four principles of Object Oriented Languages like Java?
2) Is Java a pure object oriented language?
3) How will you write an immutable class?
4) What is the difference between Comparable and Comparator interfaces in Java?
5) What is hashcode and equals contract?
6) What is the difference between == and equals method?
7) What are wrapper classes? Why they are declared as final classes?
8) What is the difference between String and StringBuffer classes?
9) What is the way to store the integer value in a string object to an integer variable?
10) What are sorted collections in Java?
11) Why is String class declared as final class?
12) What is JDBC API?

13) What are checked and unchecked exceptions?
14) What is final, finally and finalize?
15) What is weakhashmap?
16) What is the purpose of reflection API?
17) What is serialVersionUID?
18) What is bucketing in Java?
19) How does Java manages the threads?
20) What are memory leaks and how to detect/avoid them?
21) What is the order of execution of blocks in a Java program?
22) What are the exception related rules in overloading and overriding?
23) What are the different ways of creating a thread?
24) What is inter thread communication?
25) What are instance and class level locks? What is synchronization?
26) What is the difference between IS-A and HAS-A relationship?
27) What is cloning and CloneNotSupported Exception?
28) What is the difference between JAR, WAR and EAR files?
29) What are the coding standards for naming variables, constants, methods and classes?
30) What is a literal and what is special about String literals?
31) What is flyweight design pattern?
32) How will you create a Singleton class? Is it thread safe?
33) What is the difference between throw and throws clause?
34) Can one access the private members of class using reflection API?
35) What is the purpose of instanceof operator?
36) Under what circumstances, the finally block in a program may not run?
37) What is the difference between private, protected, default and public access specifiers?
38) What are this and super keywords?
39) What are transient and volatile keywords?
40) How many package statements can a program have?
41) Are all the classes specified in import statement actually imported?
42) Can an inheritance relationship exist between two interfaces?
43) What is Unicode?
44) What are annotations in Java?
45) What are the various forms of polymorphism?
46) What is the meaning of various keywords specified in creating the main method?
47) What is the purpose of ^ operator?
48) What is the difference between pass by value and pass by reference?
49) What are the various types of inner classes?
50) What are the various memory areas in JVM and what kind of information is stored in each of them?