Thursday, May 16, 2013

Using Eclipse to generate hashCode() and equals()

Right-click at the selected file, choose Source-> generate hashCode() and equals()
Then you can choose which attributes uniquely identify the object and then Eclipse generates hashCode() and equals() implementation like this:

/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof OtherObject))
return false;
OtherObject other = (OtherObject) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
return true;
}

Sonar: Correctness - Impossible downcast of toArray() result

When we are facing with the Sonar message "Correctness - Impossible downcast of toArray() result" what does this mean?

This message appears when we have something like this:

String[] getAsArray(Collection c) {
  return (String[]) c.toArray();
}


This will usually fail by throwing a ClassCastException.
The correct way to get an array of a specific type from a collection is by the usage of

c.toArray(new String[c.size()]);


that will return a String[], for this scenario.

Thursday, February 21, 2013

Windows 7: Take a partial screenshot with Snipping Tool

Windows 7 Printscreen tips:

You can take a screenshot of your screen with the key "Print Scrn" and then paste it in the Paint application (to be able to save the image), or paste is somewhere else.
For taking a screenshot of the active window, you can use the "Alt + Print Scrn" key combination.
But, Windows 7 brings us the Snipping Tool*, to take a partial screenshot of the window (select the area to capture, just like in Mac OS X), and then save it without the need to use Paint for that.


The Snipping Tool can be found at the %windir%\system32\SnippingTool.exe
There is no command to open the snipping tool, so you can define a shortcut (Properties->Shortcut) for this. (Eg. "Ctrl + Shift + 4", like in Mac OS X)


Under the "new" menu you have the following options:
  • Free-form snip
  • Rectangular snip
  • Window snip
  • Full-screen snip

After you snip, you can annotate it with a pen (you can choose among various colors, thicknesses, or tips) or highlight items.

*Not included with Windows 7 Starter or Home Basic.

OCE EJBD6 (1Z0-895) Resources

Starting to collect material, to study for the OCE (Oracle Certified Expert) Java EE 6 EJB Developer Certified Professional Exam certification, code 1Z0-895 (former CX-311-093), that talks about Enterprise JavaBeans (EJB) 3.1 Technology available in the Java EE 6 platform.

Duration: 110m
Questions: 60
Passing Score: 73%

Books:
EJB 3.1 Cookbook (recommended book)
Richard M. Reese
Packt Publishing (June 8, 2011)

Enterprise JavaBeans 3.1 (the most recommended book)
Andrew Lee Rubinger, Bill Burke
O'Reilly Media; Sixth Edition edition (September 24, 2010)

EJB3 in Action (ignore JPA chapters)
Debu Panda, Reza Rahman, Derek Lane
Manning Publications Co.

Mock Tests:

Study Notes:

EJB 3.1 Spec

Oracle Exam Topics:

Other Resources:

I'm SCJP/OCP Java 6 certified!


I passed the SCJP/OCP Java 6 exam with 90%! :) I totally recommend my SCJP study preparation.
Now I'm going to relax a little and then go back to study for the next certification: OCP Java EE 6 EJB Developer Certified Professional Exam (OCE EJBD 6). Target: end of the year!

Wednesday, February 13, 2013

SCJP Question: "hidding" issue

Given:

31. class Foo {
32. public int a = 3;
33. public void addFive() { a += 5; System.out.print("f "); }
34. }
35. class Bar extends Foo {
36. public int a = 8;
37. public void addFive() { this.a += 5; System.out.print("b " ); }
38. } Invoked with: Foo f = new Bar(); f.addFive(); System.out.println(f.a);


What is the result?
A. b 3
B. b 8
C. b 13
D. f 3
E. f 8
F. f 13
G. Compilation fails.
H. An exception is thrown at runtime.

SCJP Question with Garbage collection

Q. Given:

3. interface Animal { void makeNoise(); }
4. class Horse implements Animal {
5. Long weight = 1200L;
6. public void makeNoise() { System.out.println(“whinny”); }
7. }

8. public class Icelandic extends Horse {
9. public void makeNoise() { System.out.println(“vinny”); }
10. public static void main(String[] args) {
11. Icelandic i1 = new Icelandic();
12. Icelandic i2 = new Icelandic();
13. Icelandic i3 = new Icelandic();
14. i3 = i1; i1 = i2; i2 = null; i3 = i1;
15. }
16. }


When line 15 is reached, how many objects are eligible for the garbage collector?

A. 0
B. 1
C. 2
D. 3
E. 4
F. 6

Tuesday, February 12, 2013

SCJP: switch statement

A trick usual to be found concerns the type of the switch expression.
Only int convertibles or enums can be used in the switch expression.
long values fails to compile.

Wrong:

long l=0;
switch(l){
//...
}

SCJP Question: postfix increment

What is the output of this code?

class A {
  int i=0;

  public int getValue(){
    return i++;
  }
}

class Test {
  public static void main ( String args [ ] ) {
    System.out.println(new A().getValue());
  }
}


SCJP: Collection and Map summary

Collections comes with 4 flavors:

Set - Unique things
List - List of things, non-unique, cares about the index
Queue - Things arranged by the order to be processed
Map - Things with a unique ID (key, value pairs)

Map
HashMap - Unsorted, unordered. Allows one null key and multiple null values.
Hashtable - that's right, with lower case in table word, because of Java prehistoric times. Synchronized version of a HashMap, but with the difference of not allowing anything that is null.
TreeMap - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator).
LinkedHashMap - Maintains insertion order.
If the element to be added already exists, then it is replaced. Returns the previous value or null if it did not exist.

Set
HashSet - Unsorted, unordered. Uses hashcode of the element being inserted to determine the insertion bucket and the uses equals to determinate unicity. If the hashcode of the object is not redefined, the it uses the default Object hashcode (always returns a different value for each object that seems to be meaningfully equal). Does not allow duplicates
LinkedHashSet - Ordered version of HashSet, using insertion order. Does not allow duplicates
TreeSet - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator). Does not allow duplicates
If the element to be added already exists, then the insertion does nothing and returns false.

List
ArrayList - ordered collection (by index) but not sorted. Duplicates allowed.
Vector - Synchronized version of an ArrayList. Duplicates allowed
LinkedList - ordered collection, by index, and provides you extra methods for inserting/removing from head/tail. Duplicates allowed

Queue
PriorityQueue - Sorted, by using natural order (Comparable) or with a specific order (using a Comparator). The elements ordering represents their priority.

Utility classes
Collections
Arrays

One way of thinking about collections is the following:

Sorted Collections (objects need to implement Comparable):
TreeMap - natural order (compare from Comparable) or custom comparison rules (compareTo from Comparator)
TreeSet - natural order (compare from Comparable) or custom comparison rules (compareTo from Comparator)
PriorityQueue - natural order (compare from Comparable)

Ordered Collections:
LinkedHashMap - by insertion order
LinkedHashSet - by insertion order
ArrayList -by index
Vector - by index
LinkedList - by index

Unordered Collections (by hashcode):
HashMap
Hashtable
HashSet
(2)

(2)


(1)

(1)

(1) From book A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)
(2) From book SCJP Sun Certified Programmer for Java 6 Exam 310-065

SCJP: widening and narrowing

Widening
Widening means promoting a smaller type into a bigger one. No cast is needed. Look at the picture taken from book A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition), Khalid Mughal, that shows the chain of widening types. char is at the side, because it is signed, while the others are unsigned.


This is also applicable to the type hierarchy:

Object obj = "123" ; // no cast is needed: widening String to Object (subtype to supertype), also called upcasting


Narrowing
Narrowing means converting a wider type into a smaller one, meaning that there is loss of magnitude and precision. So a cast is needed.

String str = (String) obj // a cast is needed: narrowing an Object to a String (supertype to subtype), also called downcasting


The compiler will reject casts that are not legal, with a ClassCastException (runtime exception), but pay attention that narrowing a primitive type will never result in a runtime exception.

NumberFormat parse and format methods

format
The format method converts a number to a String representation, according to a given Locale.
Eg.

NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double d = 123.57;
System.out.println(nf.format(d));

This will print 123,57

parse
The parse method uses a String to be converted to a Number, for a given Locale.

NumberFormat fr = NumberFormat.getInstance(Locale.FRANCE);

try {
  String s = “123,45”;
  System.out.println(fr.parse(s));
}catch(ParseException e) {
  e.printStackTrace();
}

This will print 123.45

The parse method only parses the beginning of a string. After it reaches a character that cannot be parsed, the parsing stops and the value is returned.

E.g

NumberFormat nf = NumberFormat.getInstance();
try{
  String one = “456abc”;
  System.out.println(nf.parse(one));
}catch(ParseException e) {
  e.printStackTrace();
}

This will print 456


setMaximumFractionDigits
Attention to the setMaximumFractionDigits, that is not a regular truncate function, but instead, it rounds the number up or down when truncating.
E.g
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(4);
nf.setMinimumFractionDigits(2);

String a = nf.format(3.1415926);
String b = nf.format(2);

System.out.println(a);
System.out.println(b);


This will print:
3,1416
2,00

SCJP: equals and ==

The difference between == and equals
== compares if two references points to the same object
equals uses its own logic to compare if two objects are equal

==
To save memory, two instances of the following wrapper objects will always be == when their primitive values are the same (in a range from -128 to 127 for Short, Integer and Byte; values from '\u0000' to '\u007f' for Character; Boolean).

Integer one = 127;
Integer two = 127;

if(one==two)
  System.out.println("Same");

This will print Same.


But this will print Different (because the object references are different):

Integer one = new Integer(127);
Integer two = new Integer(127);

if(one==two)
  System.out.println("Same");
else
  System.out.println("Different");


And this will also print Different (it is out of the pool range from -128 to 127):

Integer one = 128;
Integer two = 128;

if(one==two)
  System.out.println("Same");
else
  System.out.println("Different");


String == and equals
String one = “today”;
String two = “today”;
if(one == two)
  System.out.println(“true”);
else
  System.out.println(“false”);

This will print true, because all the string literals are stored by the JVM in the string pool, and since they are immutable, instances in the string pool can be shared, so they are referring to the same object.


String one = “today”;
String three = new String(“today”);
if(one == three)
  System.out.println(”true”);
else
  System.out.println(“false”);

This will print false, because the one points to string that lives in the string pool while three represents a dynamically created string (it does not live in the string pool)

Comparing Wrapper to primitive value
When comparing a Wrapper to a primitive, auto-unboxing occurs and the comparison is performed primitive to primitive.

equals
For Wrapper classes, two objects are equals if they are of the same type and have the same value.
Please regard that StringBuffer does not override equals (so, cannot compare values), but StringBuilder does override equals (compares values).

Monday, February 11, 2013

SCJP - Overriding vs overloading

Overriding Rules:
Access - cannot have a more restrictive access.
Argument list - must match exactly
Return type - the same or a subtype (this is the called covariant return, new in Java 5)
Exceptions - Can throw any unchecked (runtime) exceptions; cannot throw checked exceptions that are new or broader (must by the same, a subtype or none); can throw less or narrower.

private, final or static method cannot be overriden:
private methods are not visible in the derived class, so if the method has the same signature in the derived class, then it is a new method - no compilation failure.
final methods mean that they cannot be redefined, or a compiler error is generated.
static method cannot be overriden because they do not belong to the instance.
  • When a child class contains the same instance method as a parent class instance method (assuming all the rules of method overriding are followed), the child class method overrides the parent class method.
  • When a child class contains a static method that is the same as a static method in the parent, this child method hides the parent class method.
  • A child class cannot contain a nonstatic version of a static method in its parent class. Neither can a child class contain a static method with the same version of a nonstatic method in the parent. Either of these situations generates a compiler error.

In simpler terms, instance methods are overridden and static methods are hidden.
The overriden call is executed in the object type (runtime).

Overloading Rules:
Access - can change
Argument list - Must change
Return type - can change
Exception - can change

The overloaded call is executed in the reference type (compile time).




Information collected from:
SCJP: Sun Certified Programmer for Java Platform Study Guide: SE6 (Exam CX-310-065), Richard F. Raposa
SCJP Sun Certified Programmer for Java 6 Exam 310-065, Katherine Sierra and Bert Bates
A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)

Static imports

A static variable can be imported into a source file, since Java 5.0, which allows the static variable to be accessible without being prefixed with its corresponding class or interface name.

syntax:
import static packagenames.classname.variablename;

E.g. of usage:

import static my.blueprints.House.counter;
import static java.lang.System.*;

class Test {
  public static void main(String [] args) {
    out.println(“counter = “ + counter);
  }
}

SCJP finalize question

Which statement is true?
A. A class's finalize() method CANNOT be invoked explicitly.
B. super.finalize() is called implicitly by any overriding finalize() method.
C. The finalize() method for a given object is called no more than once by the garbage collector.
D. The order in which finalize() is called on two objects is based on the order in which the two objects became finalizable.


TreeSet subset detail

When manipulating a subSet of a TreeSet, you need to know that the subSet is linked to the original set, which means that if changes are performed in the original set, they will also get reflected in the subSet, and vice-versa.

public static void main ( String args [ ] ) {
  TreeSet t = new TreeSet();
  t.add(1);
  t.add(2);
  t.add(4);
  TreeSet t2 = (TreeSet)t.subSet(2, true, 4, true);
  t.add(3);
  System.out.print(t + " " + t2);
}


This will print:
[1, 2, 3, 4] [2, 3, 4]

But if you do this:
public static void main ( String args [ ] ) {
  TreeSet t = new TreeSet();
  t.add(1);
  t.add(2);
  t.add(4);
  TreeSet t2 = (TreeSet)t.subSet(2, true, 4, true);
  t.add(5);
  System.out.print(t + " " + t2);
}


It will print:
[1, 2, 4, 5] [2, 4]

because the number 5 is out of range of the subset.

Sunday, February 10, 2013

SCJP question

What is the result of this code?


class Person{
  String name="No name";
  public Person(String nm){ name=nm;}
}

class Employee extends Person {
  String empID="0000";
  public Employee(String id) { empID=id;}
}

public class EmployeeTest{
  public static void main(String [] args){
    Employee e=new Employee("4321");
    System.out.println(e.empID);
  }
}


A. 4321
B. 0000
C. An exception is thrown at Runtime
D. Compilation fails

Thread States


FAQs concerning Threads:
Q: What happens if we create a thread, and then call twice the start() method?
A: An IllegalThreadStateException is thrown. This is a RuntimeException.

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.

Thursday, January 3, 2013

Java Web Start Cache Viewer is not showing cached applications!

I have a Windows 7 64-bit with Java installed (no matter what version it is) and my Java Web Start Cache Viewer is not showing cached applications!
With this 64-bit Windows 7, when I go to Start -> Settings -> Control Panel -> Java, then click at General tab, "View" button, no cached applications are seen, but I've just downloaded and run a jnlp file just a minute ago.
There is something wrong in here.

So, I googled it, and found the solution that I wish to share with you.

1. Run the cmd window from C:\Windows\SysWOW64
2. Download and run again the jnlp with the command: javaws <url of the jnlp file>
3. Type the command: javaws -viewer

Now the cached application loaded from the jnlp file is displayed correctly in this Java Cache Viewer window and you are able to add a shortcut to it from your desktop. Just right click the cached application and select "Install Shortcuts" from the context menu.

That's it!