Tuesday, February 12, 2013

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);
  }
}