Thursday, February 4, 2016

[Java] 5 Basic questions

1 what is "Arbitrary Number of Arguments" : 可变参数 : ...
It allows the method to take one or more parameters of the same type.  f(int ...a) --> f(int[] a)

2what is assert  :  to assert if a expression is true
 ex : assert(myValue == 0); if true, nothing; if false, throws AssertionError
is often used for assert input parameters

3 when the GC runs :  heap stack no enough and CPU is free. JVM uses System.gc() to call GC
   when memory is full occupied and there is no object can do the GC, : OutOfMemoryException.
   before the object is removed from memory, finalize() will be called. Not use finalize in your code.

4 static initialization block  static { ... }
static block, just call one time during compilation
public class InitializerExamples {
static int count;
int i;

static{
//This is a static initializers. Run only when Class is first loaded.
//Only static variables can be accessed
System.out.println("Static Initializer");
//i = 6;//COMPILER ERROR
System.out.println("Count when Static Initializer is run is " + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
InitializerExamples example3 = new InitializerExamples();
}
}
sout:
Static Initializer
Count when Static Initializer is run is 0.
 initialization block  { ... }
block is called every time we create an object
public class InitializerExamples {
static int count;
int i;
{
//This is an instance initializers. Run every time an object is created.
//static and instance variables can be accessed
System.out.println("Instance Initializer");
i = 6;
count = count + 1;
System.out.println("Count when Instance Initializer is run is " + count);
}

public static void main(String[] args) {
InitializerExamples example = new InitializerExamples();
InitializerExamples example1 = new InitializerExamples();
InitializerExamples example2 = new InitializerExamples();
}
}

5 Tokenize : 令牌化
indeed, it's splitting a string : ac;bd;def;e---> ac,bd,def, e
private static void tokenize(String string,String regex) {
String[] tokens = string.split(regex);
System.out.println(Arrays.toString(tokens));
}

Using Scanner to realize :
private static void tokenizeUsingScanner(String string,String regex) {
Scanner scanner = new Scanner(string);
scanner.useDelimiter(regex);
List<String> matches = new ArrayList<String>();
while(scanner.hasNext()){
matches.add(scanner.next());
}
System.out.println(matches);
}


No comments:

Post a Comment