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.
 

©2009 Stay the Same | by TNB