Wednesday, February 27, 2013

Java Certification



坑人的题目:
192;193;196;198;199;200;203;205; 224;228; 233;  244; 271, 275, 276, 284


1. invoke constructor: can only use this(); super(); or new // cannot use constructor name directly. 
2. Constructor call must be the first statement in a constructor
package test;

public class Hello {
String title;
int value;
public Hello(){
title += " World";
}

public Hello(int value){
this();//Constructor call must be the first statement in a constructor
this.value = value;
title = "Hello";
//Hello();  1. must call this()/2. 
}
}
3. ALL METHOD IMPLEMENTS FROM INTERFACE MUST BE DECLARED AS PUBLIC

4. Signature 一模一样 -> overriding
method name 一样,formal parameters 不一样 -> overloading

5. The final method can't be override in a subclass.
but, overloading a final method is perfectly legitimate.

6. File(File parent, String child)
          Creates a new File instance from a parent abstract pathname and a child pathname string.

7. Integer is primitive, even it is wrapped. int a = 400; int b = a; a, b share different memory space.

8.  DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.ITALY)

9. string+int 直接转化为string

10. t.join()
The current thread invokes t.join() means that  the current thread  can only start
until t thread finish.

11. overriding: 父类没有throws Exception的情况下,子类不能throws Exception.

no Exception ------------------------------------ Exception

sub ---> super


子类不能抛出比父类大的Exception : RuntimeException例外


12.public variable in inner class can only be accessed from a class in the same package.

13. variables are shadowed while functions are override.

14. int [][] x   is   int []x[]

15. When an object is created, it's necessary to call the constructors of all super classes
to initialize their fields. Java does this automatically at the beginning if you don't. (by adding super();)

16. fields in interface are naturally public final static

17. & is bitwise 位运算符. && is logical.
& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.
18. Class Super{
 Super(int a){}

class Sub extends Super{
 //error, Sub(){super();} will be added automatically, but there is no Super(){} since Super(int a){} is already there and Super(){} will not be added in this case.
}


19. 
...catch(Exception e){...}
catch(NullPointerException npe){...}


Unreachable catch block for NullPointerException. 
It is already handled by the catch block for Exception

20. Initialization of int and Integer (member variables)
default: int -> 0 ;  Integer -> null

21. again, you don't have to catch RuntimeException

22. 
 static void yield() 
          Causes the currently executing thread object to temporarily pause and allow other threads to execute.

ex:
{...
yield();
...}

23. Type Casting Q147

1.compiler will check that there objects are in inheritance tree or not . If they are in tree then it will compile. Otherwise -> compile error.

2.At runtime,actual object will be checked before casting. Here x is not object of Delta so it will fail at runtime.

24.   
  String s = "hello 12 3 wo 2";
  Scanner sc = new Scanner(s);
  System.out.print(sc.nextInt());//java.util.InputMismatchException
if
  String s = "   12 3 2"; //  output: 12
if
  String s = ", 12 3 2";//java.util.InputMismatchException

25. 
没有指定generic type  -> check the Data structure type only. 

26. label must be placed right before the loop Q179

27. A method with the same signature as a private final method in class X can be implemented in a subclass of X. 


class A{ private final void go(){}}
class B extends A{ void go(){}}  // even sharing the same signature, those go() methods have no business with each other.

28 . overriding: return type 是同一个Inheritance Tree 就可以了

29. Overloading depends on just signature not return type.

30. super.method1(); is illegal if method1 is static in super class

1. static methods can’t override.
2. super method use in case of override

31. for loop doesn't expect a iterator object: it expects a collection

32.  subclass 不继承 superclass的 private variables & private method.
但是public, default, protected的variables可以直接在subclass里面直接使用也可以在variable前面加'this.'


33. 在一个class中看到implement来自interface的method,一定要确认它是public method.

34. 看到super class的constructor有formal parameter,确认一下其有没有加上无参constructor. 因为在这种情况下JVM不会自动加。


Important Notes


  1. ALL METHOD IMPLEMENTS FROM INTERFACE MUST BE DECLARED AS PUBLIC



2. ClassName(){ super(){}} is added automatically if there is no programmer-defined constructor.
QUESTION NO: 88
Given:
1. public class Plant {
2. private String name;
3. public Plant(String name) { this.name = name; } //if (Plant has no Constructor) JVM  add Plant(){ super(){} } automatically;

4. public String getName() { return name; }
5. }


1. public class Tree extends Plant { 
//Tree(){ super(){} } was added automatically.
2. public void growFruit() { }
3. public void dropLeaves() {}  
4. }

The code will compile if public Plant() { this("fern"); } is added to the Plant class.


Sleep, Yield, and Join


We can prevent a thread from execution by using any of the 3 methods of Thread class:
  1. yield()
  2. join()
  3. sleep()
  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
  2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.
  3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

    Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
    A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it's interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.
    The sleep() method is a static method that sleeps the currently executing thread's state. One thread cannot tell another thread to sleep.
    The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.
    If not explicitly set, a thread's priority will have the same priority as the priority of the thread that created it.
    The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.
    The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in therunnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.
    When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed.

Tuesday, February 26, 2013

What Is Java "assert" Statement?


What Is Java "assert" Statement?
"assert" statements are part of the Java assertion feature introduced in Java 1.4. Java assertion feature allows developer to put "assert" statements in Java source code to help unit testing and debugging.
An "assert" statement has the following format:
   assert boolean_expression : string_expression;
When this statement is executed:
  • If boolean_expression evaluates to true, the statement will pass normally.
  • If boolean_expression evaluates to false, the statement will fail with an "AssertionError" exception.
Here is a good example of an "assert" statement used to check an invariant:
// Day-of-week calculator
// by FYICenter.com

public class DayOfWeek {
  private int days = 0;

  // main method for testing purpose
  public static void main(String[] arg) {
    int d = Integer.parseInt(arg[0]);
    DayOfWeek o = new DayOfWeek(d);
    System.out.print("Day of the week: "+o.getDayOfWeek());
  }
  
  // constrcutor
  public DayOfWeek(int d) {
    days = d;
  }

  // calculate day of the week
  public String getDayOfWeek() {
    if (days % 7 == 0) {
       return "Sunday";
    } else if (days % 7 == 1) {
       return "Monday";
    } else if (days % 7 == 2) {
       return "Tuesday";
    } else if (days % 7 == 3) {
       return "Wednesday";
    } else if (days % 7 == 4) {
       return "Thursday";
    } else if (days % 7 == 5) {
       return "Friday";
    } else {
       assert days % 7 == 6 : days;
       return "Saturday";
    }
  }
}
How To Compile and Run Java Programs with "assert" Statements?
If you are using "assert" statements in your Java program for unit testing and debugging, you need to compile and execute the program with extra command options to use them:
  • Compilation - "javac -source 1.4 MyClass.java". This tells the compiler to accept source code containing assertions.
  • Executionn - "java -ea MyClass". This tells the JVM to not skill "assert" statements. "-ea" is the same as "-enableassertions".
Here is an example of compiling and executing the sample program, DayOfWeek.java, presented in the previous question:
javac -source 1.4 DayOfWeek.java

java -ea DayOfWeek 1
Day of the week: Monday

java -ea DayOfWeek 6
Day of the week: Saturday

java -ea DayOfWeek 14
Day of the week: Sunday

java -ea DayOfWeek -2
Exception in thread "main" java.lang.AssertionError: -2
        at DayOfWeek.getDayOfWeek(DayOfWeek.java:34)
        at DayOfWeek.main(DayOfWeek.java:11)
As expected, the code does not handle negative numbers correctly.

Inner class


Why can outer Java classes access inner class private members?

http://stackoverflow.com/questions/1801718/why-can-outer-java-classes-access-inner-class-private-members



local variable must be final to be accessed from the inner (and anonymous) class.
http://stackoverflow.com/questions/3901597/access-to-variable-within-inner-class-in-java

super()


package test;

public class Super {
protected int a;
protected Super(int a) { this.a = a; }
}

----------------


package test;

public class Sub extends Super{
public Sub(int a) { super(a); }
public Sub() { this.a = 5; }//implicitly add super(); but the Super class only has Super(int a)
}

ERROR: Implicit super constructor Super() is undefined. Must explicitly invoke another constructor

10 points on finalize method in Java

http://javarevisited.blogspot.com/2012/03/finalize-method-in-java-tutorial.html

10 points on finalize method in Java – Tutorial Example

finalize method in java is a special method much like main method in javafinalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it make no sense to use finalize method for releasing critical resources or perform any time critical activity inside finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will see some important points about finalize method in JavaHow to use finalize method, what to do and what not to do inside finalize in Java.

what is finalize method in Java – Tutorial Example

1) finalize() method is defined in java.lang.Object class, which means it available to all the classes for sake of overriding. finalize method is defined as protected which leads to a popular core java question "Why finalize is declared protected instead of public"? well I don't know the exact reason its falls in same category of questions like why java doesn't support multiple inheritance which can only be answer accurately by designers of Java. any way making finalize protected looks good in terms of following rule of encapsulation which starts with least restrictive access modifier like private but making finalize private prevents it from being overridden in subclass as you can not override private methods, so making it protected is next obvious choice.

2) One of the most important point of finalize method is that its not automatically chained like constructors. If you are overriding finalize method than its your responsibility to call finalize() method of super-class, if you forgot to call then finalize of super class will never be called. so it becomes critical to remember this and provide an opportunity to finalize of super class to perform cleanup. Best way to call super class finalize method is to call them in finally block as shown in below example. this will granted that finalize of parent class will be called in all condition except when JVM exits:

 @Override
    protected void finalize() throws Throwable {
        try{
            System.out.println("Finalize of Sub Class");
            //release resources, perform cleanup ;
        }catch(Throwable t){
            throw t;
        }finally{
            System.out.println("Calling finalize of Super Class");
            super.finalize();
        }
     
    }

3) finalize method is called by garbage collection thread before collecting object and if not intended to be called like normal method.

4) finalize gets called only once by GC thread, if object revive itself from finalize method than finalize will not be called again.

5) Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I doubt if you find any trace of it.

6) There is one way you can guarantee running of finalize method by calling System.runFinalization() and
Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.

Alternative of finalize method for cleanup.

what is finalize method in Java – Tutorial ExampleSo far its seems we are suggesting not to use finalize method because of its non guaranteed behavior but than what is alternative of releasing resource, performing cleanup because there is no destructor in Java. Having a method like close() or destroy() make much sense for releasing resources held by classes. In fact JDK library follows this. if you look at java.io package which is a great example of acquiring system resource like file descriptor for opening file, offers close() method for opening stream and close() for closing it. in fact its one of the best practice to call close  method from finally block in java. Only caveat with this approach is its not automatic, client has to do the cleanup and if client forgot to do cleanup there are chances of resources getting leaked, which again suggest us that we could probably give another chance to finalize method. You will be pleased to know that Java 7 has added automatic resource management feature which takes care of closing all resource opened inside try block automatically, leaving no chance of manual release and leakage.

When to use finalize method in Java

As last paragraph pointed out that there are certain cases where overriding finalize make sense, like an ultimate last attempt to cleanup the resource. If a Java class is made to held resource like input output devices, JDBC connection than you should override finalize and call its close() method from finalize. though there is no guarantee that it will run and release the resource timely best part is we are not relying on it. It just another last attempt to release the resource which most likely have been already released due to client calling close() method. This technique is heavily used inside Java Development library. look at below example of finalize method from FileInputStream.java

 protected void finalize() throws IOException {
        if ((fd !null) &&  (fd !FileDescriptor.in)) {

            /*
             * Finalize should not release the FileDescriptor if another
             * stream is still using it. If the user directly invokes
             * close() then the FileDescriptor is also released.
             */

            runningFinalize.set(Boolean.TRUE);
            try {
                close();
            } finally {
                runningFinalize.set(Boolean.FALSE);
            }
        }

    }

What not to do in finalize method in Java

trusting finalize method for releasing critical resource is biggest mistake java programmer can made. suppose instead of relying on close() method to release file descriptor, you rely on finalize to relapse it for you. Since there is no guaranteed when finalize method will run you could effectively lock hundreds of file-descriptor of earlier opened file or socket and there is high chance that your application will ran out of file-descriptor and not able to open any new file. Its best to use finalize as last attempt to do cleanup but never use finalize as first or only attempt.

That's all on finalize method in Java. as you have seen there are quite lot of specifics about finalize method which java programmer should remember before using finalize in java. In one liner don’t do time critical task on finalize method but use finalize with caution.


Read more: http://javarevisited.blogspot.com/2012/03/finalize-method-in-java-tutorial.html#ixzz2M3YDIjnE