Showing posts with label SCJP. Show all posts
Showing posts with label SCJP. Show all posts

Saturday, June 6, 2009

uCertify PrepKit for SCJP 5.0

Recently, I got an exciting opportunity to review the uCertify Prepkit for SCJP 5.0 certification.

SCJP stands for Sun Certified Java Professional and is one of the many certifications offered by Sun Microsystems that makes you stand out in the crowd. In the times like these, who would not want that. :-)
If you want to know more about SCJP, you can look at the Sun's site here or you check this to see some related FAQ's.

Coming back to uCertify Preparation Kit, I actually found it pretty useful overall, for it gives you a broad spectrum of features for a relatively smaller price. The preparation engine provides you with
  • Study Notes & Helpful Articles
  • 7 Mock Tests, each with 75 questions
  • Study & Learn Module
  • Ability to Bookmark and Tag Questions
The Study & Learn Module provides a presentation (thus not really boring) based on each Examination Objective of SCJP 5.0. Going through them before the exam could be the fastest way to revise the entire syllabus. This is so because SCJP has well-defined objectives (rules & syntax of the language) that it tests. There is no need to go beyond these objectives if you want to clear the exam.

You can also attach your own notes with Study Notes and Articles, thus making a note of some exceptional condition or some related fact. These makes life really easy when you go through them again.

The practice exams give you a real feel of the actual certification exam as it contains both multiple choice questions (MCQ's) and few drag-and-drop questions. Also the level of the questions are neither too high nor too low. On a personal level, when I took the first practice exam without really preparing for it, I faltered on questions related to in-built classes like Locale, Date, NumberFormat and use of native modifier and Enumerations.

According to me, the best feature is certainly the way the answers are explained once your test is over and you see the results. You can review all the answers whether correct or not, and find out the reason for the same.
The answers are explained in length, touching the concept involved and focussing on why other options are wrong. This gives you a proper insight of what's going on.

On the downside, I would have preferred a highlighting feature that enables me to highlight important facts in the study notes and articles, so that next time I read only that part, which is important to me. Also, I would have loved had they allowed me to copy the code and paste it to test it but I understand that they probably can't do it for piracy issues and misuse.

Conclusion
Although it is an excellent kit to give you a proper feel of the actual exam; it is equipped with some easy ones and some tough(read tricky) questions as well just as the actual paper would. But, do not think that you need just this PrepKit to clear the paper!!
What you also need is a javac(Java compiler) to practice and code. I strongly recommend understanding the involved concepts and coding by hand (not by IDE), then take these useful tests to gain confidence as the actual exam looks almost the same.

For more information about the other preparation kits that uCertify provides you, please visit there site here.

Sunday, May 31, 2009

Strings & Java

Perhaps one of the most frequently used Class in Java is the String class. The major reason for Strings to be really poweful is the flexibility of Strings to interact with other objects with so much ease.

Strings in Java posses many unique characteristics that differentiates it from the rest. For example, it is a well-known fact that Strings are Immutable. For those who do not know what that means is, 'String objects one created, can never be changed.' An example would make it more clear.

String s1 = "Hello World";
Here, s1 holds the reference to the String object on the heap containing the value "Hello World". Now, if we type

String s2 = s1.concat(", here I come");
Now, s2 holds another object on the heap with the value "Hello World, here I come". But this doesn't change the object s1. What it rather does, it creates a new object concatenating the new value to it and storing its reference in s2.

If we would have typed,

s1.concat(", here I come");
then also a new object with value "Hello World, here I come" is created but is lost and cannot be referenced since we have not stored it somewhere. Here also, s1 remains the same and is not changed. It cannot be changed.

It would also be good to remember that to make Java Memory Model more efficient,  Java Runtime allocates memory for Strings from "String constant pool" rather than allocating the memory from the heap. 
Now, when the compiler encounters any string literal, it first searches the String constant pool for an identical string. 
  • If a match is found, the reference to the already existing identical string is returned for the new request. 
  • If a match is not found, then a new string literal is created in the pool of strings. This approach works without failure since Strings are immutable in nature.
An example can again smooth things out here:

String s1 = "Agraj";
String s2 = "Agraj";
System.out.println(s1 == s2);              // prints true !!
System.out.println(s1.equals(s2));     // prints true as expected

String s1 = "Agraj";
String s2 = new String("Agraj");
System.out.println(s1 == s2);              // prints false because of 'new'
System.out.println(s1.equals(s2));     // prints true as expected

The first example prints according to String constant pool approach. While, the second example allocates memory again to s2 because the new operator is used, which forces the compiler to allocate memory again.
It would not hurt to remember that the '==' operator is used to compare references while the 'equals' function actually compares the string value(character by character) stored inside the objects.

On some pondering, one might think that if identical strings are not allocated same memory, then if one might change one reference to the string, then all other references would also reflect the change. For example,

String s1 = "Agraj";
String s2 = "Agraj";
s1 = s1.toUpperCase();       // s1 = "AGRAJ" but s2="Agraj"

One might expect s2 also to be equal to "AGRAJ", which is not desired. But, since Strings are immutable in nature, so the toUpperCase() function creates a new string, rather than modifying the original string (it cannot modify the original string, nothing can) and assigns it to s1 while s2 still reference to the original string "Agraj".

StringBuffer and StringBuilder 

A person can argue that in a module that does heavy String manipulation, there would be excess of new Strings that would be created now and then and would not be used at the end, leading to wastage of memory. And you see, this person is not entirely wrong. Strings if used in a careless manner can cause huge performance bottleneck. 
So mostly, when we have to do String manipulation a lot in our application, it is advisable to use classes such as StringBuffer & StringBuilder. Both of these provide the same API and behave in the same manner as Strings do, the difference being the fact that they are mutable. Thus, you can change a StringBuffer / StringBuilder object once created. 
Example:

StringBuilder str1 = new StringBuilder("Hello");
str1.append(" World");

would change the existing object "Hello" and will not create a new object as normal String Object would have done. 

Difference b/w StringBuilder & StringBuffer
Both of them provide us with the same API and thus are similar except the fact that StringBuffer is thread-safe while StringBuilder is not. 
Thus it is always advisable to use StringBuilder class, where-ever thread-safety is not a issue (which is commonly the case always). It is advisable to use StringBuilder than StringBuffer because StringBuilder is much more faster than its thread-safe twin. This is so because it ignores the complications that comes along while deailing with stuff like synchronization and threads. 

There is much more to Strings usage in Java than what can be covered in a blog entry, but I guess I have covered some of the important points which are normally ignored by novices like me. 

Thursday, January 22, 2009

Checked Vs Unchecked Exceptions

In Java, there are 2 kinds of Exception:

Unchecked Exceptions which indicate some sort of programming error on the part of developer. Unchecked Exceptions are usually subclasses of RuntimeException class. Examples include: 
 --- NullPointerException (which is usually thrown when method is              invoked on a null object)
 --- DivideByZeroException (thrown when divide by zero happens in        your code)
 --- IllegalArgumentException (usually thrown when invalid argument        is passed to a method)
 --- ArrayIndexOutOfBoundsException (thrown when you try to access         array index beyond the memory allocated to it)
 --- ArithmeticException
 --- RuntimeException
If your methods throw an unchecked exception, then your method need not specify it as a part of its API i.e no need to write all the exceptions it throws using "throws" clause.

Checked Exceptions on the other hand, specifies conditions that are not due to human errors but due to conditions that are not in programmer's control. These include conditions such as database errors, network failures, file not found when searching or performing some operation on it. Examples include:
 --- FileNotFoundException
 --- SQLException
 --- PersistenceException
On the other hand, if your code throws any checked conditions, then either you must handle it or specify it using "throws" clause else your program will give compile-time error. 

Checked Vs Unchecked
Use Checked Exception in your code when you Client code (code that calls your code) is capable of dealing with the Exception and have ample knowledge why that Exception occurred in the first place and how to do away with it. 
Otherwise, it is always preferable to use Unchecked Exceptions since then the Client code is not forced to handle it and can choose to ignore it. Though that would not solve the problem and the exception would travel high up in hierarchy of function calls and perhaps finally encountered by the JVM, but at least the Client code is saved from the hassle of dealing with Exceptions that they don't know about it.
Let's take an example. Suppose we have a method throwing an SQLException:
The client code would never come to know that why this SQLException occurred, as it has no knowledge of underlying business logic and internal database design. Thus client is unable to handle the exception, so its always better to not force a client to handle an exception he do not know about.

Articles Worth Reading:

Thursday, November 13, 2008

Golden rules for Overriding

This blog entry sums up "all-you-ever-need-to-know" about Overridding Methods in Java. So just follow these simple rules and you will be home. :-)

Golden Rules:
  • The overridden method must have same number and type of arguments(i.e. the same signature) as in the original method of the superclass. Very simple to understand, so go ahead. :-)
  • Methods marked as final or static cannot be overridden. Although, a superclass and subclass can have static methods with same signatures, but that doesn't mean that you have overridden the method of superclass, rather these are inherently separate methods.
  • The overriding method CAN have less restrictive access modifier than the overridden method.
For Example, the following code would compile successfully
>   class base
>   {
>        protected void test()
      {
>          System.out.println(" Base");
>       }
>   }
>  class derived extends base
>  {
>          public void test()
>      {
         System.out.println(" Derived ");
>      }
>  }
  • The overriding method CANNOT have more restrictive access modifier than that of the original method of the superclass.
SuperClass Signature - protected void test(){ ... }
SubClass Signature     - private void test(){ ... }
This won't work. 
  • The overriding method CAN throw any unchecked exception regardless of the overridden method.
> class base
> {
> void hello()
> {
> System.out.println("base");
> }
>  }
> class derived extends base
> {
> void hello() throws RuntimeException
> {
> System.out.println("derived");
> throw new RuntimeException("My Exception from Derived");
> }
> }

  • The overriding method CANNOT throw any broader or new checked exceptions as compared to those thrown by overridden method. However, the overriding method CAN throw any narrower or fewer exceptions.
For Example, this is allowed:
SuperClass Signature - void disp() throws Exception { ... }
SubClass Signature     - void disp() throws RuntimeException { ... }

while this isn't:
SuperClass Signature - void disp() throws ArithmeticException { ... }
SubClass Signature     - void disp() throws RuntimeException { ... }
  • You can override only those methods that you can inherit. So, beware of code which seem to override private methods. 
  • The overridding method return type must be same as that of overridding method or it can be subclass of the original return type. 
> public class overriding
> {
> public static void main(String[] args)
> {
> derived d = new derived();
> derived e = d.print();
> e.print();
> }
> }
> class base
> {
> public base print()
> {
> System.out.println(" Inside Base ");
> return new base();
> }
> }
> class derived extends base
> {
>          @Override
> public derived print()
> {
> System.out.println(" Inside derived ");
> return new derived();
> }
> }

Here, the print() method is overridden though it doesn't look like that. This is known as Covariant-return type and it will work with code written for Java5 platform and above.

For any comments, suggestions or corrections, please leave your comments. :-)

Saturday, November 8, 2008

Many Public Classes in 1 Java File !!

There is a popular misconception among the beginners that we can have multiple public classes in one java source file.
But the rule is that "we can have atmost one public class and any number of non-public classes in one .java source file". The public class must contain the main method, from where the execution begins. As i see it, this is so that JVM could access and call the main method from outside the class. 

However, there is one exception to this rule. I wrote this blog entry because i came to know about the exception :)
The exception comes when we deal with inner classes. You can have as-many-as-you-want public inner classes in your class. But, it is not desirable as it results in difficult-to-manage code and of decreases its re-usability. 

For example, the following code would compile and run successfully.
>
>  class tryme
>  {
>     public static class A
>   {
>   public void print()
>   {   System.out.println(" Print inside A ");   }
>   }
>
>   public static class B
>   {
>   public void display()
>   {   System.out.println(" Display inside B ");   }
>   }
>
>  }
>
>  public class test
>  {
>   public static void main(String[] args)
>   {
>   tryme.A ob = new tryme.A();
>   ob.print();
>
>   tryme.B ob2 = new tryme.B();
>   ob2.display();
>     }
>  }
>

Of course, the file must be named test.java. It compiles and produces the following output.
>
> Print inside A
> Display inside B
>

Another way of using public inner classes is by importing them in your program like
import packagename.tryme.*;
and then use classes A and B as they you like.

But, the recommended style of programming discourages use of more than one public class in one java file. Also, such behaviour is not supported on all compilers. Infact, for maximum optimization (by compiler) it is recommended that you should write one class per java file.

Comments and corrections are welcome. :)

Monday, November 3, 2008

Static Imports in Java

Java as a language, continues to evolve and amaze developers and students alike with new innovative concepts and features. Java 5 is a major release which includes various additions like Generics, Autoboxing, Enumerations, Enhanced for-loop, Static Imports, Var-args, Serialization, Covariant return types, Annotations etc. to name a few.

Discussing each one of them would span multiple blog entries. So let's start with Static Imports as of now. Hopefully, I will devote an entry to each one of these in the coming days. :-)

Before I begin with my explanation of Static Imports, I would like to ask you something..........
Are you sick and tired of using fully-qualified static members of some other class (can be a library class too) in your program such as Math.PI whenever you want to use 3.141592653589793.... or Math.sqrt() when you need to find out square root of any number ??

Of course, these are simple examples which are short and easy to remember, so they might not seem a headache. But things can get quite complex and it can turn out to be burdensome to repeat a long fully-qualified name time and again in your code. 
Static Imports come to your rescue. :-)

With the help of Static imports, you can very well use the static members of any other class (to which you have access) like the members of your class i.e. there is no need to fully qualify the name using package name and class name 

Normally an import statement would look like 
import packageName.className.memberName;

A static import would just add the word "static" after import 
import static packageName.className.memberName;

An example would make it more clear....

>  import static java.lang.Math.*;
>  public class tryme
>  {
>    public static void main(String[] args)
>    {
>      System.out.println("Square root of PI is "+sqrt(PI));
>    }
>  }

The advantage lies in the fact that you dont have to type Math.PI....a simple PI would work....
I agree that its a small feature and not as important as other features that Java 5 has introduced or enhanced, but then as they say "Boond boond se hi gaadha badhta hain"

Limitations :
It applies to only static members, not to instance variables 
It can make code un-readable and difficult to debug, if used unnecessarily and in excess

Application:
Mostly it is used to discourage the technique of declaring constants in interfaces and then implementing those interfaces by your class. An interface is a part of public API and it defines services that your class should provide, and so it is not recommended to make constants a part of your public API. Instead, it is always preferable to use Static Imports.

Thursday, October 30, 2008

equals() & hashcode() relation in Java

I assume that you have an idea about equals() and hashCode() methods present in Object class. What you may not know, is that a relation(or perhaps a contract) exists between them.

Remember the following points:
  • If you override equals(), then you must override hashCode()
  • equals() & hashCode() must be evaluated based on same fields
  • If two objects are equal using equals() then they must have same hashCode() value, but vice-versa need not be true.
Since hashCode() value of an object determines how it will be stored and located when it is used with collections like HashMap & HashSet, so it becomes necessary that equal objects must have same hashCode() value. 
So, implementing hashCode() when your program deals with collections become really important for reasons such as efficiency and correctness.

To give an analogy to this hashing process, imagine a sequence of buckets to be your hashtable. Now, to retrieve an element, we do
1. Locate the right bucket using hashCode() value
2. Search the bucket for the element using equals()

Now, if two equals objects (which would be present in one bucket) have different hashcodes, you would never be able to retrieve them back correctly, because you are not looking in the right bucket. 

Although, it is legal to have same hashCode() value for different (read unequal) objects, but it will hurt the efficiency as it would make it a bit slow to locate the correct bucket.

Also, if two objects have different hashCode() values, then they must not be equal using equals() i.e.
if x.hashCode() != y.hashCode() then x.equals(y) == false.

This also helps in clearing a popular misconception about hashcodes that they identify an element uniquely. They can be used as an object ID but they are not necessary unique.

Still interested in more details, read this article to get more insight. :-)

Sunday, August 17, 2008

Java Interview Questions

Based on my exposure and experience with the language, I have listed some important Java(Core) questions that I think can be asked in any interview related to Java. I'm not listing the answers with them over here, but that does not mean that I do not know them :))
The only reason for not writing answers here, is that it would unnecessarily increase the length of the entry, but if you have doubts in any question, you can ask me in the comments section or can mail me.

Questions

Ques. 1 What makes Java Portable?
(The answer can spark discussion of things like Bytecode, VM so be clear with your concepts)

Ques. 2 List some features of Java that are not present in C++
(List 5-6 main features that makes the language more powerful)

Ques. 3 Is Java Slow as compared to C/C++?
(Google over it if you do not know or ask me)

Ques. 4 Differentiate between JDK. JRE and JVM.
(Ok, read this link and you are through) :-)

Ques. 5 How are interfaces different from Abstract Classes.
(Pretty simple one)

Ques. 6 List major OOPS principles and tell how each can be implemented using Java.
(simple & still Frequently asked)

Ques. 7 Parameter passing in Java.
(may be this can help.......it can be indirectly asked by giving a piece of code)

Ques. 8 How many classes can you have in 1 .java file?? How many of them can be public ? Why so ?
(if you do not know this, its high time you clear your basic concepts)

Ques. 9 Is Java a compiled language or interpreted language ??
(Ans: It is both compiled & interpreted. You need to explain in detail the conversion(compilation) of .java file into .class file(s) using javac and then execution(interpretation) of the .class file by the JVM)

Ques. 10 Talk about Garbage Collection in Java.
(very frequently asked)

Ques. 11 Can we force Garbage collector to run in Java ??
(ans is no, we can only give it a hint, not a command.... Google to know more)

Ques. 12 Is Java purely object-oriented ??
(perhaps this would help)

Ques. 13 Can we call C++ code in Java ??
(can be done using Java Native Interface (JNI), if you need to know more, Google is your best friend)

Ques. 14 Tell 3 uses of final keyword.
(typically textbook based question)

Ques. 15 Why an abstract class cannot be final ?
(don't tell me you don't know this :p)

Ques. 16 Which version of Java have you worked on ? What are the different versions of Java ? How they differ from each other ??
(Tough one if you don't know it. At least remember 2 or 3 main points of differences between Java 4, 5 & 6 such as with Java 5 new features such as Auto-boxing, variable arguments, co-variant returns (in overriding) but you also need to know what they mean. Explaining them here would require another blog post)

Ques. 17 Tell how many different types of variables are possible in Java.
(Tricky! Talk about Local Variables, Instance Variables & Class Variables)

Ques. 18 What are immutable objects? Give an example of immutable object in Java.
(Hint: Eg is String objects are immutable...rest you have to find it your way)

Ques. 19 What is Serialization ? How it can be implemented in Java.
(If you can answer this in an interview, they would seriously consider you as not many ppl can answer this so read about it & talk about the concept first and then talk abt Serializable interface)

Ques. 20 Discussion restrictions placed on method overloading & method overriding and compare the two.
(another textbook based.......but consult a good textbook :p)

Will keep on posting new questions that I feel every Java developer (rather every aspiring student) must know, whether he wants to clear his interview or not !!

Waiting for Comments :-)