Sunday, February 10, 2013

java.io Class Hierarchy Diagram









Diagram sources:
Gailer-net.de

java.io cheat sheet for SCJP:
(from book SCJP Sun Certified Programmer for Java 6 Exam 310-065)

Example for using these constructors:
How to read lines from a text file, display them and close all resources?

try{
  BufferedReader reader= new BufferedReader (new FileReader(new File("file.txt")));
  String line=null;
  while( (line=reader.readLine())!=null){
    System.out.println(line);
  }
  reader.close();
}catch(Exception e){}


For other package diagrams, check falkhausen.de

Java Exceptions

The Throwable class is the superclass of all errors and exceptions in the Java language.
Then we have Error and Exception classes, that implement the Throwable interface, and there can be checked or unchecked exceptions:
  • Checked exceptions are the exceptions that need to be catch in a try catch block or need to be declared in the method signature where they are thrown.
  • Unchecked exceptions are RuntimeExceptions (or Errors) that do not need to be caught or declared in the method signature.


RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeExceptions that are currently part of the certification objectives are:
ArrayIndexOutOfBoundsException - when attempting to access an array with an invalid index value
ClassCastException - when attempting to cast a reference variable to a type that fails the IS-A test
IllegalArgumentException - when the method receives an argument formatted differently that the method expects
IllegalStateException - when the state of the environment doesn't match the operation being attempted
NullPointerException - when attempting to access an object with a null reference variable
NumberFormatException - when a method that converts a String to a number, receives a String that it cannot convert.

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Errors that are currently part of the certification objectives are:
AssertionError - if the assert boolean test evaluates to false
ExceptionInInitializerError - error while attempting to initialize a static variable ou an initialization block
StackOverflowError - when a method recurses too deeply, and exhausts the stack
NoClassDefFoundError - when the JVM can't find the class that it needs (command line error, classpath issue ou missing .class file)

Collections class diagram

You need to know each one of these for the certification.


Diagram is from book SCJP Sun Certified Programmer for Java 6 Exam 310-065.

Comparable vs. Comparator

At a first glance, these two interfaces seems to have no difference and it is easy to confuse both.

Comparable interface (java.lang)
This is used by the Collections.sort() and Arrays.sort(), so the elements in the collection needs to implement this interface, in order to be sorted.
This interface is frequently implemented in the API by String, Wrapper Classes, Date, Calendar...
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

CompareTo returns an int with value:
negative    if this object < another object
zero          if this object == another object
positive     if this object > another object


class A implements Comparable<A>{
  String name=new String();

  public String getName(){ return name;}

  @Override
  public int compareTo(A o) {
    return name.compareTo(o.getName());
  }
}

class Test {
  public static void main ( String args[ ] ) {
    List<A> s= new ArrayList<A>();
    s.add(new A());
    s.add(new A());
    Collections.sort(s);  //if the collection does not implement Comparable, it will fail to compile in this line
 }
}


Remember that:
When overriding equals(), the argument is of type Object
When overriding compareTo(), the argument should be of the type you're sorting (but Object is allowed if you don't use Generics).

Comparator interface (java.util)
There an overloaded version of the sort method that takes both a List and something called a Comparator.
Comparator gives you the ability to sort a given collection any number of different ways, so that we can sort instances of any class.

The class that implements Comparator is a separate class from the class whose instances you want to sort, this is used as an argument by the Collections.sort() and Arrays.sort()


class MySort implements Comparator<String>{
  @Override
  public int compare(String one, String two) {
    return one.compareTo(two);
  }
}

class Test {
  public static void main ( String args [ ] ) {
    List<String> s= new ArrayList<String>();
    s.add("one");
    s.add("two");
    Collections.sort(s,new MySort());
  }
}



Searching Arrays and Collections with Comparable/Comparator
Searches are performed with the binarySearch() method.
The collection to be searched has to be sorted first, otherwise the result may become unpredictable (compiles, but the result may not be right).

If the collection was sorted with a natural order (elements implement Comparable), then a Comparator cannot be used to do the search (compiles, but the result may not be right).
E.g
Arrays.sort(array) must be used with
Arrays.binarySearch(array,elementToSearch);


If the collection was sorted with a Comparator, then it must be searched with a Comparator  (compiles, but the result may not be right).
E.g
Arrays.sort(array,someComparatorInstance) must be used with Arrays.binarySearch(array,elementToSearch,someComparatorInstance);

Result:
Successful searches returns an int index of the element being searched.
Unsuccessful searches returns a negative int index of the insertion point, that would be used to keep the collection properly sorted. The result formula for unsuccessful searched is (- (insertion point) -1 ).

Thursday, February 7, 2013

Tools: Process Explorer

Process Explorer is an excellent Microsoft tool that allows to check process dependencies, which DLL processes have been opened or loaded, watch the CPU consumption or just track leaks. Process Explorer provides insights about applications... check it out!




Wednesday, February 6, 2013

SCJP 6 doubts: implicit imports

There are implicit imports that do not need to be declared.
The classes in java.lang package can be used without importing any package, this is an implicit import, so don't be fooled if you see a question that looks like that the import is missing.

What classes can we see in the java.lang package?
JavaSE 6 API just tells us which ones belong to this package: basically its the String, StringBuilder, StringBuffer, Thread, wrappers (Integer, Float,...), Object, System, Runtime, Exception, and a lot of other classes which you can use directly.

The real exam always has line numbers on the left side of the code, so if you see that it does not start with line 1, you don't have to worry about the imports, and assume that the imports (and packages) are right.
If the code starts at line 1, just assume you're looking at the entire file. If you see that the code uses classes that belong to other packages besides java.lang, (e.g class File needs import java.io.*) then you can say for sure that the right answer is "compilation fails" due to missing imports.

Default package
If you have a class within the default package (no package declaration is found), and you create another class that has a relashionship with the first one, then no import is needed (because both are in the default package);

1. public class A{
2. int i=0;
3. }

1. public class B extends A{
2. }

Theme color generator

Kuler is a cool website from Adobe, to generate color themes.
Or you can also try the Color Scheme Designer.