Popular Posts

Monday, July 4, 2011

Java FAQ's-II


System.out.println() : 
                Let’s break this down, starting with the dot operator. In Java, the dot operator can only be used to call methods and variables so we know that ‘out’ must be either a method or a variable. Now, how do we categorize ‘out’? Since println() is clearly a method, and its called using ‘out’, then we know that ‘out’ can not possibly be a method because it doesn’t make sense to have one method invoke another method with the dot operator in Java. This means ‘out’ must be a variable.
We now know that ‘out’ is a variable, so we must now ask ourselves what kind of variable is it? There are two possibilities – it could be a static or an instance variable. Because ‘out’ is being called with the ‘System’ class name itself, and not an instance of a class (an object), then we know that ‘out’ must be a static variable, since only static variables can be called with just the class name itself. So now we know that ‘out’ is a static member variable belonging to the System class.
Noticing the fact that ‘println()’ is clearly a method, we can further classify ‘out’. We have already reasoned that ‘out’ is a static variable belonging to the class System. But now we can see that ‘out’ must be an instance of a class, because it is invoking the method ‘println()’.
The thought process that one should use to arrive at an answer is purposely illustrated above. Without knowing the exact answer beforehand, you can arrive at an approximate one by applying some basic knowledge of Java. Most interviewers wouldn’t expect you to know how System.out.println() works off the top of your head, but would rather see you use your basic Java knowledge to arrive at an answer that’s close to exact.
The more exact answer is this: inside the System class is the declaration of ‘out’ that looks like: ‘public static final PrintStream out’, and inside the Prinstream class is a declaration of ‘println()’ that has a method signature that looks like: ‘public void println()’.


What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.


JVM and Byte code :
JVM translates bytecode into machine language:
Every Java program is compiled into an intermediate language called Java bytecode. The JVM is used to both translate the bytecode into the machine language for a particular computer, and actually execute the corresponding machine-language instructions as well. The JVM and bytecode combined give Java its status as a "portable" language.
Machine language is OS dependent :
Given the previous information, it should be easier to deduce an answer to the question. Since the JVM must translate the bytecode into machine language, and since the machine language depends on the operating system being used, it is clear that the JVM is platform (operating system) dependent. This fact can be verified by trying to download the JVM – you will be given a list of JVM’s corresponding to different operating systems, and you will obviously pick whichever JVM is targeted for the operating system that you are running.



Class and Object : 
 The term ‘class’ refers to the actual written piece of code in which the class is defined. The properties of a class do not change before, during, or after the execution of a program.
                  The term ‘object’, however refers to an actual instance of a class. Every object must belong to a class. Objects are created and eventually destroyed – so they only live in the program for a limited time. While objects are ‘living’ their properties may also be changed signficantly.
           Suppose we have a class called ‘Animal’. Animals have legs, bodies, and brains. This general concept of an Animal does not change.
An instance of the Animal class would be a specific animal – like a lion, a cat, or a zebra. These instances of the Animal class would be objects. Whereas the Animal class is a general concept, the instances of that class – the lions, cats, etc – take that general concept and create a real instance of it.Every object has a lifespan associated with it – a cat or zebra can not live forever. And, the properties of those objects can change as well while they ‘live’; if we have a ‘size’ variable defined in the class that would of course change as the cat object grows bigger.
          So we can say that whereas a class is a general concept (like an Animal), an object is a very specific embodiment of that class, with a limited lifespan (like a lion, cat, or a zebra).



Serialization : 
       A class is serializable when it implements the Serializable interface, which is an interface residing in the java.io package. If a class is serializable, it means that any object of that class can be converted into a sequence of bits so that it can be written to some storage medium (like a file), or even transmitted across a network. Here’s what a serializable class looks like:

public class SomeClass implements java.io.Serializable
{
// this class is serializable
...
}
Suppose that there’s a particular object data member (like a password) that we may not want to get saved when an object is serialized. Then, what we can do is declare that data member to be "transient". A transient variable is not a part of the persistent state of a serialized object. Here’s what a transient variable looks like:
public class SomeClass implements java.io.Serializable
{
      // this variable will not persist
private transient String password;
    ...
}
So, if we were to write a serializable object to a file, any transient variable that was part of that object will not be saved to the file.

Polymorphism :

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. This is the third basic principle of object oriented programming. Overloading, overriding and dynamic method binding are three types of polymorphism.

Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. For example 'spinning' a number may mean increase it, 'spinning' an image may mean rotate it by 90 degrees. By defining a method for handling each type of parameter you control the desired effect.

Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.

Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at runtime. As an example assume that three subclasses (Cow, Dog and Snake) have been created based on the Animal abstract class, each having their own speak() method. Although each method reference is to an Animal (but no animal objects exist), the program is will resolve the correct method reference at runtime.

Dynamic binding :
        Given classes A, B, and C where B extends A and C extends B and where all classes implement the instance method void doIt(). A reference variable is instantiated as "A x = new B();" and then x.doIt() is executed. What version of the doIt() method is actually executed and why?
         The version of the doIt() method that’s executed is the one in the B class because of dynamic binding. Dynamic binding basically means that the method implementation that is actually called is determined at run-time, not at compile-time. Hence the term dynamic binding.
               Although x is of type A, because it references an object of class B, the version of the doIt() method that will be called is the one that exists in B.
public class AnimalReference
{
public static void main(String args[])
Animal ref // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Ernie");

// now reference each as an Animal
ref = aCow; ref.speak();
ref = aDog; ref.speak();
ref = aSnake; ref.speak();
}


Can constructors be synchronized in Java?
         No, constructors can not be synchronized in Java. In fact using the keyword “synchronized” with a constructor is actually a syntax error. Remember that the “synchronized” keyword is used to prevent 2 or more threads from accessing a group of methods before one thread finishes execution in those methods.
Does synchronizing a constructor make sense?
       Synchronizing a constructor does not make sense simply because only one thread needs to have access to a constructor. Only the thread that creates an object needs to have access to it while it is being constructed. In other words, there is no need to switch out of the constructor to another thread. Also, when the constructor is called, the object does not even exist yet.



Can an interface extend another interface in Java?
Yes, an interface can extend another interface in Java. This is what the code for something like that would look like:

// this interface extends from the Body interface:
public interface FourLegs extends Body//cannot implement
{
  public void walkWithFourLegs( );

}
When would we want an interface to extend another interface?
           Remember that any class that implements an interface must implement the method headings that are declared in that interface. And, if that interface extends from other interfaces, then the implementing class must also implement the methods in the interfaces that are being extended or derived from. So, in the example above, if we have a class that implements the FourLegs interface, then that class must have definitions for any method headings in both the FourLegs interface and the Body interface.


Java Pass by Value : Java passes by value, and not by reference. What is the difference between the two? When passing arguments to a method, Java will create a copy of the original variable and pass that to the method as an argument. This means that the method will not receive the original variable – but just a copy of it.If we pass an object,it will pass the address as it's value.


Java cloning,Shallow copy and deep copy : 
http://www.java-questions.com/Cloning_interview_questions.html




Java Generics : 
There are three types of wildcards:
  • "? extends Type": Denotes a family of subtypes of type Type. This is the most useful wildcard
  • "? super Type": Denotes a family of supertypes of type Type
  • "?": Denotes the set of all types or any



Threads and Thread Groups : http://nadeausoftware.com/articles/2008/04/java_tip_how_list_and_find_threads_and_thread_groups

No comments:

Post a Comment