New features in SCJP exam

Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.

New features in SCJP exam

Rating:

SCJP 1.5 and SCJP 1.6 are very different from the older versions of the exam.

SCJP 1.6 has added some new features, which are as follows:

  • NavigableSet interface

  • NavigableMap interface

  • Console class
The major changes that took place in the 1.5 version are as follows:
  • Autoboxing and Unboxing

  • Covariant returns

  • Enhanced for loop (for-each)

  • Enumeration (enum)

  • Generics

  • Static Imports

  • Variable-argument lists (VarArgs)

  • StringBuilder class
Other additions to the exam, which are not new to Java, are as follows:
  • Serialization

  • I/O Stream classes

  • NumberFormat, DateFormat, Locale

  • Pattern and Matcher classes, String.split() method

  • PrintWriter.format()/printf() methods

  • Comparable and Comparator interfaces

  • Arrays and Collections classes from the java.util package

  • Setting the classpath correctly

  • OO concepts of coupling and cohesion
NavigableSet interface

The NavigableSet interface extends the SortedSet interface in which the elements are ordered either by natural ordering or using a Comparator. It contains methods to find out the closest matches for given search targets. The elements of the NavigableSet interface must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

NavigableMap interface

The NavigableMap interface extends the SortedMap interface in which the elements are ordered either by natural ordering or by using a Comparator. It contains methods to find out the closest matches for given search targets. All keys inserted into a sorted map must implement the Comparable interface and must be mutually comparable. The elements of the NavigableSet interface can be accessed and traversed in either ascending or descending order.

Console Class

The Console class extends the Object class and has convenience methods to read from and write to the console objects. Also, the Console class has the readPassword() method to read a password from the console. If the underlying virtual machine has a console, it can be obtained by invoking the System.console() method. If no console device is available, then an invocation of the System.console() method returns null.


Autoboxing and Unboxing

It is not possible to put any primitive value, such as int or char, into a collection. Collections can hold only object references. To add any primitive to a collection, you need to explicitly box (or cast) it into an appropriate wrapper class. Again, while taking out an object out of the collection, it needs to be unboxed. To avoid these steps, Java 5.0 has added the autoboxing and unboxing features.

The example code shown below would have not compiled prior to version 1.5. But now that these new features have been added, it can be compiled without any difficulty.

class Autoboxunbox{
    public static void main(String[] args)
    {
        Character c = null;
        if (c == 'h')
        {
            System.out.println("I like boxing");
        }
        else
        {
           System.out.println("I like boxing very much");
}}}

The above example simply explains the concept of autoboxing and unboxing. However, due to null assignment to c, during runtime, a NumberFormatException will be thrown in the code.

Covariant returns

Another new feature of Java 1.5 is that it supports coVariant return types. The use of coVariant return types will allow a method overriding a super class method to return a subclass of the super class method's return type.

Consider the following lines of code:

class CoVarian{}
class SubcoVarian extends CoVarian{}
class SuperVarian{
    CoVarian method1(){
        return new CoVarian();
}}

class SubClass extends SuperVarian{
    SubcoVarian method1()
   {
        return new SubcoVarian();
}}


Had you tried to compile the above code using Java 1.4 or prior version, it would have definitely given an exception saying method method1 has already been defined in class SuperVarian. CoVariant return types are just another feature that adds clarity and type safety to Java. Because of coVariant return types, it becomes clear which method is being called. So, there is no cast required.

Generics

When anything is taken out of a collection, it needs casting. This is an annoying feature, when it is known what type of object was there in the collection. Generics help resolve this issue. Now, collections, such as ArrayList, can be bound to contain specific types of objects. Java's implementation of generics provides more compile-time type safety, which will enable the development of stronger and more self-describing APIs.

Consider the following example:

static void Gener(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
    {
        String str = (String) i.next();
        if(str.length() == 10)
        i.remove();
    }
}


In the above example, although you know that the collection will hold String, even then, you have to cast the retrieved element to string. Let us take a look at the same example using generics:

static void Gener(Collection<String> c)
{
    for (Iterator<String>> i = c.iterator(); i.hasNext(); )
    if (i.next().length() == 10)
    i.remove();
}


Generics make code more readable and avoid exceptions at runtime (classCastException), which may occur due to wrong casting, since the code is checked at compile time.

Enhanced for loop (for-each)

The enhanced for loop (also known as for-each loop) is a newly added feature in Java 5.0. The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. Let us take a very simple example with simple for loop, and then with the enhanced for loop.

Using simple for loop:

class OldForLoop{
    public static void main(String args[])
   {
       int[] arr={1,2,3,4,5,6,7,8,9,0};
        for(int i=0 ; i<arr.length;i++)
        {
            System.out.println(i);
        }
    }
}


Using the enhanced for loop:

class ForEachLoop{
    public static void main(String args[])
   {
        int[] arr={1,2,3,4,5,6,7,8,9,0};
        for(int i : arr)
        {
            System.out.println(i);
}}}


Variable-argument lists

Although Variable-argument lists (varargs) is a new feature in Java, it was used in C and C++. Previously, to invoke a method that takes arbitrary number of values, you needed to create an array and put the values into the array. Using varargs, you still pass the arguments in an array, but this is all done automatically. For example, consider the following syntax:

public varArgsEg method(String name, Class[] parameterTypes)

Now the same method can be written using varargs as follows:

public varArgsEg method(String name, Class... parameterTypes)

Varargs can be used only in the final argument position. The dots after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. A method can have only one varargs, and it must be the last parameter in the method signature.

Static import

Static import is a new feature introduced in J2SE 5.0. It allows static members to be treated as if they were declared in the class that uses them. Now, it is no longer needed to use the static class name and dot operator as was required before. Static imports are of two types, which are as follows:
  • One in which all the members of a particular static class are imported.
Syntax

import static packageName.ClassName.*;

  • And the other in which only a particular member of a class is imported.
Syntax

import static packageName.ClassName.membername;

For example:

import static java.lang.Math.*;
public class StaticImportTest
{
   public static void main( String args[] )
    {
        System.out.println( "Square root of 400 ="+sqrt(400.0 ) );
} }


StringBuilder

StringBuilder is a class, which is very similar to the StringBuffer class. It is a new concept introduced in J2SE 5. Like the String and the StringBuffer classes, it extends directly from the Object class. The StringBuilder class can act as an alternative to StringBuffer in places where the environment is not multithreaded, i.e., where synchronization or multithreading is not significant. The signature of the StringBuilder class is as follows:


public final class StringBuilder extends Object implements Serializable, CharSequence



Since StringBuilder is not synchronized, it offers faster performance than StringBuffer.

An example of using StringBuilder is given below:

import java.util.*;
public class StrBld {
    public static String likeJava(List<String> list)
    {
        StringBuilder b = new StringBuilder();
        for (Iterator<String> i = list.iterator(); i.hasNext(); )
        {
            b.append(i.next()).append(" ");
        }
        return b.toString();
    }

    public static void main(String[] args) {
        List list = new ArrayList();
       list.add("I");
       list.add("like");
       list.add("java");
       System.out.println(StrBld.likeJava(list));
}}


This will compile and execute to give the output "I like java".

Some of the important methods of the StringBuilder class are as follows:

public StringBuilder append(char c)

It appends the string representation of the char argument to the current sequence.
The argument is appended to the contents of this sequence. It increases the length of the sequence by 1.

public int capacity()

This will return the current capacity of the StringBuider.

public StringBuilder insert(int offset,boolean b)

This will insert the string representation of the boolean argument into current sequence.

public StringBuilder reverse()

This will cause the character sequence to be replaced by the reverse of the sequence.

public String toString()

This will return a string representing the data in current sequence

public StringBuilder replace(int start, int end, String str)

This will replace the characters in a sub-string of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.


Rating:



Other articles

Click here to Article home

MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD, SCJA, SCBCD, SCMAD Cisco Certification: CCNA, CCENT, A+, Network+, Security+
Oracle Certification: OCP 9i, OCP 10g, OCA 9i, OCA 10g CIW foundation    EC-212-32    CISSP    Photoshop ACE    Adobe Flash ACE
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.
 
HACKER SAFE certified sites prevent over 99.9% of hacker crime.