Thursday, August 16, 2012

Generics - Part 2


One of the hardest sections is Generics that was introduced by Sun in Java 5.0, this section will try to summarize the most relevant topics as well as real examples to help you memorize when/where and why use a specific collection for a given scenario.

Let's start with the key interfaces and classes.

Intefaces



Classes



Noticed that almost all the interfaces and classes directly or not extend java.util.Collection, only Map and interfaces and classes under it don't extend java.util.Collection. Take a look at the structure of Collection below:



Watch out - Collections is a utility class which provides static methods and Collection is an interface.

Overview of each member of collections.

¦ Lists - Lists of things (classes that implement List).
¦ Sets  - Unique things (classes that implement Set).
¦ Maps  - Things with a unique ID (classes that implement Map).
¦Queues - Things arranged by the order in which they are to be processed.

Sorted,Unsorted,Ordered and Unordered that's a tricky part of collections

Ordered --> When a collection is ordered, it means you can iterate through the
collection in a specific (not-random) order, find below some examples of ordered and unordered collection


As you can see the class LinkedHashSet keeps the order based on insertion where the last inserted is the last element in a collection, ArrayList keeps the order by using index position and finally Hashtable does not keep the order of its elements.

Sorted --> A sorted collection means that the order in the collection is determined
according to some rule or rules, to determine this rule we need to implement Comparator or Comparable, more about it is comming up.

Let's see an overview of the interfaces and those concrete implementations.

List Interface:
A List cares about the index, it's a ordered collection.

ArrayList:
It's a ordered collection by index but not sorted, it's a good idea choose this collection when you need fast iteration, however is not suitable if your intention is insertion and deletion.

Vector: 
Basically the same as an ArrayList, but its methods are synchronized.

LinkedList: 
It's a ordered collection by index, also it has methods that allow insertion and deletion from the beginning or end.
You'll be in a good shape using this collection to massive insertion and deletion but be careful when you need iteration.
Finally since Java 5.0 it implements java.util.Queue so it has the basic methods peek(), poll(), and offer().

Set Interface:
A Set cares about uniqueness, it doesn't allow duplicates, to do this the method equals() ensures it.

HashSet:
A HashSet is an unsorted, unordered Set, ensure that you did a good implementation for hashCode() method because it's determines a performance of this collection, use it when you don't want duplicates and you don't care about order when you iterate through it.

LinkedHashSet: 
Different from HashSet this collection is ordered, so use it when you care about order when you iterate through it, an order is determined by insertion of elements.

TreeSet:
It's a sorted collection, the elements will be in ascending order based on natural order also you can construct a TreeSet using a Comparator/Comparable.

Map Interface:
A Map cares about unique identifiers. It's structure is based on key/value(Objects of course).
Equals() method determines if the keys are the same or different.

HashMap:
A HashMap is an unsorted, unordered Set, ensure that you did a good implementation for hashCode() method because it's determines a performance of this collection
HashMap allows one null key and multiple null values in a collection.

HashTable:
It's like a Vector where its methods are synchronized, different from HashMap it does not allow null values as well as null key.

LinkedHashMap:
Similar to LinkedHashSet this collection is ordered, so use it when you care about order when you iterate through it, an order is determined by insertion of elements, you can get faster interation but don't expect good performance for insertion and deletion.

TreeMap:
It's a sorted collection, the elements will be in ascending order based on natural order also you can construct a TreeMap using a Comparator/Comparable.

Queue Interface:
Basically used as a FIFO(first in - first out), it supports all the methods related to collections, in addition there are methods for adding, removing and review the queue.

PriorityQueue:
A PriorityQueue's elements are ordered either by natural ordering

See below the table with useful information.


Tuesday, August 14, 2012

Generics - Part 1


Before diving into Generics we have to get a better understanding of some Object's methods like hashCode() and equals().

Overriding equals()

The main purpose of this method is compare if the objects are meaningfully equivalent, if you don't override this method you cannot use the object as a key in a hashtable, it's because when you don't override a equals() method it uses the operator == to do a comparison.

Let's override a equals() method.

Overriding hashCode()

Hascode is used by some Collections, it provides a way to store the objects in a collection as well as it helps to locale the objets within the collections.  If two objects are equal, their hashcodes must be equal as well.

Implementing hashCode()
Let's review equals and hashCode methods



After this brief introduction needed to work with Collections you're able to dive into Collections which will be covered in the next section.

Monday, July 30, 2012

Parsing, Tokenizing and Formatting


Parsing

This section is intended to review all the approches to find, token and format stuff.
Let's see the first example:


As you can see the mehtod matcher from the class Matcher gets a source and the class Pattern uses the method compile to handle a pattern that you want to search.

!Important:

  a b a b a b a
  0 1 2 3 4 5 6

Why the little program showed above didn't print 0 2 4?
The reason is the regex engine does not consider the index 2 because it was consumed, and cannot be reused, but there are expections for this rule and will be shown sooner.

  a b a
  0 1 2

Using Metacharacters

\d A digit
\s A whitespace character
\w A word character (letters, digits, or "_" (underscore))
 . Any character

Output
Matcher ==> 0
5 7 16
Matcher ==> 1
6 14
Matcher ==> 2
0 1 2 3 4 5 7 8 9 10 11 12 13 15 16
Matcher ==> 3
0 1 2
Matcher ==> 4
0 1 2 3 4 8 13
Matcher ==> 5
0 1 2 3 4 8 10 13 15

Using Quantifiers

+ One or more occurrences
* Zero or more occurrences
? Zero or one occurrence


Greedy Quantifiers



Tokenizing

Tokenizing is the process of taking big pieces of source data, breaking them into
little pieces, and storing the little pieces in variables

Tokenizing with Scanner


Formatting with printf() and format()

Both methods have exactly the same behaviour which means anything we say about one of these methods is applicable to both.

Let's see how formatting works:

%[arg_index$][flags][width][.precision]conversion char

The values within [ ] are optional.

1. arg_index - An integer followed directly by a $, this indicates which argument should be printed in this position.

2. flags - While many flags are available, for the exam you'll need to know:
¦ "-" Left justify this argument
¦ "+" Include a sign (+ or -) with this argument
¦ "0" Pad this argument with zeroes
¦ "," Use locale-specific grouping separators (i.e., the comma in 123,456)
¦ "(" Enclose negative numbers in parentheses


3. width -  This value indicates the minimum number of characters to print. (If you
want nice even columns, you'll use this value extensively.)

4. precision - For the exam you'll only need this when formatting a floating-point
number, and in the case of floating point numbers, precision indicates the number of
digits to print after the decimal point.

5. conversion - The type of argument you'll be formatting. You'll need to know:
¦ b boolean
¦ c char
¦ d integer
¦ f floating point
¦ s string





Wednesday, July 18, 2012

Working with Dates/Numbers and Currencies


In this section you'll learn the most common methods to format Dates, Numbers and Currencies as well as the relationship between the main classes responsible to do that.

Let's start with the classes that you have to learn.

java.util.Date;
java.util.Calendar;
java.text.DateFormat;
java.text.NumberFormat;
java.util.Locale;


Console:

Wed Jul 18 10:18:42 AMT 2012
Wed Dec 31 19:16:40 AMT 1969
1342621122734
Wed Jul 18 10:18:42 AMT 2012
Sun Nov 21 04:58:20 AMT 2286

The class java.util.Date is hard to work with,if you look at the preceding example to set a specific date we have to use a number representation(long), this class is normally used to create a date that represents "now" as well as working with java.util.Calendar.


Console:

Sat Sep 15 00:00:00 AMT 2012
Today is Wed Jul 18 10:37:26 AMT 2012
Day of the week 4
Day of the year 200
Last day of the year 259
Remaining Days ==> 59
Fri Jul 18 10:37:26 AMT 2014
Sun May 18 10:37:26 AMT 2014


Watch out, the class Calendar is abstract you cannot create an instance of it(look at line 16), also it provides friendly methods to manipulate dates, where you can add hours, days, weeks, and so on.
Notice the class java.util.Calendar work together java.util.Date, instead of setting a date using number(long) you can use a Date object.
Finally the method roll is similar to add, the difference is it does not change into next month(if you're adding days), years(if you're adding months) and so on.


Console:

Friday, August 17, 2012
Sexta-feira, 17 de Agosto de 2012
vendredi 17 août 2012
viernes 17 de agosto de 2012
2012?8?17?
Parse ==> Fri Aug 17 00:00:00 AMT 2012


The class java.text.DateFormat is an abstract class that provides us formatted dates using or not pré-defined styles as well as Locales.
You can get a DateFormat class by invoking the methods getInstance() and getDateInstance().
Finally we can parse a String to Date by using the method parse() which must be enclosed in a try-catch block.


Console:

pt ->
pt -> Brasil
fr ->
en -> United States


Let's take a briefly look at java.util.Locale.

The first argument is related to the language and the second is a country.
The most important methods are getLanguage() and getDisplayCountry().
There are not setters to define language and country at java.util.Locale.


Console:

1.100,56848
1.100,568
1,100.568
R$ 1.100,57
¤ 1.100,57
$1,100.57
5
1234567
1234567


Similar to java.text.DateFormat the class java.text.NumberFormat works with numbers(currency, percent, and so on), where there are many ways to get a concrete class since NumberFormat is abstract.

getInstance(),
getNumberInstance(),
getCurrencyInstance(),
.. and so on

The method parse() is present as well where you can get a Number object.

Wednesday, July 11, 2012

I/O - Getting better understanding of API


Let's start with the class File


Notice that the file has not been created until the line 13 be reached, to memorize it think of when you create a File(line 10) it doesn't throw any exception but the method createNewFile does.

Serialization

Serialization is the mechanism that allows you save the state of objects.
Find below the keys to make a class serializable.


First of all we have to implement the interface serializable( look at line 11), also to save the state of object we need the classes FileOutputStream and ObjectOutputStream, the writeObject(object) method is responsible for it and to retrieve the serializable object from the file we need FileInputStream and ObjectInputStream the readObject() is responsible for reading it.

!Import

- If you don't want to save a member of object you must mark it as transient
- Whether a super class implements Serializable its subclasses are indirectly Serializable
- Whether a subclass implements Serializable and a superclass doesn't the constructor will be invoked as well as the instance variable will get their default values

Let's see an example:

Let's see what's been saved.



- if you wanna save a state of object that has a reference to another object which does not implement Serializable you have to write the methods writeObject() and readObject().


- Finally we can use serialization with static variables but as you've seen serialization is useful for objects

Print this post

Working with Strings and StringBuffer/StringBuilder

In this section we'll discuss about String as well as its creation, polemic things like "Strings are immutable" and see wthat's going on behind the scenes also StringBuffer and StringBuilder will be on focus.

Let's take a look at how the string objects are created and understand the immutability.




As you can see it prints "Book" because we don't refer the new String created to "Java - Book", so the object is in the heap however nobody refers to it.

Commom methods
Let's see common methods in action.


Pool of String

Also you can use the method intern() (String class) this way we can get the string from the pool if the string pass using the method equals().


StringBuffer and StringBuilder friends of memory

Both classes are intented to help you handle Strings without wasting memory, as we mentioned Strings are immutable and if we have to handle lots and lots of them StringBuffer and StringBuilder will help you.
The unique difference between StringBuffer and StringBuilder is StringBuilder is not thread-safe which means its methods aren't synchronized, as you can imagine StringBuilder is faster than StringBuffer.


The most import thing here is StringBuffer and StringBuilder are not immutable like String and the StringBuffer contains the synchronized methods;

Monday, July 2, 2012

Unusual things in Exceptions


I called this post "Unusual things in Exceptions" because you're going to see something that isn't usually used in a real word as well as staffs that you have to memorize for the OCJP certification.

Let's start with the class hierarchy:



The code above does not compile you cannot handle an exception if the block try does not "throw" one.

!Import
The block finally always is called, even if there is a return statement in the try/catch block, the finally block will be executed before the return stamement.


In this case the block try "throws" an exception throught the creation of FileOutputStream, but we still getting a compiler error, because the catch that handles FileNotFoundException will never be reached.

That's the rule for checked exceptions if you throw an exception you must declare(throws) from the calling method or catch(try/catch).


Different from checked exception, every exception under RuntimeException/Error are not obligated to catch or declare, but if you did you would be able to catch it by using try/catch block.

Common Exception

Let's take a look at the common exception, watch out where they come from