Showing posts with label Java Certification. Show all posts
Showing posts with label Java Certification. Show all posts

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 java. finalize() 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 Java, How 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

static block


Thursday, January 24, 2013

1/24/2013



1. Primitives and collections

Why Java Collections can not directly store Primitives types?

It was a Java design decision (mistake). Containers want Objects and primitives don't derive from Object.
Generics allow you to pretend there is no wrapper, but you still pay the performance price of boxing. This is IMPORTANT to many programmers.

what is so hard technically to include primitive types when talking about Generics ?
In Java's case, it's because of the way generics work. In Java, generics are a compile-time trick, that prevents you from putting an Image object into an ArrayList<String>. However, Java's generics are implemented with type erasure: the generic type information is lost during run-time. This was for compatibility reasons, because generics were added fairly late in Java's life. This means that, run-time, an ArrayList<String> is effectively an ArrayList<Object> (or better: just ArrayList that expects and returns Object in all of its methods) that automatically casts to String when you retrieve a value.

But since int doesn't derive from Object, you can't put it in an ArrayList that expects (at runtime) Object and you can't cast an Object to int either. This means that the primitive int must be wrapped into a type that does inherit from Object, like Integer.


2. A constructor cannot be abstract, static, final, native, or synchronized
It can be public, protected, default, and private.

But, what’s the point of having a private constructor?



2.1 The first that you only want objects to be created internally – as in only created in your class.

Private constructors can be used in the singleton design pattern

2.2 The second is that you don’t want any objects of your class to be created at all.
when creating an object doesn’t make sense – and this occurs when the class only contains static members.


3. Static method can only use static variables.


4. The concept is : || and && are short circuiting operation i.e. if the value of the expression can be known by just seeing the first part then the remaining part is not evaluated while | and & will always let all the parts evaluates.

robust design
if ( (str == null) || (i == str.length() )
(i == str.length()) will only be evaluated if (str == null) is false, and (str == null) will be false if 'str' is NOT null. So it will NEVER throw a NullPointerException.


5. Unlike a class, an interface can extend from multiple interfaces.

6. invalid Identifier

My Variable // Contains a space
9pins // Begins with a digit
a+c // The plus sign is not an alphanumeric character
testing1-2-3 // The hyphen is not an alphanumeric character
O'Reilly // Apostrophe is not an alphanumeric character
OReilly_&_Associates // ampersand is not an alphanumeric characterIdentifiers must comply with these rules:

7. key word:  native?  friendly?

Wednesday, January 16, 2013

1/16/2013 Java Certification


1. What is wrong with the following code?
abstract class TestClass{
   transient int j;
   synchronized int k;  //Variables cannot be declared synchronized. 
   final void TestClass(){}//This is not a constructor because it has return type
   static void f(){  //cannot be declared static Because it refers to instance variables j and k
      k = j++;
   }
}


2. You cannot store primitives in an ArrayList because only Objects can be stored in it.
An ArrayList is backed by an array.

Integer can be stored in it while int cannot.

3. There is no graph in Collections.


4. Trie Structure?



5. Overriding

class A{
   A() {  print();   }
   void print() { System.out.println("A"); }
}
class B extends A{
   int i =   Math.round(3.5f);
   public static void main(String[] args){
      A a = new B();
      a.print();
   }
   void print() { System.out.println(i); }
}






Monday, January 14, 2013

7 - Anonymous Inner Classes

1. Final formal parameter

Use the final modifier on formal paramaters to methods when you want to make it clear that the supplied value is not modified by that method.



Note also that using final on a reference variable does not mean that you can't change the value that the reference points to -- only that you won't change the reference itself.







Anonymous Inner Classes


An anonymous class in Java is a class with no specified name declared and instantiated at the same time.
Because it has no name it can only be used once at place of declaration.
Anonymous classes implement an interface or extend a class. They cannot declare their own constructors (they don’t have a name known to the programmer) so the constructor used for instantiation is one inherited from the superclass. In the case where the the anonymous class implements an interface a no parameter constructor inherited from java.lang.Object is used.
Access of Anonymous class
Anonymous classes are given a name by the compiler and they are treated as local inner classes. 
This means that anonymous classes can access members of the enclosing class regardless of their access modifiers and they can access final variables declared in the enclosing block of code.

The next example provides the basic syntax and shows how complexity can add up when the concept is “abused”;
01.package com.littletutorials.nested;
02. 
03.public class AnonymousTest
04.{
05.private String s = "test member access";
06. 
07.public void test(final String s)
08.{
09.// anonymous instance as a variable
10.Runnable r = new Runnable()
11.{
12.@Override
13.public void run()
14.{
15.System.out.print(getClass().getName() + " inner in ");
16.System.out.println(getClass().getEnclosingClass());
17.System.out.println("in anonymous class 1");
18.System.out.println(AnonymousTest.this.s);
19.}
20.};
21. 
22.Thread t1 = new Thread(r, "anonymous 1");
23. 
24.// anonymous instance as a parameter
25.Thread t2 = new Thread (new Runnable()
26.{
27.int a = 5;
28. 
29.@Override
30.public void run()
31.{
32.System.out.print(getClass().getName() + " inner in ");
33.System.out.println(getClass().getEnclosingClass());
34.System.out.println("in anonymous class 2");
35.System.out.println(s);
36. 
37.// anonymous instance inside another anonymous class
38.Thread t3 = new Thread (new Runnable()
39.{
40.@Override
41.public void run()
42.{
43.System.out.print(getClass().getName() + "inner in ");
44.System.out.println(getClass().getEnclosingClass());
45.System.out.println("in anonymous class 3");
46.System.out.println("a = " + a);
47.}
48. 
49.});
50.t3.start();
51.try
52.{
53.t3.join();
54.}
55.catch (InterruptedException e)
56.{
57.e.printStackTrace();
58.}
59.}
60. 
61.}, "anonymous 2");
62. 
63.try
64.{
65.t1.start();
66.t1.join();
67.t2.start();
68.t2.join();
69.}
70.catch (InterruptedException e)
71.{
72.e.printStackTrace();
73.}
74.}
75. 
76.public static void main(String[] args)
77.{
78.new AnonymousTest().test("final parameter");
79.}
80.}
The output of the execution reveals the naming conventions used by the compiler for anonymous classes:
com.littletutorials.nested.AnonymousTest$1 inner in class com.littletutorials.nested.AnonymousTest
in anonymous class 1
test member access
com.littletutorials.nested.AnonymousTest$2 inner in class com.littletutorials.nested.AnonymousTest
in anonymous class 2
final parameter
com.littletutorials.nested.AnonymousTest$2$1 inner in class com.littletutorials.nested.AnonymousTest$2
in anonymous class 3
a = 5

As you can see each anonymous class is numbered in the order of declaration in the enclosing class.
Usually anonymous classes are used for short non reusable implementations. Examples are runnable instances, listeners etc.
This post is part of a series explaining the Java concept of defining classes in other classes: