首页 > 代码库 > JI_3

JI_3

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‘sconstructor

 

Q5: Which of thefollowing statements concerning the Virtual Machine are true and which arefalse?

 

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

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

3. The VirtualMachine does not differentiate between an instance method and a constructormethod.                   F

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

5. The VM keeps aprogram 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 differentClassloaders can they communicate?

 

1.When the invoker object access the other object through an interface that hasbeen 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 upon Q6 in case they got it right).

 

A: Class loaders arehierarchical. Classes are introduced into the JVM as they are referenced byname in a class that is already running in the JVM. So how is the very firstclass loaded? The very first class is specially loaded with the help of staticmain() method declared in your class. All the subsequently loaded classes areloaded by the classes, which are already loaded and running. A class loadercreates a namespace. All JVMs include at least one class loader that isembedded within the JVM called the primordial (or bootstrap) class loader. Nowlet’s look at

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

 

CLASSLOADER         reloadable?               Explanation

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

 

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

 

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

 

 

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

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

loader will have its ownsingleton.

 

Q9.  Which of the following are valid ways ofmaking 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 anobject for a class in Java (follow up on Q8)?

 

A:There arefour ways in which we can create an object for a class in java, the only notmentioned in Q6 is cloning and through object deserialization (extra points ifthey 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

Testx=new Test();

Testt=x.clone();

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

 

Q11: How does the Object.clonemethod work. What is the main difference between shallow cloning and deepcloning of objects?

 

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

 

Shallow copy: If a shallow copy is performed on obj-1 as shown in fig-2 then it iscopied but its contained objects are not. The contained objects Obj-1 and Obj-2are affected by changes to cloned Obj-2. Java supports shallow cloning ofobjects 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 onlyobj-1 has been copied but the objects contained within it have been copied aswell. Serialization can be used to achieve deep cloning. Deep cloning throughserialization is faster to develop and easier to maintain but carries aperformance overhead.

 

For example, invoking clone() method on a HashMap returns a shallow copyof 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 aByteArrayOutputSream and then deserialize it. This creates a deep copy but doesrequire that all keys and values in the HashMap are Serializable. Its primaryadvantage 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 aredeclared static and don’t have function name (ie static initializers) areexecuted even before the constructors are executed. As the name suggests theyare typically used to initialize static fields.

 

public class StaticInitilaizer

{

public staticfinal int A = 5;

public staticfinal int B;

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

static

{

if(A == 5)

B = 10;

else

B = 5;

}

public StaticInitilaizer()

{} // constructor is called only after staticinitializer block

}

 

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

public class Test

{

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

}

 

Q13: What is thedifference between an abstract class and an interface and when should you usethem?

 

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

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

 

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

 

Abstract Classes:

Haveexecutable methods and abstract methods.

Can onlysubclass one abstract class.

Can haveinstance variables, constructors and any

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

 

Interfaces:

Have noimplementation code. All methods are abstract.

A classcan implement any number of interfaces.

Cannothave instance variables, constructors and can have

onlypublic and none (aka package) visibility.

 

When to use an abstract class?: In casewhere you want to use implementation inheritance then it isusually provided by an abstract base class. Abstract classes are excellentcandidates inside of application frameworks. Abstract classes let you definesome 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 isa method said to be overridden?

 

Difficulty: veryeasy:

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

 

class MyClass

{

public void getInvestAmount(int rate) {…}

public void getInvestAmount(int rate, longprincipal)

{ … }

}

 

Both the abovemethods have the same method names but different method signatures, which meanthe methods are overloaded.

 

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

class BaseClass

{

public void getInvestAmount(int rate) {…}

}

 

class MyClassextends BaseClass

{

public void getInvestAmount(int rate) { …}

}

 

Both the abovemethods have the same method names and the signatures but the method in thesubclass MyClass overrides the method in the superclass BaseClass.

 

Overloading letsyou define the same operation in different ways for different data.

 

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

A: The interfaces with no defined methods act likemarkers. They just tell the compiler that the objects of the classesimplementing the interfaces with no defined methods need to be treateddifferently.

 

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

 

A: Other languages use pass-by-reference or pass-by-pointer. But in Javano matter what type of argument you pass the corresponding parameter (primitivevariable or object reference) will get a copy of that data, which is exactlyhow pass-by-value (ie copy-by-value) works. In Java, if a calling method passesa reference of an object as an argument to the called method then the passed inreference gets copied first and then passed to the called method. Both theoriginal reference that was passed-in and the copied reference will be pointingto the same object. So no matter which reference you use, you will be alwaysmodifying the same original object, which is how the pass-by-reference works aswell.

 

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

 

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

 

void Method1(boolparam1)

{

          Method2(param1, false);

}

void Method2(boolparam1, bool param2optional)

{

          Method3(param1, param2optional,false); 

}       

void Method3(boolparam1, bool param2optional, bool param3optional)

{

          // blah blah blah;     

}       

 

 

 

Q18: What is the difference between an instance variable and astatic 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 perclass loader.

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

Instancevariables are non-static and there is oneoccurrence 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 ofutility 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: Privateconstructor 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’dmight 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 andfinalize() in Java?

 

Difficulty: easy

Answer:

 

  final - constant declaration. Refer Q27in Java section.

  finally- handles exception. The finally block is optional and provides a mechanism toclean 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 systemresources like database connections, statements etc.

  finalize()- method helps in garbage collection. A method that is invoked before an objectis 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 resourcesand you do not know when the garbage collection is going to kick in to releasethese non-memory resources through the finalize() method.

 

 

Q23: Explain Outerand Inner classes (or Nested classes) in Java? When will you use an InnerClass?

 

A: In Java not all classes have to be defined separatefrom each other. You can put the definition of one class inside the definitionof another class. The inside class is called an inner class and the enclosingclass is called an outer class. So when you define an inner class, it is amember of the outer class in much the same way as other members likeattributes, methods and constructors.

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

in the outer classfor 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 aninner class is only relevant in the context of the outer class and/or innerclass can be made private so that only outer class can access it. Inner classesare used primarily to implement helper classes like Iterators, Comparators etcwhich are used in the context of an outer class

 

JAVA VM/Performance:

 

Q1: Which of the following statements concerning the VirtualMachine 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 8registers, each one has the length of one word. F

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

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

5. The VM keeps a program counter forevery 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 thefollowing statements concerning performance are true and which are false?

 

1. Methods calledthrough an interface reference are slower than those called through abstractmethods because they can never be pointed directly by fields in the class poolof the caller T

2. The invocation ofan interface method is slower than Instantiation F

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

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

5. Polymorphic callsare 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 intothe 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 aclass). In Java methods local variables are pushed into stack when a method isinvoked and stack pointer is decremented when a method call is completed. In amulti-threaded application each thread will have its own stack but will sharethe same heap. This is why care should be taken in your code to avoid anyconcurrent access issues in the heap space. The stack is threadsafe (eachthread will have its own stack) but the heap is not threadsafe unless guardedwith synchronisation through your code.

 

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

A function is recursive (easy – must know this) if it calls itself. Given enough stack space, recursive method calls areperfectly valid in Java though it is tough to debug. Recursive functions areuseful in removing iterations from many sorts of algorithms. All recursivefunctions 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 callsto the same method with the same arguments yield same results. For exampleclustered EJBs, which are written with idempotent methods, can automaticallyrecover 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 garbagecollection occur? Explain different types of references in Java?

 

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

 

What is an unreachable object? An object’s lifehas no meaning unless something has reference to it. If you can’t reach it thenyou can’t ask it to do anything. Then the object becomes unreachable and thegarbage collector will figure it out. Java automatically collects all theunreachable objects periodically and releases the memory consumed by thoseunreachable 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 defaultimplementation of equals compares the memory of the objects.

 

Q2: What is the main difference between aString 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.

 

//Inefficientversion using immutable String

Stringoutput = “Some text”

Intcount = 100;

for(intI =0; i<count; i++)

{

output+= i;

}

returnoutput;

 

The above code wouldbuild 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 inall respects to StringBuffer except that it is notsynchronised, which makes it slightly faster at the cost of not beingthread-safe.

 

//More efficient version using mutable StringBuffer

StringBuffer output =new StringBuffer(110);

Output.append(“Sometext”);

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

{

output.append(i);

}

returnoutput.toString();

 

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

 

** Extra Points ifthey mention something about this: Another important point is that creation ofextra strings is not limited to ‘overloaded mathematical operators’ (“+”) butthere are several methods like conact(),trim(), substring(), andreplace() in String classes thatgenerate new string instances. So use StringBuffer or StringBuilder forcomputation intensive operations, which offer better performance.

 

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

 

Vector / Hashtable

Original classesbefore the introduction of Collections API.

Vector &Hashtable are synchronized.

Any method thattouches their contents is thread-safe.

 

ArrayList / Hashmap

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

 

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

 

MapmyMap = Collections.synchronizedMap (myMap);

ListmyList = Collections.synchronizedList (myList);

 

Java arrays areeven faster than using an ArrayList/Vector and perhaps therefore may bepreferable. ArrayList/Vector internally uses an array with some convenientmethods like add(..), remove(…) etc

 

Q4: Explain the Java Collection framework?

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

 

A Set is a collection with uniqueelements and prevents duplication within the collection. HashSet and TreeSet areimplementations of a Set interface. A List is a collection with an orderedsequence of elements and may contain duplicates. ArrayList, LinkedList andVector are implementations of a List interface.

 

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

 

How to implement collection ordering? SortedSet andSortedMap interfaces maintain sorted order. The classes, which implement theComparable interface, impose natural order. For classes that don’t implement comparableinterface, or when one needs even more control over ordering based on multipleattributes, a

Comparator interface should be used.

 

Design pattern: Whatis an Iterator?

An Iterator is ause once object to access the objects stored in a collection. Iterator designpattern (aka Cursor) is used, which is a behavioral design pattern thatprovides a way to access elements of a collection sequentially without exposingits internal representation.

 

Exception Handling:

 

Q1:

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

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

 

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

A :

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

 

Exceptions: Most programsthrow and catch objects that derive from the Exception class. Exceptionsindicate that a problem occurred but that the problem is not a serious JVMproblem. An Exception class has many subclasses. These descendants indicatevarious types of exceptions that can occur. For example, NegativeArraySizeExceptionindicates that a program attempted to create an array with a negative size. Oneexception subclass has special meaning in the Java language: RuntimeException.All the exceptions except RuntimeException are compiler checked exceptions. Ifa method is capable of throwing a checked exception it must declare it in itsmethod header or handle it in a try/catch block. Failure to do so raises acompiler error. So checked exceptions can, at compile time, greatly reduce theoccurence of unhandled exceptions surfacing at runtime in a given application atthe expense of requiring large throws declarations and encouraging use ofpoorlyconstructed try/catch blocks. Checked exceptions are present in otherlanguages like C++, C#, and Python.

 

ARuntimeException class represents exceptions that occur within the Java virtualmachine (during runtime). An example of a runtime exception isNullPointerException. The cost of checking for the runtime exception often

outweighsthe benefit of catching it. Attempting to catch or specify all of them all thetime would make your code unreadable and unmaintainable. The compiler allowsruntime exceptions to go uncaught and unspecified. If you Java like, you cancatch these exceptions just like other exceptions. However, you do not have todeclare it in your “throws" clause or catch it in your catch clause. Inaddition, you can create your own RuntimeException subclasses and this approachis probably preferred at times because checked exceptions can complicate methodsignatures and can be difficult to follow.

 

 

Threads:

 

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

A:The codesleep(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 itreceives the notify() or notifyAll() call. The method wait() is defined in theclass Object and the method sleep() is defined in the class Thread.

 

Q2: Describe synchronization in respect tomultithreading.

A:With respectto multithreading, synchronization is the capability to control the access ofmultiple threads to shared resources. Without synchronization, it is possiblefor one thread to modify a shared variable while another thread is in theprocess of using or updating same shared variable. This usually leads tosignificant errors. Without synchronization you may have race conditions.

 

 

 

SWING/AWT/GUI

 

Q1: What is thepattern that best expresses the relationship between AWT’s classes Componentand 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 another1000. Now add 30. Add

another1000. Now add 20. Now add another 1000

Nowadd 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.

Whatposition 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, thenyou are wrong. If you overtake the second person and you take his place, so youare second.

 

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

 

Q3. Brain Twisterlogic.

 

(theseare 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 andneeds to be paid in full at the end of each day. You are allowed to cut the bartwice. Where would you cut it such that you can pay him 1/7th of thebar each day?

 

b)you have 25 horses and 1 race track on which 5 horses can race at a time. Howmany 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/7thspiece. Then day 1 you pay him with the 1/7th piece, day two you takeit back and give him the 2/7ths piece, day three you give him the 1/7thpiece. Etc.

 

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

-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 notnecessarily include the 3 fastest horses. The three fastest horses could be thetop three finishers in any one of the races. But you do know that the fastest horse is one of the first placefinishers.

 

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

 

-Optimal - instead after the firstrace - have the 5 first place finishers race in a 6th race, and fromtheir positions you can determine what sets include candidates for the fastest3. (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 3rdrace can be any of the 3 fastest).

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

Coding:

 

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

 

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

JI_3