Thursday, September 29, 2011

SCJP 6 Part III

Constructor
  • Character, Byte, Short
Any integer that is passed as constructor parameter must be casted because int require memory space bigger than char, byte, or short so there could be some bits loss.
Character c1 = new Character((char) 19);
  • Long, Float, Double
Any integer can be passed to long, float, or double constructor without casting because int always fits memory of long, float, or double.
Long l1 = new Long(18);

We then can conclude that if the being passed primitive is bigger, it needs casting.
new Integer(shortObject.shortValue());
new Integer((int) shortObject.doubleValue());

Primitive
  • Character, Byte, Short
Any integer that can fit char, byte, or short memory can be referenced without casting.
char c3 = 127;
Any integer that can not fit char, byte, or short memory must be casted because there could be some bits loss.
char c5 = (char) 123456;
  • Long, Float, Double
Any integer can be referenced to long, float, or double.
long l5 = 128;

We then can conclude that if the being passed primitive is bigger, it needs casting.
float f = 90;
long l = 90;
double d = 90;
int i = (int) d;
short s = (short) f;
long l = (long) f;

Autoboxing
  • Character, Byte, Short
Any integer that can fit char, byte, or short memory can be referenced without casting.
Character c3 = 127;
Any integer that is greater than char, byte, or short bits must be casted because there could be some bits loss.
Character c5 = (char) 123456;
  • Long, Float, Double
Any integer must be casted to be referenced by long, float, or double because long has l, float has f, and double has d after int.
Long l5 = (long) 128;
Long l5 = 128l;

From autoboxing example above we can conclude that we must always cast the primitive to the appropriate format. This applies for char, byte, short, int, long, float, and double.

private void m(Double d) {...}

m(anIntObject); // compile error. Integer is not a Double
m(anIntObject.intValue); // compile error. Equal to Double d = 123;
m((double)
anIntObject.intValue); // OK
m(anIntObject.doubleValue); // OK

SCJP 6 Part II

Character c3 = 127;
Character c4 = 127;

if (c3 == c4) {
System.out.println("Literals Character less than 127 is the same character");
}

Byte b3 = 127;
Byte b4 = 127;

if (b3 == b4) {
System.out.println("Literals Byte less than 127 is the same byte");
}

Short sh3 = 127;
Short sh4 = 127;

if (sh3 == sh4) {
System.out.println("Literals Short less than 127 is the same short");
}

Integer int5 = 100;
Integer int6 = 100;

if (int5 == int6) {
System.out.println("Literals Integer less than 127 is the same integer");
}

Long l3 = (long) 127;
Long l4 = (long) 127;

if (l3 == l4) {
System.out.println("Literals Long less than 127 is the same long");
}

Float f3 = (float) 66;
Float f4 = (float) 66;

if (f3 ==f4) {
System.out.println("Literals Float is the same float");
}

Double d3 = (double) 6;
Double d4 = (double) 6;

if (d3 == d4) {
System.out.println("Literals Double is the same double");
}

Boolean bol3 = true;
Boolean bol4 = true;

if (bol3 == bol4) {
System.out.println("Literals Boolean is the same boolean");
}

Result :

Literals Character less than 127 is the same character
Literals Byte less than 127 is the same byte
Literals Short less than 127 is the same short
Literals Integer less than 127 is the same integer
Literals Long less than 127 is the same long
Literals Boolean is the same boolean

We can conclude that two different objects created by assigning primitive to it, if the primitive is between -128 and 127, they are equal object for Charater, Byte, Short, Integer, and Long but not equal for Float and Double.

Obviously, if the primitives are not between -128 and 127, they are two different objects.

SCJP 6 Part I

String str1 = new String("My name is Budi");
String str2 = new String("My name is Budi");

if (str1 == str2) {
System.out.println("Object String is the same string");
}

String str3 = "Your name is Budi";
String str4 = "Your name is Budi";

if (str3 == str4) {
System.out.println("Literals String is the same string");
}

Character c1 = new Character((char) 19);
Character c2 = new Character((char) 19);

if (c1 == c2) {
System.out.println("Object Character is the same character");
}

Byte b1 = new Byte((byte) 8);
Byte b2 = new Byte((byte) 8);

if (b1 == b2) {
System.out.println("Object Byte is the same byte");
}

Short sh1 = new Short((short) 9);
Short sh2 = new Short((short) 9);

if (sh1 == sh2) {
System.out.println("Object Short is the same short");
}

Integer int1 = new Integer(1000);
Integer int2 = new Integer(1000);

if (int1 == int2) {
System.out.println("Object Integer is the same integer");
}

Long l1 = new Long(18);
Long l2 = new Long(18);

if (l1 == l2) {
System.out.println("Object Long is the same long");
}

Float f1 = new Float(17);
Float f2 = new Float(17);

if (f1 == f2) {
System.out.println("Object Float is the same float");
}

Double d1 = new Double(5000);
Double d2 = new Double(5000);

if (d1 == d2) {
System.out.println("Object Double is the same double");
}

Boolean bol1 = new Boolean(true);
Boolean bol2 = new Boolean(true);

if (bol1 == bol2) {
System.out.println("Object Boolean is the same boolean");
}

Result : Literals String is the same string

We can conclude that two different objects with same literals are always two different objects.

Thursday, September 15, 2011

Useful Java util Classes

There are some useful classes defined in java util package. Lets visit them:

Arrays

This class contains methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

Integer[] array = new Integer[] {5, 3, 1, 4, 2, 4, 9};

// sort array
Arrays.sort(array);

// search integer 4 in the array and return the index using binary search algorithm
// note that the array must be in sort
int index = Arrays.binarySearch(array, 4);

// fill or replace index 2 (inclusive) until index 5 (exclusive) with integer 100
Arrays.fill(array, 2, 5, 100);

// create a List from an array
List list = Arrays.asList(array);

Collections

This class consists of methods that operate on or return collections.

List src = new ArrayList();
src.add(new Integer(5));
src.add(new Integer(3));
src.add(new Integer(1));
src.add(new Integer(4));
src.add(new Integer(2));
src.add(new Integer(4));
src.add(new Integer(9));

// reverse the order of the elements in the list
Collections.reverse(src);

// get max Integer element in the list
Integer result = Collections.max(src);

// get min Integer element in the list
Integer result = Collections.min(src);

// replace all integer 4 with integer 1000 in the list
Collections.replaceAll(src, new Integer(4), new Integer(1000));

// replace oldBean with newBean, they are compared using Object.equals() method
Collections.replaceAll(src, oldBean, newBean);

// swap objects in index 0 and 6
Collections.swap(src, 0, 6);

// replace all objects in the list with the new integer object
Collections.fill(src, new Integer(1999));

// sort objects in the list
Collections.sort(src);

// search an element in the list. The list must be sorted first
Collections.binarySearch(src, key);

// shuffle the list
Collections.shuffle(src);

StringBuffer & StringBuilder

Both classes are used to deal with string, however, StringBuffer is thread-safe because it performs thread synchronization. StringBuilder should be used when we don't need thread synchronization.

SimpleDateFormat

SimpleDateFormat is a class for formatting and parsing date (date to text and vice versa). Date and time formats are specified by date and time pattern strings.



// create SimpleDateFormat object
SimpleDateFormat format = new SimpleDateFormat("'on' dd/MMMM/yyyy");

// format date to string
String formattedDate = format.format(new Date()); // result: on 19/September/2011

// format string to date
Date date = format.parse("on 12/August/2001");

Properties

This class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

// create Properties object
Properties properties = new Properties();

// load Properties from input stream
InputStream inStream = new FileInputStream("properties.properties");
properties.load(inStream);

// get property
String name = properties.getProperty("property.name");
String size = properties.getProperty("property.size");

// set property
properties.setProperty("property.size", "101");

// persistent property
OutputStream out = new FileOutputStream("properties.properties");
properties.store(out, "Comments here");

The content of properties file:

property.name=Rochmat Santoso
property.size=101

equals, hashCode, and toString with Apache Commons

Lets now play a little bit with Apache Commons EqualsBuilder, HashCodeBuilder, and ToStringBuilder.

ToStringBuilder

When we print an object to console, something not meaningful like [Ljava.lang.String;@a90653 will be printed. If we have an entity bean, most likely we prefer printing all of its properties in a formatted string to previous string. To achieve that, we can use ToStringBuilder class in Apache Commons Lang library.

public class MyBean {

private String name;
private String address;
private String email;

@Override
public String toString() {
return new ToStringBuilder(this).append("name", name).append("address", address).append("email", email).build();
}

}

And the result will be MyBean@a62fc3[name=Al Pacino,address=Surabaya,email=gmail].

EqualsBuilder

When we want to compare two entity beans, most likely we want to compare by properties. If both entity holds same properties, they are equal. We can use EqualsBuilder to do this.

@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}

if((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}

MyBean target = (MyBean) obj;
return new EqualsBuilder().append(this.name, target.name).append(this.address, target.address).append(this.email, target.email).isEquals();
}

HashCodeBuilder

Note that we must override the Object.hashCode() if we override Object.equals(). We can use HashCodeBuilder to create hash code for an object.

@Override
public int hashCode() {
return new HashCodeBuilder().append(this.name).append(this.address).append(this.email).toHashCode();
}

Wednesday, September 14, 2011

Enum

Since version 1.5.0, Java introduced enum as a special kind of class. It lets us to rewrite our static final constants to enum class. Here is a simple example:

public enum OrderStatus {
NEW,
COMPLETE,
BILLING_FAILED,
SHIPPED;
}

It is pretty straightforward, isn't it? Now lets put constructor, methods, and variables in it:

public enum OrderStatus {

NEW(20),
COMPLETE(100),
BILLING_FAILED(-1),
SHIPPED(80);

private int percent;

private OrderStatus(int paramPercent) {
this.percent = paramPercent;
}

public int getPercent() {
return percent;
}

}

Now what happens if we print it on console?

System.out.println(OrderStatus.NEW.name()); // this will print NEW
System.out.println(OrderStatus.NEW.getPercent()); // this will print 20
System.out.println(OrderStatus.NEW.ordinal()); // this will print 0

Note that the first statement must be the constant (NEW, COMPLETE, etc in our example), otherwise the compiler will generate error messages. In addition, the constructor can't be declared as public (that's why I declare it as private).

To get a list of all constants of the enum we can use OrderStatus.values() and it will return an array of {NEW, COMPLETE, BILLING_FAILED, SHIPPED} in that order.

Wednesday, August 24, 2011

Java Access Modifier

While waiting for the lunch time lets do something very basic but quiet interesting; Java access modifier.

There are four access modifiers in Java: public, protected, private, and package access. Suppose we have a project with package structure as below:



There are four classes:
1. A superclass for other classes named SuperClass
2. A subclass of class SuperClass named SubClassA which resides at the same package as its superclass.
3. A subclass of class SuperClass named SubClassB which resides at different package as its superclass.
4. Another class at different package named Main.



The SuperClass has all four different level access method. We will see which methods are visible at any of the other three classes.



We can see that the public, protected, and package access level methods are visible in class SubClassA through both inheritance and reference.



Now we can see that there are only public and protected methods visible to class SubClassB through inheritance and only public method visible through reference. This happens because package level access, as its name suggest, only applies for classes reside at same package. Whereas protected applies for all of its subclasses.

There is a note here regarding overriding protected method. As we can see in class SubClassB, we override method protectedMethod from its superclass. Therefore, all classes at the same package with class SubClassB can access SubClassB's protectedMethod through reference. However, if we didn't override the protectedMethod, all other classes at the same package wouldn't be able to access it at all because protectedMethod would become private in SubClassB.



For a class at another package, as we can see in class Main, can only access public methods.

The access levels are simple and clear, aren't they? All method modifiers also apply to instance variables as well. OK, now it's time to go out for lunch.

Monday, August 22, 2011

Cassandra Architecture

Apache Cassandra is not another relational database in market. Instead of using relational model, it uses key-value map to store its data. The structure is more or less can be explain as in the following picture:



Cluster: Cassandra is designed to be distributed over several nodes/machines. A cluster consists of several nodes. I've only ever used Cassandra in a single node which is my computer.

Keyspace: A cluster consists of several keyspaces. Keyspace is the place where our data reside. A keyspace could have several Column Family or Super Column Family.

Column Family and Super Column Family: Both Column Family and Super Column Family is a collection of rows, just like a table is a collection of rows in relational database.

Row: A row consists of columns; key-value columns for a row in Column Family, or Super Columns for a row in Super Column Family.

Super Column: It is sort of container of sub-columns (which are of type Key-value Column).

Key-value Column: The most basic data structure in Cassandra where the actual data is saved as byte. The behavior is a lot like Java Hash data type.

Here are examples of Cassandra data retention and retrieval:

COLUMN_FAMILY_NAME[ROW_KEY_NAME][COLUMN]

User['user1']['name'] = 'Rochmat Santoso';
User['user1']['address'] = 'Surabaya';
User['user2']['name'] = 'Barbie';
User['user2']['address'] = 'Malibu';

SUPER_COLUMN_FAMILY_NAME[ROW_KEY_NAME][SUPER_COLUMN_NAME][COLUMN]

Province['province1']['info']['name'] = 'East Java';
Province['province1']['info']['capital'] = 'Surabaya';
Province['province1']['city']['sby'] = 'Surabaya';
Province['province1']['city']['mlg'] = 'Malang';
Province['province1']['city']['sda'] = 'Sidoarjo';

Province['province2']['info']['name'] = 'West Java';
Province['province2']['info']['capital'] = 'Bandung';
Province['province2']['city']['bdg'] = 'Bandung';
Province['province2']['city']['tgr'] = 'Tangerang';

Wednesday, August 10, 2011

Annotation

Setelah sekian lama akhirnya punya waktu juga untuk mencoba annotation. Beberapa catatan untuk annotation ini adalah:
- Tambahkan @Documented agar annotation ini bisa di-generate saat membuat javadoc karena defaultnya sebuah annotation tidak di-generate oleh javadoc tool.
- Tambahkan @Retention(RetentionPolicy.RUNTIME) untuk menyimpan data-data annotation pada saat kompilasi sehingga bisa dibaca saat runtime. Jika tidak disimpan maka kita tidak bisa membacanya.
- Ada beberapa macam tipe annotation tergantung tempat di mana annotation itu akan ditempatkan misalnya di class, method, field, parameter, konstruktor, dll. Gunakan @Target(value = ElementType.TYPE) untuk annotation yang diletakkan di Class atau interface. Beberapa tipe yang lain adalah @Target(value = ElementType.METHOD) untuk annotation pada method, @Target(value = ElementType.FIELD) untuk annotation pada field, @Target(value = ElementType.PARAMETER) untuk annotation pada method parameter, dll.

Berikut ini adalah contoh annotation dan cara mengaksesnya

Friday, August 5, 2011

Lucene Analyzer

There are several analyzer available in Lucene:

WhitespaceAnalyzer: It splits text into tokens on whitespace characters. It doesn't normalize the tokens and doesn't lowercase each token.

SimpleAnalyzer: It splits tokens at non letter characters and lowercases each token. It discards numeric characters but keeps all other characters.

StopAnalyzer: It acts almost same as SimpleAnalyzer except it removes common words. By default, it removes common words specific to English (the, a, etc).

StandardAnalyzer: It is the most sophisticated core analyzer. It has quite a bit of logic to identify certain kinds of tokens such as company names, email addresses, and hostnames. It lowercases each token and removes stop words and punctuation.

KeywordAnalyzer: It treats entire text as a single token.
 

©2009 Stay the Same | by TNB