码迷,mamicode.com
首页 > 其他好文 > 详细

JI_3

时间:2014-10-29 18:57:31      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:des   io   os   ar   java   for   sp   strong   on   

Java Interview Questions + some logic questions at the end.

 

Basics:

 

Q1: What happens when the following program executes?

 

class A

{

public void a()

{

b();

}

private void b()

{

System.out.println(“Executing A’s b()”);

}

}

 

class B extends A

{

public void b()

{

System.out.println(“Executing B’s b()”);

}

}

public static void main(String[] argv)

{

B b = new B();

b.b();

b.a();

}

 

For each of these, indicate if True or False:

 

1. B’s b() will run and then A’s b() will run           T

2. A’s b() is going to be called twice          F       

3. B’s b() is going to be called twice          F

4. A’s b() will run and the B’s b() will run             F

5. The compiler will not allow the above code to compile  F

 

Answer : 1 = true

Grading : 10 points for the correct answer

Difficulty : 9/10 A.

 

 

 

 

 

 

 

Q2: More inheritance: what’s the output of this code:

 

class A

{

   public void F() { System.out.println("A.F"); }

   public virtual void G() { System.out.println ("A.G"); }

}

class B: A

{

   new public void F() { System.out.println ("B.F"); }

   public override void G() { System.out.println ("B.G"); }

}

class Test

{

   static void Main() {

      B b = new B();

      A a = b;

      a.F();

      b.F();

      a.G();

      b.G();

   }

}

 

Answer:

A.F    // Not B.F, since class b uses the "new" keyword which breaks the inheritance tree.

B.F                                     

B.G

B.G

 

Difficulty: higher.

 

Q3: And more: describe if each of the following lines of code compiles and will execute without exceptions.

 

class Test

{

          public static void main(String[] args)

          {

                   // Line 1

                   Class2 a = new Class3();

                   // Line 2

                   Class3 b = new Class2();

                   // Line 3

                   Class2 c = (Class2)(new Class3());

                   // Line 4

                   Class3 d = (Class3)(new Class2());

                   // Line 5

                   Class2 e = (new Class3()) as Class2;

                   // Line 6

                   Class3 f = (new Class2()) as Class3;

          }

}

 

 

public class Class2

{

}

 

public class Class3: Class2

{

}

 

A 1. Basic Inheritance.

Line 1: Compiles + Runs.

Line 2: Doesn‘t Compile.

Line 3: Compiles + Runs.

Line 4: Compiles + Throws invalid cast exception.

Line 5: Compiles + Runs.

Line 6: Compiles + Runs.

Q4 How can a subclass call a method or a constructor defined in a superclass?

A: To call a method use the following syntax: super.myMethod();
To call a constructor of the superclass, write super(); in the first line of the subclass‘s constructor

 

Q5: Which of the following statements concerning the Virtual Machine are true and which are false?

 

1. Object are stored in the heap, local variables are stored in the stack.          T

2. The Virtual Machine has 8 registers, each one has the length of one word.  F

3. The Virtual Machine does not differentiate between an instance method and a constructor method.                   F

4. A StackFrame gets created into the VM’s stack area for every thread executed. F

5. The VM keeps a program counter for every thread.                                 T

 

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = true

Grading : 2 points per correct answer

Difficulty : 4/10 A.

 

Q7  When two objects loaded through different Classloaders can they communicate?

 

1. When the invoker object access the other object through an interface that has been loaded using the invoker object’s classloader.

2. When they belong to the same package

3. When the invoker’s classloader has resolved the class of the other object

4. When the Security Manager allows it

5. Never, objects loaded using different Classloaders can’t communicate.

 

Answer : 1 = true

Grading : 10 points for the correct answer

Rational : This question assesses the delegate’s understanding of

Difficulty : 8/10 A.

 

Q8: Explain Java class loaders? Explain dynamic class loading? (this is a follow up on Q6 in case they got it right).

 

A: Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at

non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.

 

CLASS LOADER         reloadable?               Explanation

Bootstrap(primordial) No                         Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar)

 

Extensions                 No                                 Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)

 

System                      No                                 Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options)

 

 

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class

loader will have its own singleton.

 

Q9.  Which of the following are valid ways of making an instance from class X

 

1. X myX = new X();

2. X myX = (X)((X.class).newInstance())

3. X myX = (X)Class.instantiate(X);

4. X myX = (X)(X.class).getClass().forName(”X”).newInstance();

5. X myX = (X)(Class.forName(”X”)).newInstance())

 

Answer : 1 = true, 2 = true, 3 = false, 4 = true, 5 = true

Grading : 10 points for giving all four correct answers

Difficulty : 5/10 A.

 

Q10:  Are there any other ways of creating an object for a class in Java (follow up on Q8)?

 

A: There are four ways in which we can create an object for a class in java, the only not mentioned in Q6 is cloning and through object deserialization (extra points if they mention the deserialization way).

  1. Using New Operator: like Test t=new Test();
  2. Using newInstance(): like Test t=(Test)Class.forName("").newInstance();
  3. Using Clone: like

Test x=new Test();

Test t=x.clone();

  1. Using Object Deserialization : like ObjectInputStream istream=new ObjectInputStream(some inputStream);

 

Q11: How does the Object.clone method work. What is the main difference between shallow cloning and deep cloning of objects?

 

A: The default behaviour of an object’s clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted.

 

Shallow copy: If a shallow copy is performed on obj-1 as shown in fig-2 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.

 

Deep copy: If a deep copy is performed on obj-1 as shown in fig-3 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.

 

For example, invoking clone() method on a HashMap returns a shallow copy of HashMap instance, which means the keys and values themselves are not cloned. If you want a deep copy then a simple method is to serialize the HashMap to a ByteArrayOutputSream and then deserialize it. This creates a deep copy but does require that all keys and values in the HashMap are Serializable. Its primary advantage is that it will deep copy any arbitrary

object graph.

 

Q12: What are “static initializers” or “static blocks with no function names”?

 

A: When a class is loaded, all blocks that are declared static and don’t have function name (ie static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields.

 

public class StaticInitilaizer

{

public static final int A = 5;

public static final int B;

//Static initializer block, which is executed only once when the class is loaded.

static

{

if(A == 5)

B = 10;

else

B = 5;

}

public StaticInitilaizer()

{} // constructor is called only after static initializer block

}

 

The following code gives an Output of A=5, B=10.

public class Test

{

System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B);

}

 

Q13: What is the difference between an abstract class and an interface and when should you use them?

 

A: In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents it.

The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. The interface is a very useful and commonly used aspect in OO design, as it provides the separation of interface and implementation and enables you to:

 

  • Capture similarities among unrelated classes without artificially forcing a class relationship.
  • Declare methods that one or more classes are expected to implement.
  • Reveal an object‘s programming interface without revealing its actual implementation.
  • Model multiple interface inheritance in Java, which provides some of the benefits of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass.

 

Abstract Classes:

Have executable methods and abstract methods.

Can only subclass one abstract class.

Can have instance variables, constructors and any

visibility: public, private, protected, none (aka package).

 

Interfaces:

Have no implementation code. All methods are abstract.

A class can implement any number of interfaces.

Cannot have instance variables, constructors and can have

only public and none (aka package) visibility.

 

When to use an abstract class?: In case where you want to use implementation inheritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior. Care should be taken not to overuse implementation inheritance as discussed in Q8 in Java section.

 

Q14: When is a method said to be overloaded and when is a method said to be overridden?

 

Difficulty: very easy:

A Overloading deals with multiple methods in the same class with the same name but different method signatures.

 

class MyClass

{

public void getInvestAmount(int rate) {…}

public void getInvestAmount(int rate, long principal)

{ … }

}

 

Both the above methods have the same method names but different method signatures, which mean the methods are overloaded.

 

Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.

class BaseClass

{

public void getInvestAmount(int rate) {…}

}

 

class MyClass extends BaseClass

{

public void getInvestAmount(int rate) { …}

}

 

Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.

 

Overloading lets you define the same operation in different ways for different data.

 

Q15: Why there are some interfaces with no defined methods (i.e. marker interfaces) in Java?

A: The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.

 

Q16: What is the main difference between pass-by-reference and pass-by-value?

 

A: Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (ie copy-by-value) works. In Java, if a calling method passes a reference of an object as an argument to the called method then the passed in reference gets copied first and then passed to the called method. Both the original reference that was passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you will be always modifying the same original object, which is how the pass-by-reference works as well.

 

Q17: How do you define a method that assigns default values to parameters in Java?

 

A: You can’t, java doesn’t implement methods with optional parameters and default values, but you can achieve the same effect by overloading methods.

 

void Method1(bool param1)

{

          Method2(param1, false);

}

void Method2(bool param1, bool param2optional)

{

          Method3(param1, param2optional, false); 

}       

void Method3(bool param1, bool param2optional, bool param3optional)

{

          // blah blah blah;     

}       

 

 

 

Q18: What is the difference between an instance variable and a static variable? Give an example where you might use a static variable?

 

Answer:

Static Variables

Class variables are called static variables.

There is only one occurrence of a class variable per JVM per class loader.

When a class is loaded the class variables (aka static variables) are initialized.

Instance variables are non-static and there is one occurrence of an instance variable in each class instance (ie each object).

 

A static variable is used in the singleton pattern. A static variable is used with a final modifier to define constants.

 

Q20: Give an example where you might use a static method?

A: Static methods prove useful for creating utility classes, singleton classes and factory methods

Utility classes are not meant to be instantiated. Improper coding of utility classes can lead to procedural coding. java.lang.Math, java.util.Collections etc are examples of utility classes in Java.

 

Q21: Where and how can you use a private constructor?

Difficulty: easy/medium.

Answer: Private constructor is used if you do not want other classes to instantiate the object. The instantiation is done by a public static method within the same class.

 

// follow up with a question where you’d might want to use a private constructor and see if you get any of the following

 

  Used in the singleton pattern.

  Used in the factory method pattern

  Used in utility classes e.g. StringUtils etc.

 

Q22: What is the difference between final, finally and finalize() in Java?

 

Difficulty: easy

Answer:

 

  final - constant declaration. Refer Q27 in Java section.

  finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

  finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

 

 

Q23: Explain Outer and Inner classes (or Nested classes) in Java? When will you use an Inner Class?

 

A: In Java not all classes have to be defined separate from each other. You can put the definition of one class inside the definition of another class. The inside class is called an inner class and the enclosing class is called an outer class. So when you define an inner class, it is a member of the outer class in much the same way as other members like attributes, methods and constructors.

Where should you use inner classes? Code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions

in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class

 

JAVA VM/Performance:

 

Q1: Which of the following statements concerning the Virtual Machine are true and which are false?

 

1. Object are stored in the heap, local variables are stored in the stack. T

2. The Virtual Machine has 8 registers, each one has the length of one word.  F

3. The Virtual Machine does not differentiate between an instance method and a constructor method. F

4. A StackFrame gets created into the VM’s stack area for every thread executed. F

5. The VM keeps a program counter for every thread. T

 

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = true

Grading : 2 points per correct answer

Difficulty : 4/10 A.

 

Q2 Which of the following statements concerning performance are true and which are false?

 

1. Methods called through an interface reference are slower than those called through abstract methods because they can never be pointed directly by fields in the class pool of the caller T

2. The invocation of an interface method is slower than Instantiation F

3. The statement x = 3 executes faster than the statement x = 15. T

4. Hotspot compilers convert all the bytecode into native code at runtime F

5. Polymorphic calls are almost as fast as static method calls.  F

 

Answer : 1 = true, 2 = false, 3 = true, 4 = false, 5 = false

Grading : 2 points per correct answer

Difficulty : 8/10 A.

 

Q3: How does Java allocate stack and heap memory? Explain re-entrant, recursive and idempotent methods/functions?

 

Difficulty: medium/harder.

 

A: Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

 

A method in stack is reentrant (medium – should know this) allowing multiple concurrent invocations that do not interfere with each other.

A function is recursive (easy – must know this) if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive.

 

Idempotent (harder/this is a bit academic)methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

 

Q4: What do you know about the Java garbage collector? When does the garbage collection occur? Explain different types of references in Java?

 

Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can’t force it.

 

What is an unreachable object? An object’s life has no meaning unless something has reference to it. If you can’t reach it then you can’t ask it to do anything. Then the object becomes unreachable and the garbage collector will figure it out. Java automatically collects all the unreachable objects periodically and releases the memory consumed by those unreachable objects to be used by the future reachable objects.

 

API/Collections:

 

Q1: What does the Object.equals method do (implementation). Follow up with why equals works for Strings.

A1: Want to hear some mention that the default implementation of equals compares the memory of the objects.

 

Q2: What is the main difference between a String and StringBuffer class?

 

A:

String

String is immutable: you can’t modify a string object but can replace it by creating a new instance. Creating a new instance is rather expensive.

 

//Inefficient version using immutable String

String output = “Some text”

Int count = 100;

for(int I =0; i<count; i++)

{

output += i;

}

return output;

 

The above code would build 99 new String objects, of which 98 would be thrown away

immediately. Creating new objects is not efficient.

 

StringBuffer / StringBuilder

 

StringBuffer is mutable: use StringBuffer or StringBuilder when you want to modify the contents.

StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronised, which makes it slightly faster at the cost of not being thread-safe.

 

//More efficient version using mutable StringBuffer

StringBuffer output = new StringBuffer(110);

Output.append(“Some text”);

for(int I =0; i<count; i++)

{

output.append(i);

}

return output.toString();

 

The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed, which is costly however, so it would be better to initilise the StringBuffer with the correct size from the start as shown.

 

** Extra Points if they mention something about this: Another important point is that creation of extra strings is not limited to ‘overloaded mathematical operators’ (“+”) but there are several methods like conact(), trim(), substring(), and replace() in String classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance.

 

Q3: What is the main difference between an ArrayList and a Vector? What is the main difference between Hashmap and Hashtable?

 

Vector / Hashtable

Original classes before the introduction of Collections API.

Vector & Hashtable are synchronized.

Any method that touches their contents is thread-safe.

 

ArrayList / Hashmap

So if you don’t need a thread safe collection, use the ArrayList or Hashmap. Why pay the price of synchronization unnecessarily at the expense of performance degradation.

 

So which is better? As a general rule, prefer ArrayList/Hashmap to Vector/Hashtable. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API‘s external synchronization facility as shown below to temporarily synchronize your collections as needed:

 

Map myMap = Collections.synchronizedMap (myMap);

List myList = Collections.synchronizedList (myList);

 

Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable. ArrayList/Vector internally uses an array with some convenient methods like add(..), remove(…) etc

 

Q4: Explain the Java Collection framework?

A 14: The key interfaces used by the collection framework are List, Set and Map. The List and Set extends the Collection interface. Should not confuse the Collection interface with the Collections class which is a utility class.

 

A Set is a collection with unique elements and prevents duplication within the collection. HashSet and TreeSet are implementations of a Set interface. A List is a collection with an ordered sequence of elements and may contain duplicates. ArrayList, LinkedList and Vector are implementations of a List interface.

 

The Collection API also supports maps, but within a hierarchy distinct from the Collection interface. A Map is an object that maps keys to values, where the list of keys is itself a collection object. A map can contain duplicate values, but the keys in a map must be distinct. HashMap, TreeMap and Hashtable are implementations of a Map interface.

 

How to implement collection ordering? SortedSet and SortedMap interfaces maintain sorted order. The classes, which implement the Comparable interface, impose natural order. For classes that don’t implement comparable interface, or when one needs even more control over ordering based on multiple attributes, a

Comparator interface should be used.

 

Design pattern: What is an Iterator?

An Iterator is a use once object to access the objects stored in a collection. Iterator design pattern (aka Cursor) is used, which is a behavioral design pattern that provides a way to access elements of a collection sequentially without exposing its internal representation.

 

Exception Handling:

 

Q1:

Is it possible to use try-catch in the finally block of java

A: Yes it is possible to use try catch inside the finally block of java. As a matter of fact it is a good practice to do so as the methods called in finally block may throw an exception.

 

Q 2: Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions and checked exceptions? What is the implication of catching all the exceptions with the type “Exception”?

A :

Errors: When a dynamic linking failure or some other “hard” failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addition, it’s unlikely that typical Java programs will ever throw Errors either.

 

Exceptions: Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious JVM problem. An Exception class has many subclasses. These descendants indicate various types of exceptions that can occur. For example, NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One exception subclass has special meaning in the Java language: RuntimeException. All the exceptions except RuntimeException are compiler checked exceptions. If a method is capable of throwing a checked exception it must declare it in its method header or handle it in a try/catch block. Failure to do so raises a compiler error. So checked exceptions can, at compile time, greatly reduce the occurence of unhandled exceptions surfacing at runtime in a given application at the expense of requiring large throws declarations and encouraging use of poorlyconstructed try/catch blocks. Checked exceptions are present in other languages like C++, C#, and Python.

 

A RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often

outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code unreadable and unmaintainable. The compiler allows runtime exceptions to go uncaught and unspecified. If you Java like, you can catch these exceptions just like other exceptions. However, you do not have to declare it in your “throws" clause or catch it in your catch clause. In addition, you can create your own RuntimeException subclasses and this approach is probably preferred at times because checked exceptions can complicate method signatures and can be difficult to follow.

 

 

Threads:

 

Q1:  What‘s the difference between the methods sleep() and wait()

A: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

 

Q2:  Describe synchronization in respect to multithreading.

A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. Without synchronization you may have race conditions.

 

 

 

SWING/AWT/GUI

 

Q1: What is the pattern that best expresses the relationship between AWT’s classes Component and Container?

 

1. Factory

2. Strategy

3. Composite

4. Decorator

5. Proxy

 

Answer :3 = true

Grading :10 points for correct answer

Difficulty : 4/10 A.

 

 

Logic Questions (Read these to them, don’t give them to read):

 

 

Q1. Basic Maths

 

a) Carefully add the following numbers in your head.

 

Take 1000 and add 40 to it. Now add another 1000. Now add 30. Add

another 1000. Now add 20. Now add another 1000

Now add 10. What is the total?

 

b) Calculate 19 * 17 in your head?

 

A 33. Basic Maths

 

a) If you got 5000 you are wrong, the correct answer is 4100.

b) 323.

 

Q2. Logic

 

Think carefully before giving your answer.

 

a) You are participating in a race. You overtake the second person.

What position are you in?

 

b) If you overtake the last person, then what position are you in?

 

A 34. Logic

 

a) If you answered that you are first, then you are wrong. If you overtake the second person and you take his place, so you are second.

 

b) If you answered that you are second to last, then you are wrong. It is impossible overtake the LAST Person, unless you count lapping them (in which case you will remain in the same position that you were before you lapped them).

 

Q3. Brain Twister logic.

 

(these are common Microsoft type questions, people may have seen them before).

 

a) A contractor is to be paid with a Gold bar. He is going to work 7 days and needs to be paid in full at the end of each day. You are allowed to cut the bar twice. Where would you cut it such that you can pay him 1/7th of the bar each day?

 

b) you have 25 horses and 1 race track on which 5 horses can race at a time. How many races do you need to find the 3 fastest horses.

 

a) cut it so you have a 1/7 piece, a 2/7ths piece, and a 4/7ths piece. Then day 1 you pay him with the 1/7th piece, day two you take it back and give him the 2/7ths piece, day three you give him the 1/7th piece. Etc.

 

b) if they get this question quickly they’ve seen it before. People should start with:

- have 5 races with 5 horses in each (so each horse has raced once at the end of the 5 races).

- the key piece to get is that the first finishers of the 5 races so far do not necessarily include the 3 fastest horses. The three fastest horses could be the top three finishers in any one of the races. But you do know that the fastest horse is one of the first place finishers.

 

- not optimal but obvious way of solving - One way to things out is to take top 3 finishers in each of the five races (15 horses), race them again (3 more races), take the top 3 finishers in each (9 horses), race them again (2 more races), and finally you’re done in 10 races.

 

- Optimal - instead after the first race - have the 5 first place finishers race in a 6th race, and from their positions you can determine what sets include candidates for the fastest 3. (say the first horse from the 3rd race finished 4th – you know that neither horse 4, nor any of the horses that ran in the 3rd race can be any of the 3 fastest).

- with the results from race 6 you’ll have 5 horses 3 of which are the fastest in the entire 25 horse set. Race them in a 7th race and you’re done.

Coding:

 

Write a function called fib, which give a parameter N returns the Nth number in the Fibonacci sequence (this is a weeder/easy question).

 

This is a 3 line function, the recursive version is much easier to write than the iterative. If they get bogged down with the iterative version ask them to do a recursive version. 

JI_3

标签:des   io   os   ar   java   for   sp   strong   on   

原文地址:http://www.cnblogs.com/chayu3/p/4060147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!