Moon Light Box

Time is Money

Posts match “ java ” tag:

Java - Shadow

| Comments

public class ShadowExample {
    public static void main() {
        Food mFood = new Food();
        Rice mRice = new Rice();
        
        System.out.println("mFood.price = ", mFood.price);
        System.out.println("mRice.price = ", mRice.price);
    }
    
    class Food {
        protected int price = 100;
        
        public Food() {
            System.out.println(price);
        }
    }
    
    class Rice extends Food {
        protected int price = 200; // shadow


        public Rice() {
            System.out.println(price);
        }
    }
}
Result:
mFood.price = 100
mRice.price = 200

If remove below line

protected int price = 200; // shadow

And result is

Result:
mFood.price = 100
mRice.price = 100

Java - Serializable

| Comments

When program is executed, it will be loaded into memory.
And we cannot access the data directly in memory.
If you want to save the data to a file, we can use Serializable interface.

public class Food implements Serializable {
    private String name = "";
    private int price = 0;
    
    public Food(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

public class FoodToFile {
    public static void main(String args[]) {
        Food mFood = new Food("rice", "100");
        
        try {
            FileOutputStream mFileOutputStream = new FileOutputStream("Food.txt");
            ObjectOutputStream mObjectOutputStream = new ObjectOutputStream(mFileOutputStream);
            mObjectOutputStream.writeObject(mFood); 
            mObjectOutputStream.close();
            mFileOutputStream.close();
        } catch (IOException ie) {
            System.err.println(e);
        }
    }
}

Java - NULL

| Comments

We usually use below statements to check a variable whether it is null or not.

This is using C language concept and it is a worng statement.

if (food == "") {
    // do something here

}

This is using Java API equals, but it is still a worng statement.

if (food.equals("")) {
    // do something here

}

And this is the same situation.

if (food != null) {
    // do something here

}

Why? Because food is possible not to be an instance when checking.

Actually, it will cause NullPointerException and we always forget using try-catch to handle.

To avoid NPE, we must modify statement in a better way.

if ("".equals(food)) {
    // do something here

}

or

if (null != food) {
    // do something here

}

Java - Callback

| Comments

Sometimes, a class need execute some specific task when it is triggered by other class calling.
In other words, a morning call service is a callback mechanism in our life.
You tell waiter to call you at six every morning.
Then waiter will give you a morning call when time's up.

And we can use interface to achieve this concept.

public interface MorningCall {
    public void call();
}
public class Guest implements MorningCall {
    public static void main(String[] args) {
        Waiter mWaiter = new Waiter();
        mWaiter.makeCall(this);
    };

    @Override
    public void call() {
        System.println.out("Guest: I Get Up.");
    }
}
public class Waiter {
    public void makeCall(MorningCall mMorningCall) {
        System.println.out("Waiter: Make a Morning Call At Six O'Clock.");
        mMorningCall.call();
    }
}

Java - getInstance VS new

| Comments

Usually, you write this syntax to create an instance.

Father myFather = new Father();

Then we consider family relation of a father and his children then write this.

public class Father {
    public Father() {
    }
}
public class ChildA {
    public void getFather() {
        return new Father();
    }
}
public class ChildB {
    public Father getFather() {
        return new Father();
    }
}
public class Family {
    public static void main(String[] args) {
        ChildA mChildA = new ChildA();
        ChildB mChildB = new ChildB();
        if (mChildA.getFather().equals(mChildB.getFather())) {
            System.out.println("Same father.");
        } else {
            System.out.println("Difference father.");
        }
    }
}

Oh my god, we get the terrible result.

Result:
Difference father.

We have to modify.

public class Father {
    private static Father mFather = new Father();
    public static Father getInstance () {
        return mFather;
    }
}
public class ChildA {
    public Father getFather() {
        return Father.getInstance();
    }
}
public class ChildB {
    public Father getFather() {
        return Father.getInstance();
    }
}

Summary :

getInstance() is not a Java reserved name.
But it is a potential standard which we want only one instance when class be created.

Java - Singleton Pattern

| Comments

Singleton pattern can make a class to be created the only one instance.

First, writing a singleton class.

public class Singleton {
    public Singleton() {
    }
}

Then you will do this to use it. And this way causes duplicate instances when you call new many times.

Singleton mSingleton = new Singleton();

So we modify design to this.

public class Singleton {
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        return new Singleton();
    }
}

But it still happened duplicate instances when we call several times of Singleton.getInstance();.

Next, we modify it again.

public class Singleton {
    private static Singleton mSingleton;
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        if (null == mSingleton) {
            mSingleton = new Singleton();
        }
        return mSingleton;
    }
}

Do we finish it? No. Let us think about multi-thread situation instead of single-thread.

Thread1: if (null == mSingleton) // This will be true.
Thread2: if (null == mSingleton) // This will be true.

Thread1: mSingleton = new Singleton();
Thread2: mSingleton = new Singleton();

Thread1: return mSingleton;
Thread2: return mSingleton; 

Happened duplicate instances again! Let us added synchronized to protect.

public class Singleton {
    private static Singleton mSingleton;
    private Singleton() {
    }
   
    public static synchronized Singleton getInstance() {
        if (null == mSingleton) {
            mSingleton = new Singleton();
        }
        return mSingleton;
    }
}

Now, duplicate instances problem is solved. And the new problem is performance.
If there are many threads running, a thread need wait front thread until it finished work.
So we can do this. Initialed the Singleton class only once when program on started.

public class Singleton {
    private static Singleton mSingleton = new Singleton();
    private Singleton() {
    }
   
    public static Singleton getInstance() {
        return mSingleton;
    }
}

Java - concat vs append

| Comments

concat():
String has concat method, remember string is immutable.
It adds a string to another string.
It will create the new object after concatenation done, since it is a immutable.

append():
StringBuilder and StringBuffer has append method, remember these two are mutable.
It appends a char or char sequence to a string.
It will not create a new object, since it is a mutable one.

https://stackoverflow.com/questions/25138587/what-is-difference-between-mutable-and-immutable-string-in-java

http://pydoing.blogspot.tw/2011/01/java-concat.html

http://javadomain.in/ifference-between-concat-and-append-in-java/

http://stackoverflow.com/questions/8962482/yet-again-on-string-append-vs-concat-vs

http://stackoverflow.com/questions/8755063/concatenation-operator-vs-concat?lq=1

http://stackoverflow.com/questions/8962482/yet-again-on-string-append-vs-concat-vs

answer
http://stackoverflow.com/questions/14927630/java-string-concat-vs-stringbuilder-optimised-so-what-should-i-do

Java - Anonymous Inner Class

| Comments

但有時候我們所設計的類別, 在程式中只會用到一次, 根本不會重複使用。費時去定義一個類別, 再來建立物件, 就顯得沒有必要了, 此時就能利用匿名類別的技巧來建立此類別物件, 同時也有使程式碼較簡化的功效。

http://openhome.cc/Gossip/Java/AnonymousInnerClass.html

http://ccckmit.wikidot.com/ja:implicitoverride

http://www.codedata.com.tw/java/understanding-lambda-closure-7-jdk8-lambda-syntax/

http://openhome.cc/Gossip/JavaGossip-V1/InnerClass.htm

Android - Install Android Developer Tools on Mac OS 10.10 Yosemite

| Comments

Problem

If you occurred below error message when you open a new Android Project, please upgrade JDK7 to JDK8.
Because Mac OS 10.10 Yosemite doesn't support JDK7 or lower.

Errors running builder 'Android Resource Manager' on Project java.lang.NullPointerException

Step1.

Download Android Developer Tools as follows.

  1. Eclipse Java Luna
  2. Android SDK 23.0.2
  3. JDK 8 Update 25

Step2.

Remove old version JDK.

  1. Finder -> Search JavaAppletPlugin.plugin -> Move JavaAppletPlugin.plugin to Trash
  2. Remove /Library/Java/JavaVirtualMachines/jdk<major>.<minor>.<macro[update]>.jdk

Step3.

Double-click jdk-8u25-macosx-x64.dmg then install it and you can check result in terminal.

Step3.

Start Eclipse -> Help -> Install New Software -> Add -> Enter Name and Location

  1. Name: ADT Plugin
  2. Location: https://dl-ssl.google.com/android/eclipse/

Android - KitKat Support Java 7

| Comments

ADT 22.6.0 (March 2014)

General Notes:
Added support for Java 7 language features like multi-catch, try-with-resources, and the diamond operator. These features require version 19 or higher of the Build Tools. Try-with-resources requires minSdkVersion 19; the rest of the new language features require minSdkVersion 8 or higher. To use the new language features after installing ADT 22.6.0, ensure that you run Eclipse on JDK 7 and change your application project settings to use JDK 7.

Reference:http://developer.android.com/tools/sdk/eclipse-adt.html

Linux - Install OpenJDK1.8 in CentOS 7

| Comments

Step 1.

sudo yum -y install java-1.8.0-openjdk.x86_64 java-1.8.0-openjdk-devel.x86_64

Step 2.

sudo vim /etc/profile.d/java-sdk-env.sh

Add below.

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin

Linux - Install Oracle JDK1.8 in CentOS 7

| Comments

Step 1.

# yum remove *openjdk* -y
# cd /opt
# wget http://download.oracle.com/otn-pub/java/jdk/8u102-b14/jdk-8u102-linux-x64.tar.gz
# tar zxvf jdk-8u102-linux-x64.tar.gz
# ln -s jdk1.8.0_102/ jdk

Step 2.

# vim /etc/profile.d/java-sdk-env.sh

Add below.

export JAVA_HOME=/opt/jdk
export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin

Step 3.

# source /etc/profile

Step 4.

# cd /opt/jdk1.8.0_102/
# alternatives --install /usr/bin/java java /opt/jdk1.8.0_102/bin/java 2
# alternatives --config java

There are 1 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
   1           /opt/jdk1.8.0_101/bin/java

Enter to keep the current selection[+], or type selection number: 1

# alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_102/bin/jar 2
# alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_102/bin/javac 2
# alternatives --set jar /opt/jdk1.8.0_102/bin/jar
# alternatives --set javac /opt/jdk1.8.0_102/bin/javac

http://tecadmin.net/install-java-8-on-centos-rhel-and-fedora/#