Sunday, July 2, 2017

Java Index Parameters: from - including, to - excluding

String string1 = "Hello World";

String substring = string1.substring(0,5);
After this code is executed the substring variable will contain the string Hello.
The substring() method takes two parameters. The first is the character index of the first character to be included in the substring. The second is the index of the character after the last character to be included in the substring. Remember that. The parameters mean "from - including, to - excluding". This can be a little confusing until you memorize it.
@reference_1_jenkov.com

Saturday, July 1, 2017

Strings in Java are immutable

Concatenating Strings means appending one string to another. Strings in Java are immutable meaning they cannot be changed once created. Therefore, when concatenating two Java String objects to each other, the result is actually put into a third String object.
Here is a Java String concatenation example:
String one = "Hello";
String two = "World";

String three = one + " " + two;
The content of the String referenced by the variable three will be Hello World; The two other Strings objects are untouched.

String Concatenation Performance

When concatenating Strings you have to watch out for possible performance problems. Concatenating two Strings in Java will be translated by the Java compiler to something like this:
String one = "Hello";
String two = " World";

String three = new StringBuilder(one).append(two).toString();
As you can see, a new StringBuilder is created, passing along the first String to its constructor, and the second String to its append() method, before finally calling the toString() method. This code actually creates two objects: A StringBuilder instance and a new String instance returned from the toString() method.
When executed by itself as a single statement, this extra object creation overhead is insignificant. When executed inside a loop, however, it is a different story.
Here is a loop containing the above type of String concatenation:
String[] strings = new String[]{"one", "two", "three", "four", "five" };

String result = null;
for(String string : strings) {
    result = result + string;
}
This code will be compiled into something similar to this:
String[] strings = new String[]{"one", "two", "three", "four", "five" };

String result = null;
for(String string : strings) {
    result = new StringBuilder(result).append(string).toString();
}
Now, for every iteration in this loop a new StringBuilder is created. Additionally, a String object is created by the toString() method. This results in a small object instantiation overhead per iteration: One StringBuilder object and one String object. This by itself is not the real performance killer though. But something else related to the creation of these objects is.
Every time the new StringBuilder(result) code is executed, the StringBuilder constructor copies all characters from the result String into the StringBuilder. The more iterations the loop has, the bigger the result String grows. The bigger the result String grows, the longer it takes to copy the characters from it into a new StringBuilder, and again copy the characters from the StringBuilder into the temporary String created by the toString() method. In other words, the more iterations the slower each iteration becomes.
The fastest way of concatenating Strings is to create a StringBuilder once, and reuse the same instance inside the loop. Here is how that looks:
String[] strings = new String[]{"one", "two", "three", "four", "five" };

StringBuilder temp  = new StringBuilder();
for(String string : strings) {
    temp.append(string);
}
String result = temp.toString();
This code avoids both the StringBuilder and String object instantiations inside the loop, and therefore also avoids the two times copying of the characters, first into the StringBuilder and then into a String again.
@reference_1_jenkov.com

String Literals as Constants or Singletons

If you use the same string (e.g. "Hello World") in other String variable declarations, the Java virtual machine may only create a single String instance in memory. The string literal thus becomes a de facto constant or singleton. The various different variables initialized to the same constant string will point to the same String instance in memory. Here is a Java String constant / singleton example:
String myString1 = "Hello World";
String myString2 = "Hello World";
In this case the Java virtual machine will make both myString1 and myString2 point to the same String object.
More precisely, objects representing Java String literals are obtained from a constant String pool which the Java virtual machine keeps internally. That means, that even classes from different projects compiled separately, but which are used in the same application may share constant String objects. The sharing happens at runtime. It is not a compile time feature.
If you want to be sure that two String variables point to separate String objects, use the new operator like this:
String myString1 = new String("Hello World");
String myString2 = new String("Hello World");
Even though the value (text) of the two Java Strings created is the same, the Java virtual machine will create two different objects in memory to represent them.

@reference_1_jenkov.com

Thursday, June 29, 2017

Proxy Pattern

@reference_1_tutorialspoint
Design Patterns - Proxy Pattern

There are many different flavours of Proxy, depending on it's purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.

This pattern is recommended when either of the following scenarios occur in your application:
  • The object being represented is external to the system.
  • Objects need to be created on demand. 
  • Access control for the original object is required
  • Added functionality is required when an object is accessed.
You'll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.

@reference_2_dzone.com
Proxy Pattern Tutorial with Java Examples

If you've read my "Decorate Your Java Code" (JavaWorld, December 2001), you may see similarities between the Decorator and Proxy design patterns. Both patterns use a proxy that forwards method calls to another object, known as the real subject. The difference is that, with the Proxy pattern, the relationship between a proxy and the real subject is typically set at compile time, whereas decorators can be recursively constructed at runtime.

@reference_3_javaworld
Java Design Patterns

Wednesday, June 28, 2017

JAVA_HOME、PATH、CLASSPATH

JAVA_HOME
指的是你JDK安装的位置,一般默认安装在C盘,如 C:\Program Files\Java\jdk1.8.0_91

PATH
将程序路径包含在PATH当中后,在命令行窗口就可以直接键入它的名字了,而不再需要键入它的全路径,比如上面代码中我用的到javac和java两个命令。
一般的 PATH=%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;%PATH%;
也就是在原来的PATH路径上添加JDK目录下的bin目录和jre目录的bin.

CLASSPATH CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar
一看就是指向jar包路径。
需要注意的是前面的 . 代表当前目录。

@reference_1_csdn

JAVA_HOME= C:\Program Files\Java\jdk1.6.0_10
Path= %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;
CLASSPATH= .;%JAVA_HOME%\lib;

@reference_2_zhidao.baidu

The bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib directory. This class loader, which is part of the core JVM, is written in native code.
The extensions class loader loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext, or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.
The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

@reference_3_wikipedia

Tuesday, June 27, 2017

Java ClassLoader

@reference_1_stackoverflow
What is a Java ClassLoader?
@reference_2_oracle
Understanding Network Class Loaders
@reference_3_docs.oracle
Class ClassLoader

The bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib directory. This class loader, which is part of the core JVM, is written in native code.
The extensions class loader loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext, or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.
The system class loader loads code found on java.class.path, which maps to the CLASSPATH environment variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

@reference_4_wikipedia

Every class loaded in a Java application is identified by its fully qualified name (package name + class name), and the ClassLoader instance that loaded it. That means, that a class MyObject loaded by class loader A, is not the same class as the MyObject class loaded with class loader B.
MyObject object = (MyObject)
    myClassReloadingFactory.newInstance("com.jenkov.MyObject");
 
Notice how the MyObject class is referenced in the code, as the type of the object variable. This causes the MyObject class to be loaded by the same class loader that loaded the class this code is residing in.
If the myClassReloadingFactory object factory reloads the MyObject class using a different class loader than the class the above code resides in, you cannot cast the instance of the reloaded MyObject class to the MyObject type of the object variable. Since the two MyObject classes were loaded with different class loaders, the are regarded as different classes, even if they have the same fully qualified class name. Trying to cast an object of the one class to a reference of the other will result in a ClassCastException.
It is possible to work around this limitation but you will have to change your code in either of two ways:
  1. Use an interface as the variable type, and just reload the implementing class.
  2. Use a superclass as the variable type, and just reload a subclass.
Here are two coresponding code examples:
MyObjectInterface object = (MyObjectInterface)
    myClassReloadingFactory.newInstance("com.jenkov.MyObject");
MyObjectSuperclass object = (MyObjectSuperclass)
    myClassReloadingFactory.newInstance("com.jenkov.MyObject");
 
@reference_5_tutorials.jenkov.com
Java Reflection - Dynamic Class Loading and Reloading

Monday, June 19, 2017

Youdao Dictionary API

http://dict.youdao.com/jsonapi?q=nice&keyfrom=deskdict.mini&dogVersion=1.0&dogui%20=%20json&client=deskdict&id=b1915e13d589286bf&vendor=unknown&in=YoudaoDictSetup&appVer=7.2.0.0511&appZengqiang=0&abTest=&le=en&dicts=%7B%22count%22%3A4%2C%22dicts%22%3A%5B%5B%22ec%22%2C%22ce%22%2C%22cj%22%2C%22jc%22%2C%22ck%22%2C%22kc%22%2C%22cf%22%2C%22fc%22%20%2C%20%22multle%22%20%5D%2C%5B%22web_trans%22%5D%2C%5B%22fanyi%22%5D%2C%5B%22typos%22%5D%5D%7D&LTH=47

Decode:
http://dict.youdao.com/jsonapi?q=nice&keyfrom=deskdict.mini&dogVersion=1.0&dogui = json&client=deskdict&id=b1915e13d589286bf&vendor=unknown&in=YoudaoDictSetup&appVer=7.2.0.0511&appZengqiang=0&abTest=&le=en&dicts={"count":4,"dicts":[["ec","ce","cj","jc","ck","kc","cf","fc" , "multle" ],["web_trans"],["fanyi"],["typos"]]}&LTH=47

http://dict.youdao.com/jsonapi?q=good&keyfrom=deskdict.main&dogVersion=1.0&dogui=json&client=deskdict&id=b1915e13d589286bf&vendor=unknown&in=YoudaoDictSetup&appVer=7.2.0.0511&appZengqiang=0&abTest=&le=en&dicts=%7B%22count%22%3A12%2C%22dicts%22%3A%5B%5B%22newjc%22%5D%2C%5B%22newcj%22%5D%2C%5B%22auth_sents_part%22%5D%2C%20%5B%22longman%22%5D%20%2C%20%5B%22collins%22%5D%20%2C%20%5B%22ec21%22%5D%2C%5B%22hh%22%5D%2C%5B%22ee%22%5D%2C%5B%22media_sents_part%22%5D%2C%5B%22rel_word%22%5D%2C%5B%22special%22%5D%2C%5B%22syno%22%5D%5D%7D&LTH=1828

Decode:
http://dict.youdao.com/jsonapi?q=good&keyfrom=deskdict.main&dogVersion=1.0&dogui=json&client=deskdict&id=b1915e13d589286bf&vendor=unknown&in=YoudaoDictSetup&appVer=7.2.0.0511&appZengqiang=0&abTest=&le=en&dicts={"count":12,"dicts":[["newjc"],["newcj"],["auth_sents_part"], ["longman"] , ["collins"] , ["ec21"],["hh"],["ee"],["media_sents_part"],["rel_word"],["special"],["syno"]]}&LTH=1828

http://dict.youdao.com/jsonapi?q=good&le=en&dicts={%22count%22:12,%22dicts%22:[[%22newjc%22],[%22newcj%22],[%22auth_sents_part%22],%20[%22longman%22]%20,%20[%22collins%22]%20,%20[%22ec21%22],[%22hh%22],[%22ee%22],[%22media_sents_part%22],[%22rel_word%22],[%22special%22],[%22syno%22]]}

Decode:
http://dict.youdao.com/jsonapi?q=good&le=en&dicts={"count":12,"dicts":[["newjc"],["newcj"],["auth_sents_part"], ["longman"] , ["collins"] , ["ec21"],["hh"],["ee"],["media_sents_part"],["rel_word"],["special"],["syno"]]}

http://dict.youdao.com/jsonapi?q=good&le=en&dicts={"count":1,"dicts":[["collins"]]}

@url encode/decode