So Hot !!

Java Coding Tips

1. Short way to initial array

boolean[] side=new boolean[SIDE_SIZE];
Arrays.fill(side, Boolean.TRUE);

2.Using StringBuffer instead of String when have to concat string object, it saves a lot of memory

//------test string buffer ---------
StringBuffer sb=new StringBuffer("hello");
//String s="hello";
for(i=0;i<1000;i++){
sb.append("test test test");
//s+="test test test";
}
System.out.println(sb.toString());
//System.out.println(s);

//try to compare memory uses between string s and stringbuffer sb
System.out.println("Total Memory"+Runtime.getRuntime().totalMemory());
System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());

3.When compare String , use equals method

String test1="hello";
String test2="hi";

if(test1.equals(test2))
//do something

4.[BUG Point]When divide something with integer, make sure to cast divider to float.

int divider=2;

float ans=5/divider; // this gets 2 not 2.5

float ans2=5/(float)divider; //this gets 2.5

5.How to insert text between text

StringBuilder sb = new StringBuilder();
sb.append("こんにちは。元気です。");
sb.insert(5, "鈴木さん");

6. Convert byte array to string

String s = bytes.toString(); //this gave "[B@187aeca"
String s = new String(bytes); //this gave "readable txt"

Share this page :

Custom Search