Monday 1 April 2013

Importance of toString() in java

Object class of Java is having predefined toString() method. This method by default Object class calls implicitly when an object created. Overriding toString manually is nothing but implementing this method in our class.The java toString() method is used when we need a string representation of an object. It is defined in Object class.

The toString() method is useful for debugging. By default, when an object is printed out in a print stream like System.out, the toString() method of the object is automatically called.
While develping the code the developers used to check the object properties are getting through the object or not. For this print statement will be useful to quick test in the console.


public String toString()
Returns: a string representation of the object.
Let us take a Person class and try to print the person object using the System.out.println() statement.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package blog.javabynataraj;
//@author Muralidhar N
class Person{
 public String fname;
 public String lname;
  
 Person(String fn,String ln){
  this.fname=fn;
  this.lname=ln;
 }
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
}
 
public class ToStringTest {
 public static void main(String[] args) {
  Person p = new Person("murali","dhar");
  System.out.println(p);
 }
}

The output will be the class name@hexadecimal

here the Object class's method toString returning
getClass().getName()+'@'+Integer.toHexString(hashCode())
But here we assumed that the firstname and the lastname will be print. But it is not done. This is the magic toStirng method.

But in the below program we can print the firstname and lastname of person Object. What we are going to do here is just overriding the toString method in Person Class.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package blog.javabynataraj;
//@author Muralidhar N
class Person{
 public String fname;
 public String lname;
  
 Person(String fn,String ln){
  this.fname=fn;
  this.lname=ln;
 }
 public String getFname() {
  return fname;
 }
 public void setFname(String fname) {
  this.fname = fname;
 }
 public String getLname() {
  return lname;
 }
 public void setLname(String lname) {
  this.lname = lname;
 }
 public String toString(){
  return (getClass()+"  FirstName: "+fname+"  LastName: "+lname);
 }
}
 
public class ToStringTest {
 public static void main(String[] args) {
  Person p = new Person("murali","dhar");
  System.out.println(p);
 }
}
See the output of this:
Now you can achieve this by overriding the default toString() method inside Person class to return the contents of the instance of Person.

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.