Java foreign game lottery written test questions

First round of written examination

Written form: paper test
subject difficult degree: medium
written examination time: 1 hours,
written test language: questions and answers are all in English

1 What’s difference between a “static synchronized method” and “synchronized” method

synchronized? A: is the current instance of the lock, to prevent other threads simultaneously access the class of the instance of all synchronized blocks, note here is the “current instance”, two different class no this constraint.
static synchronized just happens to control access to all instances of the class. Static synchronized is the thread that limits the thread to all instances of that class in the JVM while accessing the corresponding block of code.
actually, in a method or a block of code in synchronized, then in creating an instance of this class, the class also has a monitoring block, placed threads concurrent access the instance synchronized protection block. Static synchronized is a shared monitor block for all instances of that class, and that’s the difference between the two. That is, synchronized is equivalent to this.synchronized, while static synchronized is equivalent to classname.synchronized.

2, If, you, define, a, which, will, be, put, a, HashMap, what, methods, will, you, overwrite, class, and, how, into,
, a.:

Import java.util.*; class Person private String private int {username; age; public (Person) {public} Person (String username, int age) {this.username = username; this.age = age;} public String getUsername (return) {username}; public void setUsername (String username) {this.username = username;} public int getAge (return) {age}; public void setAge (int age) {this.age = age;} @Override public Boolean equals (Object obj) {if (this = = obj) return true; if (obj = = null) return false (getClass); if (obj.getClass) = (!) Return false; Person other = (Person) obj; if (age! = other.age) return false; if (name = = null) {if (! = null) return false else if;} (! Name.equals ( return false; return true; @Override public int (hashCode)} {return age*2 public class;}} EqualDemo {public static void main (String[] args) {Map< Person, String> map = new; HashMap< > map.put (New) (Person (tree, 25), System.out.println ("hello"); map.get (New Person (tree, 25)))}};

Running results: Hello

3 Given following requirements please provide, your solution, at least interface/method need to be provideed.
a. We need provide a machanism.
B. It supports log message to file, to database and to a remote server using HTTP.
C. Log message to which target output is configuable.
D. Do not use any existing log library, please implement yours.

“What is the output of the following:”

Public class Foo static void main {public (String[] args) {if ((A)) {System.out.println ("fdsa");}} public static Boolean (A) {try} {return true; catch (Exception x) {finally} / {System.out.println ("asdf");} return false;}}

Run results:
, asdf,
, fdsa

5 Write a Singleton pattern’s implementation, match following requirements.
b.Lazy initializing
C. (Optional) Using Java 1.5 new feature to implement it.

Public class Singleton private Singleton (private) {} {static Singleton = instance null public Singleton (getInstance); static {if (null = = instance) {synchronized (Singleton.class) {if (null = = instance) {instance = new (Singleton);}}}}} return instance;

6 Given following requirements please provide, your solution, at lease interface/method need to be provided.
a. Design a cache machanism, which can cache any type of objects.
B. The cache’s capacity is 1000000 objects.

7, How, to, start/commit/rollback, a, transaction, using, JDBC, API,
, answer:

Connection, Conn = DriverManager.getConnection ("jdbc:oracle:thin:@host:1521:SID", "username", "password"); conn.setAutoCommit (false); conn.commit (); conn.rollback ();

The “Code review. Give some comments to improve the code quality.”

9 You are given 50000 large HTTP files, some of which contain phone numbers and asked to provide a list of the unique numbers contained in the files. How would you go about doing this Describe the algorithm and tools? You would use to accomplish this?

  1. Design and write an implementation of Iterator that meets the following requirements:
    a. It must accept an instance of an Iterator as a parameter in the constructor.
    B. It must allow the user to specify a predicate that is used to filter the items in the supplied iterator.
    C. The hasNext (method) must only return true if and only if there is at least one remaining element in the supplied iterator that satifies the predicate.
    D. The next (method) must only return values that satisfy the predicate.
The definition of a Collection interface public interface Collection container {void add (Object obj); int (size); Iterator (iterator);} defines a Iterator iterator interface public interface Iterator {Object next (Boolean); (hasNext);} define a ArrayList that implements the Collection interface and write a to implement the interface Iterator class ArrayList implements Collection internal class public {Object[] objects = new Object[10]; int index = 0; @Override public void add (Object obj) {if (index = = objects.length) {Object[] newObjects = new Object[objects.length * 2]; System.arraycopy (objects, 0, newObjects, 0, objects.length); objects = newObjects objects[index] = O;} BJ; index++; @Override public int (size)} {return index;} @Override public Iterator (iterator) new (ArrayListIterator) {return}; private class ArrayListIterator implements Iterator private int {cursor = 0; @Override public Boolean (hasNext) {return = size (cursor!); @Override public Object (next)} Object {obj = objects[cursor]; cursor++; return obj;}}} {Test class test: public public static void main (String[] args) {Collection C = new (ArrayList); for (int i = 0; I 5; < i++) {c.add (string + I); } System.out.println ("The + c.size (length is:)); Iterator it = c.iterator (while); (it.hasNext) (obj = Object) {(; System.out.println ((obj.toString) +" ");}}}

Running results:
, The, length, is:, 5,
, string, 0,
, string, 1,
, string, 2,
, string, 3,
, string,

Second round interview

There are two interviewers and technical questions are deeper

1 introduce yourself in English

2 architecture and technical details of a project

The 3 synchronized synchronization method calls another synchronized synchronization method

Public, synchronized, void, methodA (int, a, int, b) {{; public, synchronized, void, methodB (int, a) {methodA (a, 0)}

should understand two questions: who is the object of the lock; who holds the lock?.
has three cases:
(1) assumes that methods A and B are the two methods in the same class Test.
Test t = new Test (
); t.methodB (
); this time, the methodB method is invoked, because the addition of synchronized, you need to first obtain a lock, the lock object should be t, which is the current instance of the Test class, and obtain a lock is something that is thread. Said the current thread to get the t lock (instead of the B method to acquire the lock), this time the B method call methodA, because A also added synchronized, also need to obtain a lock, because A and B are the methods of the Test class, so the current thread to obtain the lock object is t. Since the current thread already holds the lock of the t object when the B method is executed, it is no use calling methodA at this time, which is equivalent to the method of not adding synchronized on the A. The synchronized method added to the non static method is equivalent to the synchronized (this) block, both of which are object locks, that is, the this lock (
). Gets the thread of the current object lock, you can continue to get the current object lock, and JVM is responsible for tracking the number of times the object is locked. Run the B thread, if this can be used to obtain the thread lock, lock, thread to the object lock counter into 1, then B method called the A method because it is on the same object with a thread, the thread can continue to get the lock, counter to 2, said the this is locked to 2 times. When the A method is finished, the thread releases the lock and the counter becomes 1. At this point, the object lock is still not available to other threads. When the B method is finished, the thread continues to release the lock, when the counter becomes 0, indicating that the lock is fully released and that other threads can get the object lock.

(2) suppose that there are two Test
Test T1 = new Test (
); Test T2 = new (Test);
(t1.methodB); / / the current thread holds the lock object (T1
t2.methodB); / / the current thread also holds the T2
the current thread holds the lock on the object. Two locks, lock objects are two different instances of the Test class T1 and T2, had no effect on each other.

(3) hypothesis in a multi-threaded environment, two threads can access the Test t=new Test (
); thread1 t.methodB (assuming the call); and t.methodB (
) thread2 in the call when assuming the thread1 t object to grab the lock, then thread2 need to wait for the thread1 t release the lock on the object can execute B methods. The results of
like this:
thread1 -&gt t thread1 to acquire the lock; methodB-> thread1 methodA-> t release lock; thread2 -&gt t thread2 to acquire the lock; methodB-> thread2 methodA-> t release lock.

Synchronized has many ways of using it, but it’s easy to understand what it means to get the lock of which object the thread gets.

4 has a static variable, num, with an initial value of 0. Now open 1000 threads, each thread within 1000 cycles, each cycle to num plus 1, ask the final value is greater than, equal to or less than 1000000?
(1) less than 1000000, because there are 1000 threads, different threads may access num at the same time, resulting in less than the number of self increasing.

Import java.util.concurrent.TimeUnit; public class Test implements Runnable{private static int num @Override public = 0; void (run) {for (int i = 1; I < =1000; i++) {num++; System.out.println (Thread.currentThread) (.GetName) ("num + =" + Num);}} (main void public static String[] args throws InterruptedException for (int) {I = 1; I < =1000; i++) {Thread thread = new Thread (New) (Test); thread.setName ("Thread:"); thread.start (+i);} try {/ / wait for all Zi Xiancheng completed TimeUnit.SECONDS.sleep (30) catch (InterruptedException E;} {(e.printStackTrace)); } System.out.println ("Finally, Num =" + Num)}}

Thread:19, num
Thread:19 = 999981, Num = 999982
Thread:975, Num = 999983, Num = 999367
Thread:975, Num = 999984, Num = 999985
Thread:975, Num = 999986, Num = 999987
Thread:975, Num = 999988, Num = 999989
Finally, Num = 999990, Num = 999990

(2) if you want to prevent this phenomenon, use the static synchronized keyword to synchronize the data protection.

Import java.util.concurrent.TimeUnit; public class Test implements Runnable{private static int num static synchronized = 0; private void increaseNumber (num++) {}; @Override public void (run) {for (int i = 1; I < =1000; i++) {(increaseNumber); System.out.println (Thread.currentThread) (.GetName (Num) + ". =" + Num);}} public static void main (String[] args throws InterruptedException for (int) {I = 1; I < =1000; i++) {Thread thread = new Thread (New) (Test); thread.setName ("Thread:"); thread.start (+i);} try {/ / wait for all Zi Xiancheng finished TimeUnit.SE CONDS.sleep (30);} catch (InterruptedException, e) {e.printStackTrace ();} System.out.println (` Finally ',' num = '+ Num)}}

Thread:3, num
Thread:3 = 999993, Num = 999994
Thread:3, Num = 999995, Num = 999996
Thread:3, Num = 999997, Num = 999998
Thread:3, Num = 999999, Num = 1000000
Finally, Num = 999985, Num = 1000000

5 what’s wrong with the following code?

Try {return 0;} catch (Exception, e) {return 1;} finally {return 2;} return 3;

last return 3 will cause compile error: Unreachable code.

(1) will execute the finally block regardless of whether there is a return statement in the try block or in the catch block.
(2) return return statement in the finally block will cover the front (the return statement in the catch block, try block), so if there is a return statement in the finally block, the Eclipse compiler will report “finally block does not complete warning normally”.
(3) if the finally block contains a return statement, even if the block in front of the catch rethrows the exception, this method is called the statement will not get catch block rethrows the exception, but will be the return value of the finally block, and no exception.

Experiment 1:

Public class MyTest public static int (func) {{try} {return 0; catch (Exception E) {return 1;} finally {return 2}}; public static void main (String[] args) {int = func (RES); System.out.println (res= + RES);}}

Running results:

Experiment 2:

Public class MyTest public static int (func) {try {int {a = 2 / 0; return 0;} catch (Exception E) {System.out.println ("exception"); (e.printStackTrace); return 1;} finally {return}} 2; public static void main (String[] args) {int res = (func); System.out.println (res= + RES);}}

Operation result:

Capturing exceptions: java.lang.ArithmeticException: / by, zero, at, Test.func (, at, Test.main (, res=2

6 what kinds of exceptions does Java have?
(1) basic concept,
, the exception structure diagram

[Uploading! Throwable_458816.png. “

Throwable is the root of all exceptions. Java.lang.Throwable
Error is an error. Java.lang.Error
Exception is an exception, java.lang.Exception

(2) Exception
is generally divided into abnormal Checked and abnormal Runtime, all instances of the RuntimeException class and its subclasses are called Runtime anomaly, does not belong to the category of the anomaly is called CheckedException.

Checked exception
only the Java language provides the Checked exception, and Java considers the Checked exception to be an exception that can be processed, so the Java program must display the handling of the Checked exception. If the program does not handle the Checked exception, the program will compile errors and cannot compile. This reflects Java’s philosophy of design: code without perfect error handling does not have the chance to be executed at all. There are two kinds of Checked exception handling methods:
A., the current method knows how to handle the exception, and the try / catch block is used to process the exception. The
B. does not know how to handle the current method, and declares that exception is thrown when the method is defined.
our more familiar Checked exceptions are
, Java.lang.ClassNotFoundException,
, Java.lang.NoSuchMetodException,

, Runtime, such as divisor is 0 and array subscript cross, etc., and its frequent occurrence, dealing with trouble, if the declaration or capture, will have a great impact on the readability and efficiency of the program. So they are automatically detected by the system and handed over to the default exception handler. Of course, if you have processing requirements, you can also display capture them. We are familiar with the
subclass of RumtimeException

(3) Error
, when an error occurs in a program, the usual practice is to notify the user and abort the execution of the program. Unlike exceptions, objects of Error and its subclasses should not be thrown.
Error is a subclass of throwable that represents compilation errors and system errors that are used to indicate a serious problem that a reasonable application should not attempt to capture.
Error is generated and thrown by the Java virtual machine, including dynamic link failure, virtual machine error, and so on. The program does not handle it.

7 stack
answer: the
heap is usually an array object that can be considered as a tree. The heap always satisfies the following nature: the value of a node in the
(1) heap is always no greater than or less than the value of its parent; the
(2) heap is always a completely two fork tree.
will be the largest pile of root node is called the maximum heap or root heap, heap the smallest root node is called the minimum heap or a small heap.

8 from the principle of hash table to analyze why different objects can have the same
hashCode a.
(1), because hashCode can be overloaded. For example, the Teacher class
heavy hashCode:
int hashCode (
return age) {
* 2; another example of class Doctor heavy hashCode:
int hashCode (
return age) {
* 2; according to the above rules, as long as teachers and doctors of the same age, they have the same hashCode. But they are obviously different objects.

(2) in principle, hash requires only the mapping from A to B as a mapping, and it does not limit the mapping to one-to-one mapping. So there is the possibility that two different key values correspond to the same hash value. This situation is called a hash collision (hash collision) or a hash conflict. For example, the checksum in the network protocol might be the case that the content to be verified is different from the original, but the same as the checksum (hash) generated by the original. For example, the MD5 algorithm is often used to calculate the hash values of passwords. Experiments have shown that the MD5 algorithm is likely to crash, that is, different plaintext passwords generate the same hash value, which will bring great security vulnerabilities to the system.

9, two fork tree traversal sequence
can refer to the establishment of sorting two fork tree, and in the order traversal

10, two stack simulation of a queue,
can refer to the use of two stacks to simulate a queue