Good questions asked during Java interview

  1. Is “abc” a primitive value? - The String literal “abc” is not a primitive value. It is a String object.
  2. What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
  3. What modifiers may be used with an interface declaration? - An interface may be declared as public or abstract.
  4. Is a class a subclass of itself? - A class is a subclass of itself.
  5. What is the difference between a while statement and a do statement? - A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
  6. What modifiers can be used with a local inner class? - A local inner class may be final or abstract.
  7. What is the purpose of the File class? - The File class is used to create objects that provide access to the files and directories of a local file system.
  8. Can an exception be rethrown? - Yes, an exception can be rethrown.
  9. When does the compiler supply a default constructor for a class? - The compiler supplies a default constructor for a class if no other constructors are provided.
  10. If a method is declared as protected, where may the method be accessed? - A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
  11. Which non-Unicode letter characters may be used as the first character of an identifier? - The non-Unicode letter characters $ and _ may appear as the first character of an identifier
  12. What restrictions are placed on method overloading? - Two methods may not have the same name and argument list but different return types.
  13. What is casting? - There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
  14. What is the return type of a program’s main() method? - A program’s main() method has a void return type.
  15. What class of exceptions are generated by the Java run-time system? - The Java runtime system generates RuntimeException and Error exceptions.
  16. What class allows you to read objects directly from a stream? - The ObjectInputStream class supports the reading of objects from input streams.
  17. What is the difference between a field variable and a local variable? - A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
  18. How are this() and super() used with constructors? - this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
  19. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? - A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
  20. Why are the methods of the Math class static? - So they can be invoked as if they are a mathematical code library.
  21. What are the legal operands of the instanceof operator? - The left operand is an object reference or null value and the right operand is a class, interface, or array type.
  22. What an I/O filter? - An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
  23. If an object is garbage collected, can it become reachable again? - Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
  24. What are E and PI? - E is the base of the natural logarithm and PI is mathematical value pi.
  25. Are true and false keywords? - The values true and false are not keywords.
  26. What is the difference between the File and RandomAccessFile classes? - The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
  27. What happens when you add a double value to a String? - The result is a String object.
  28. What is your platform’s default character encoding? - If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
  29. Which package is always imported by default? - The java.lang package is always imported by default.
  30. What interface must an object implement before it can be written to a stream as an object? - An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
  31. How can my application get to know when a HttpSession is removed? - Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
  32. Whats the difference between notify() and notifyAll()? - notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
  33. Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? - The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
    However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.
  34. Why are there no global variables in Java? - Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
  35. What does it mean that a class or member is final? - A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
  36. What does it mean that a method or class is abstract? - An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
    	public abstract class Container extends Component {
    

    Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,

    	public abstract float price();
    

    Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

  37. What is a transient variable? - transient variable is a variable that may not be serialized.
  38. How are Observer and Observable used? - Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
  39. Can a lock be acquired on a class? - Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
  40. What state does a thread enter when it terminates its processing? - When a thread terminates its processing, it enters the dead state.
  41. How does Java handle integer overflows and underflows? - It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
  42. What is the difference between the >> and >>> operators? - The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
  43. Is sizeof a keyword? - The sizeof operator is not a keyword.
  44. Does garbage collection guarantee that a program will not run out of memory? - Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
  45. Can an object’s finalize() method be invoked while it is reachable? - An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
  46. What value does readLine() return when it has reached the end of a file? - The readLine() method returns null when it has reached the end of a file.
  47. Can a for statement loop indefinitely? - Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
  48. To what value is a variable of the String type automatically initialized? - The default value of an String type is null.
  49. What is a task’s priority and how is it used in scheduling? - A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
  50. What is the range of the short type? - The range of the short type is -(2^15) to 2^15 - 1.
  51. What is the purpose of garbage collection? - The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
  52. What do you understand by private, protected and public? - These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.
  53. What is Downcasting ? - Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
  54. Can a method be overloaded based on different return type but same argument type ? - No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
  55. What happens to a static var that is defined within a method of a class ? - Can’t do it. You’ll get a compilation error
  56. How many static init can you have ? - As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.
  57. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? - The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
  58. Describe what happens when an object is created in Java? - Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
  59. What does the “final” keyword mean in front of a variable? A method? A class? - FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
  60. What is the difference between instanceof and isInstance? - instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
  61. Why does it take so much time to access an Applet having Swing Components the first time? - Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.
This entry was posted in Java. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

45 Comments on Good questions asked during Java interview

  1. Arunakumar
    Posted 10/28/2004 at 10:12 am | Permalink

    Q>Which protocol is used in JNDI Mechansim?
    A> t3.

  2. java java
    Posted 10/29/2004 at 2:17 am | Permalink

    Here’s a tricky one that’s being asked lateley:

    What’s the difference between an abstract class and an interface?

    interface:
    A class may implement several interfaces.
    An interface cannot provide any code at all, much less default code.
    Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.
    An interface implementation may be added to any existing third party class.
    Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.
    You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the inteface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design.
    If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method.
    Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty.
    The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can’t call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so.
    If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.

    abstract class:
    A class may extend only one abstract class.
    An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
    Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
    A third party class must be rewritten to extend only from the abstract class.
    An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
    In a Java context, users should typically implement the Runnable interface rather than extending Thread, because they’re not really interested in providing some new Thread functionality, they normally just want some code to have the capability of running independently. They want to create something that can be run in a thread, not a new kind of thread.The similar is-a vs has-a debate comes up when you decide to inherit or delegate.

    You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad.
    If the various implementations are all of a kind and share a common status and behaviour, usually an abstract class works best.
    Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
    Fast
    You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
    If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

  3. Jean-Baptiste BRIAUD
    Posted 12/16/2004 at 9:43 am | Permalink

    Q: What are the differences between == and .equals() ?
    A: == compare rerefences and .equals should compare contents.
    Q: What would return “abc”==”abc” ?
    A: true, because of JVM optimisations.
    Q: What would return new String(”abc”)==new String(”abc”)
    A: return false because its 2 differents object.

  4. Mike Gershman
    Posted 3/14/2005 at 9:27 am | Permalink

    Java interview question 2 has the wrong answer.

    The answer given was:
    What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

    This is from JLS 14.10:
    Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

  5. Ebube O.
    Posted 4/5/2005 at 12:55 pm | Permalink

    The Answer to #12 is ambiguous (or wrong): Restrictions on overloading is in the argument list not return type. Two overloaded methods may have same/different return types but MUST have different arguments.

  6. Samrat
    Posted 4/7/2005 at 7:46 am | Permalink

    The answer for question4 is incorrect. The Class can’t be subclass of itself. It will result in ” “cyclic inheritence” error

  7. 6
    Posted 4/20/2005 at 8:12 am | Permalink

    Q: What are the differences between == and .equals() ?
    A: == compare rerefences and .equals should compare contents.

  8. Narendhar Reddy
    Posted 4/21/2005 at 3:07 pm | Permalink

    For 33rd question, A reasonable answer is “All the methods in Math class are static but not math class. we should call all static methods with class name as prefix, thats why we should write Math.abs()”…,

  9. ideanator
    Posted 4/25/2005 at 8:57 pm | Permalink

    33rd question: One more reason, becuae it’s a library of mathmatical funtions, by declaring them static they have class scope so when you use it you don’t have to create a instance of the Math class like
    Math obj = new Math();, you can dirctly use as Math.abs().

  10. Posted 6/12/2005 at 5:19 pm | Permalink

    what is a singleton class?

    The main purpose behind the class is simply to ensure that an application (or a web session, if you’re not a total purist) creates only one instance of a class. This is done in order to do things like control resources (only one factory class is needed per application) or to control business logic access (facades only need to have one instance per application as well). Preventing users from re-instantiating the class and doing unwanted things with it is a happy side effect of the pattern too.

  11. Avinaba Dhar
    Posted 7/15/2005 at 12:14 am | Permalink

    I am confused regarding Question number 4.Is a class really a subclass of itself or it will generate a cyclic inheritance error?

  12. pravin dubey
    Posted 7/21/2005 at 2:17 am | Permalink

    Talking about Q.4.
    a class can be subclass of itself if its inner class extend the outer class
    so the class is indirectly extending itself with out throwing any Exception
    thats different issue that there might be no use of doing this.

    rock rules

  13. Posted 7/28/2005 at 1:42 pm | Permalink

    Answer 4: is bugus, as is the question. Any interviewer asking it should be kicked in the shin -> or politely asked why on earth anyone would want to use this information. Comment 12 goes a long way, but think of private member variables to figure this one out. Though the answer is technically correct, there is no reason to even need to use this fact IMHO.
    Answer 35: when finalizing a member object, you are finalizing the *reference*, not the data contained in the member object. create a and feel free to modify the contents… Primitive data types are, of course, a different matter.
    Answer 36: abstract methods may also occur in interfaces
    Answer 54: in other words, the return type is not part of the method signature
    Answer 59: see answer 35. This is IMO based on the misconception that the java programming language can’t use pointers. This is, ofcourse, complete nonsense. For example, all objects are passed by reference in java…

    Use this information at your own risk. its only my opinion

  14. Posted 7/28/2005 at 1:53 pm | Permalink

    Whoops, egg on my face. I had the nagging suspicion that I had not considered all when stating that objects are passed by reference. Though the details can be ignored by the programmer, they need to be stated for the sake of correctness.

    Java is strictly pass by value. See http://javadude.com/articles/passbyvalue.htm for an explanation that is vastly superior to anything I can write!

    cheers

  15. Posted 8/15/2005 at 6:10 pm | Permalink

    Question 25 perplexes me. Last time I tried something like…

    boolean false = false;

    bad things happened… true and false are keywords — or at least boolean values/reserved words. What point are they trying to make?

  16. Pete
    Posted 10/24/2005 at 8:14 am | Permalink

    Question 33’s “little trick” is absolutely horrific. Don’t do that, people.

    Pete

  17. Vivian
    Posted 10/26/2005 at 12:49 am | Permalink

    In answer to response 15 regarding question 25 being confusing. false is not a keyword, it is a reserved word therefore it still cannot be used as names in programs.

  18. Kiran
    Posted 12/30/2005 at 2:35 pm | Permalink

    I think true and false are key words only.

  19. Posted 2/6/2006 at 3:06 pm | Permalink

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

    A. Use the following syntax: super.method1();
    Use super(); to call constructor in a superclass
    ( this should be the first line of the subclass’s constructor )

  20. Posted 3/19/2006 at 11:28 am | Permalink

    25) true and false are literal values for the boolean type also null is a literal value for type objects.

    33) First of all Math class is final that means you cannot subclass it and also the constructor of Math class is private so that noone can create the object of Math class.
    Both of these things make sence because Math class provides some basic mathemetical functionality which is universal for example squareroot of a number, value of 30 degrees cosine and so on… and these things should not be allowed to change that’s why the class is declared as final so that noone can extend it and try to change the implementation of these basic mathemetical methods.

    constructor is private means noone can create the oject of Math class. Math class is designed to work with the data that is not built into it.

  21. Ritesh Patkar
    Posted 3/24/2006 at 5:22 am | Permalink

    Java interview question 2 has the wrong answer.

    The answer given was:
    What restrictions are placed on the values of each case of a switch statement? - During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

    This is from JLS 14.10:
    Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

    Yes, it is true but then switch expression can only have values that can be promoted to int type

  22. Prafullkumar
    Posted 3/28/2006 at 10:17 am | Permalink

    FOR Q: 14
    if return type of main is void, how the system knows that program execute properly.

  23. Anjali
    Posted 10/17/2006 at 5:56 am | Permalink

    can a int value n a float value be compared???

  24. Posted 11/7/2006 at 12:27 pm | Permalink

    What is a transient variable?
    transient variable is a variable that may not be serialized

  25. Tarun Bansal
    Posted 12/25/2006 at 1:28 pm | Permalink

    True and False are reserved keywords.
    These are values defined by java.u cannot use these words for names ofvariables,classes etc.

  26. Prafullkumar
    Posted 1/19/2007 at 11:11 am | Permalink

    Can anybody tell me why int in java requires 4 bytes and int in other language requires 2 bytes only ?

  27. Ameen
    Posted 2/18/2007 at 7:36 am | Permalink

    How multiple inheritance is implemented in Java ?

  28. Janani
    Posted 2/19/2007 at 12:46 am | Permalink

    answer for difference between equals and == for string objects, the first one compares the content i.e string value of the string object and returns the value true if the comparisons are equal,
    and the == checks the memory value for the string objects and return true if they have the same memory location else returns false.

  29. Kulbir Singh
    Posted 2/26/2007 at 5:25 am | Permalink

    The answer for question4 is incorrect. The Class can’t be subclass of itself. It will result in ” “cyclic inheritence” error

  30. Krishn Gupta
    Posted 3/5/2007 at 1:10 am | Permalink

    == and equals() are same unless the class overrides the equals method appropriately to check the contents.The default implementation of equals() ie ref1.equals(ref2) method check whether the ref1 and ref2 points to the same object or not which is equivalent to ==.

  31. anil
    Posted 3/9/2007 at 2:02 am | Permalink

    Integer obj=new Integer();
    For above statement how much memory wil b allocated for object obj of type Integer(Wrapper class)…??
    Similarly what is memory allocated for Float,Double,Character…?

  32. Rekha
    Posted 3/16/2007 at 7:31 am | Permalink

    can the upper most class be protected or private?

    A: No, the upper most class should always be public..

  33. amit
    Posted 3/26/2007 at 2:17 pm | Permalink

    answer 12 is not wrong

  34. anil
    Posted 3/28/2007 at 1:17 am | Permalink

    1. wat is the difference between interface and absract class in java…??
    2. how applets are executed without writing main function…??

  35. Kumarvijay
    Posted 4/12/2007 at 2:07 am | Permalink

    FOR JNDI(Java Netive directory Interface) LDAP(Light weight Directory Access Protocal ) is used..

  36. Kumarvijay
    Posted 4/12/2007 at 2:12 am | Permalink

    In java multiple inheritance is achieved through Interface……..By extending a class and imlementing a interface or by implementing more than one interface.

  37. nakul
    Posted 5/10/2007 at 12:16 am | Permalink

    i think the answer 12 is like this
    in overloading a method two methods must have the diff arguments
    they may have the diff return type ,or acess modifier(not necessary that they should have the sane return type or acess modifier)also the
    the overloading method can throw the exceptions higher the the overloaded method

  38. SURESH
    Posted 5/30/2007 at 5:23 am | Permalink

    1.What is the difference between string and string buffer with examples?

    2.What is the difference between Abstract class and interface with examples?

  39. vaishali dighe
    Posted 7/13/2007 at 5:53 am | Permalink

    2.What is the difference between Abstract class and interface with examples?

    abstract contain only declarations of methods but not the definations,it may contain other methods with definations.class contaning abstract methods i.e.
    which are only declared but not defined are to be written with prefix of ‘abstract’.

    implementation of abstract method will be in class extending abstract class.

    on the other hand,interface contain only abstract classes and final variable.

    methods in interface will be defined by class implementing interface.

    example of abstract class:

    abstract class hello
    {
    public void a()
    public show()
    {
    System.out.println("hello how r u");
    }
    }

    class bye extends hello
    {
    public a()
    {
    System.out.println("defined in class extending abstract class");
    }
    }

    class M
    {
    public static void main(String args[])
    {
    Bye by=new Bye()
    {
    by.a()
    by.show()
    }
    }

    example of interface:-
    ———————–
    interface nameofinterface
    {
    int a=10;
    public void show()
    }
    class I implements nameofinterface
    {
    public void show()
    {
    System.out.println(a)
    }
    }
    class N {
    public static void main(string arg[])
    {
    I i=new I();
    i.show();
    }
    }

  40. vaishali dighe
    Posted 7/13/2007 at 5:59 am | Permalink

    2. how applets are executed without writing main function…??

    using appletviewer or web browser.

    1>using appletviewer:
    we will pass name of class implementing applet to appletviewer
    syntax:- appletviewer classname
    we will write in our program coding as
    after class declaration
    public class h extends applet
    {

    2>using web browser:
    we will make html file in which we will write code as

  41. Rahul K
    Posted 10/13/2007 at 8:46 am | Permalink

    What is MultiThreading in Java?

    What is purpose of implementing EJB in Java?

  42. Posted 3/13/2008 at 1:53 pm | Permalink

    These are good questions and answers, here is my take…

    > What restrictions are placed on the values of each case of a switch statement?
    Enum constants are allowed although you cannot cast these to int.

    > Is a class a subclass of itself?
    A class cannot extend itself however
        new Integer(1) instanceof Integer
    is true.
    BTW: The super class of Object.class.getSuperclass() is null. So is MyInterface.class.getSuperclass() and int.class.getSuperclass()

    > What restrictions are placed on method overloading?
    Two methods with different generics cannot overload each other
    e.g. This is not allowed
    void print(List<String> strings);
    void print(List<Double> doubles);

    > What is casting?
    You could add a comment about auto-boxing

    > What is the return type of a program’s main() method?
    main throws an Exception/Error to report  a failure.

    > What class of exceptions are generated by the Java run-time system?
    The rt.jar and native methods can trigger checked exceptions as well.

    > What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
    A method can declare a super class of any Exception thrown in the method.
    e.g.
    public static void main(String… args) throws Exception { …

    > What are the legal operands of the instanceof operator?
    Enum types are also allowed.
    For instanceof an annotation it loses the @
    e.g. object instanceof Annotation
    not
    object instanceof @Annotation

    > If an object is garbage collected, can it become reachable again?
    The GC only collects unreachable objects.

    > Are true and false keywords?
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
    States "true, false, and null might seem like keywords, but they are actually literals"

    > Which package is always imported by default?
    The current package and java.lang

    > Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()?
    You can import these with a static import.

    import static java.lang.Math.*;

    Then you can uses abs() and sin() without a class qualifier.

    > Why are there no global variables in Java?
    It could be argued that "public static" variables are globally accessible, this breaks the OO model and should be kept to a minimum!

    > What does it mean that a class or member is final?
    Note: a final field only means the reference cannot change, however the contents can change.
    e.g.
    final Set<String> strings = new HashSet<String>();
    strings.add("hello");

    > What does it mean that a method or class is abstract?
    Note: This means that public constructors on an abstract class are actually protected.  They can only be called by a subclass.

    > What is a transient variable?
    A transient variable is not automatically serialised using the default behaviour in ObjectOutputStream. However, you can serialise the contents of the field using custom code, or a custom serialiser could ignore this modifier.

    > Can a lock be acquired on a class?
    static synchronized methods acquire a lock on the class not the object.
    This means if every method is synchronized you can have two threads in different methods for a class. i.e. a static and a non-static one.

    > What state does a thread enter when it terminates its processing?
    Technically, isAlive() = false and getState() == State.TERMINATED. There is no "dead" state.

    > Can an object’s finalize() method be invoked while it is reachable?
    If you call finalize() of a reachable object from the finalize() of an unreachable object this will cause the GC to call the first one. (But this won’t cause it to be collected)

    > Can a method be overloaded based on different return type but same argument type ?
    In Java 5, yes.

    > Describe what happens when an object is created in Java?
    You could comment that the class is loaded first, then its static block….

    > An interface cannot provide any code at all, much less default code.
    However an inner class of an interface can have code, and helper methods for the interface etc.
    Constants defined in the interface can call static methods (in say the inner class)

    public interface A {
        public static final long NUM = B.NUM;
        static class B {
            public static final long NUM = System.currentTimeMillis();
            static {
                System.out.println("hello World");
            }
        }
    }
    If you print A.NUM, it will print "hello World" first.

    > What would return “abc” == ”abc” ?
    See String.intern() for more details on how this is done.

    > Q. How can a subclass call a method or a constructor defined in a superclass ?
    > A. Use the following syntax: super.method1();
    > Use super(); to call constructor in a superclass
    super(); calls the constructor in the immediate superclass.  You cannot call a constructor in higher super classes.

    > the constructor of Math class is private so that noone can create the object of Math class.
    Except by using reflection, but you shouldn’t want to. :)

    > can a int value n a float value be compared
    yes.

    > True and False are reserved keywords.

    true and false are literals, not reserved or keywords.  True and False are not the same as true and false.

    > Can anybody tell me why int in java requires 4 bytes and int in other language requires 2 bytes only ?
    ‘int’ requires 2-bytes on C/C++ system which were designed for 16-bit computing.  Welcome to the age of the 32-bit processing, or is that 64-bit?

    > How multiple inheritance is implemented in Java ?
    You can use delegation instead.

    > Integer obj=new Integer(); For above statement how much memory wil b allocated for object obj of type Integer(Wrapper class)…

    It won’t compile. However an Integer object uses about 24 bytes of memory.

    > can the upper most class be protected or private?
    > A: No, the upper most class should always be public..

    It should be public, protected or package local but doesn’t have to be.
    public class A {
        private class B {
            public class C extends B {
            }
        }
    }
    Class A cannot be private as it has the same name as the file.

    > What is MultiThreading in Java?
    programming using multiple threads.

  43. ashok
    Posted 7/11/2008 at 1:20 am | Permalink

    Can a method be overloaded based on different return type but same argument type ?
    In Java 5, yes.

    this answer is wrong,in overloading method arguments must be different,and return type may be same or not.
    if we give same arguments in overloaded methods compiler does not know which method it has to call.

  44. Shabeer
    Posted 9/9/2008 at 4:50 am | Permalink

    Answer for 12 question
    Two methods may not have the same name and argument list but different return types.
    Is correct as they are explaining the restrictions of method overloading.

  45. vinay
    Posted 10/10/2008 at 10:24 am | Permalink

    How Applet works with out main?
    ans:
    applet works in a browser ,browser or internet explorer provides thread like jvm provides main thread ,the thread provides by the browser was said to be Green thread ,which takes care of execution of applet.

    What is the difference between Abstract and Interface?
    ans:
    We can say simply the difference between abstract and interface are

    abstract class does not extends multiple inheritance where as interface can and
    in interface all the methods are to be declared as abstract i.e we should not give implemnetation for any method ,where as in abstract class some of the methods may be abstract or can be implemented.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*