Clouds
Home

Core Java

Java Fundamentals 1

Java Fundamentals 2

Java Fundamentals 3

Java Swing

Java Applet

Java Memory & Performance

Core Java Fundamentals Interview Questions


Advantage of using Java?

Java is a fun language. Some of the reasons to use it are:
  • Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
  • Object Oriented (OO).
  • Better portability than other languages across operating systems.
  • Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI, EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardized APIs (Application Programming Interfaces).

    What is the main difference between the Java platform and the other software platforms?

    Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.
    The Java platform has 2 components:
  • Java Virtual Machine (JVM) - 'JVM' is a software that can be ported onto various hardware platforms. Byte codes are the machine language of the JVM.
  • Java Application Programming Interface (Java API) - set of classes written using the Java language and run on the JVM.

    What are the differences between C++ and Java?

    Both C++ and Java use similar syntax and are Object Oriented, but:
  • Java does not support pointers. Pointers are inherently tricky to use and troublesome.
  • Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.
  • Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized. Avoid using finalize() method to release nonmemory 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 resources through the finalize() method.
  • Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework
  • All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions.
  • C++ requires explicit memory management, while Java includes automatic garbage collection.

    What are the usages of Java packages?

    It helps resolve naming conflicts when different packages have classes with the same names. This also helps us organize files within project. For example: java.io package do something related to I/O and java.net package do something to do with network and so on. If we tend to put all .java files into a single package, as the project gets bigger, then it would become a nightmare to manage all the files. We can create a package as follows with package keyword, which is the first keyword in any Java program followed by import statements. The java.lang package is imported implicitly by default and all the other packages must be explicitly imported.

    package com.xyz.client ;
    import java.io.File;
    import java.net.URL;

    Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?

    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 especially 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.
    • Bootstrap (primordial) - Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar)
    • Extensions - Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property usually lib/ext directory of the JRE)
    • System - 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.

    What do you need to do to run a class with a main() method in a package?

    If we have a class named Animal in a project folder D:\Project and package named com.xyz.client, will you be able to compile and run it as it is? package com.xyz.client; public class Animal {
      public static void main(String[] args) {
        System.out.println("We found the classpath");
      }
    }


    To run D:\Project> java com.xyz.client.Animal
    The answer is no and you will get the following exception:
    Exception in thread "main" java.lang.- NoClassDefFoundError: com/xyz/client/Animal. You need to set the classpath. How can you do that? One of the following ways:
  • Set the operating system CLASSPATH environment variable to have the project folder D:\Project.
  • Set the operating system CLASSPATH environment variable to have a jar file D:/Project/client.jar, which has the Animal.class file in it.
  • Run it with cp or classpath option as shown below:
    D:\>java cp D:/Project com.xyz.client.Animal
    OR
    D:\>java -classpath D:/Project/client.jar com.xyz.client.Animal
    Note: 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.

    What is the difference between constructors and other regular methods? What happens if you do not provide a constructor? Can you call one constructor from another? How do you call the superclass’s constructor?

    Constructors Regular methods: Constructors must have the same name as the class name and cannot return a value. The constructors are called only once per creation of an object while regular methods can be called many times.
    e.g. for a Pet.class
    public Pet() {} // constructor
    Regular Methods: Regular methods can have any name and can be called any number of times.
    e.g. for a Pet.class.
    public void Pet(){} // regular method has a void return type.
    Note: method name is shown starting with an uppercase to differentiate a constructor from a regular method. Better naming convention is to have a meaningful name starting with a lowercase like:
    public void createPet(){} // regular method has a void return type
  • What happens if you do not provide a constructor? Java does not actually require an explicit constructor in the class description. If you do not include a constructor, the Java compiler will create a default constructor in the byte code with an empty argument. This default constructor is equivalent to the explicit “Pet(){}”. If a class includes one or more explicit constructors like
    public Pet(int id) or Pet(){} etc, the java compiler does not create the default constructor Pet(){}.
  • Can you call one constructor from another? Yes, by using this()
    syntax. e.g.
    public Pet(int id) {
      this.id = id; // this means this object
    }
    public Pet (int id, String type) {
      this(id); // calls constructor public Pet(int id)
      this.type = type; // this means this object
    }
  • How to call the superclass constructor? If a class called "SpecialPet" extends your "Pet" class then you can use the keyword "super" to invoke the superclass’s constructor. e.g.
    public SpecialPet(int id) {
      super(id); //must be the very first statement in the constructor.
    }

    To call a regular method in the super class use: super.myMethod( );. This can be called at any line. Some frameworks based on JUnit add their own initialization code, and not only do they need to remember to invoke their parent's setup() method, you, as a user, need to remember to invoke theirs after you wrote your initialization code:
    public class DBUnitTestCase extends TestCase {
    public void setUp() {
      super.setUp(); // do my own initialization }
    } public void cleanUp() throws Throwable {
      try {
        // Do stuff here to clean up your object(s).
      }
      catch (Throwable t) {}
      finally{
        super.cleanUp(); //clean up your parent class. Unlike constructors
        // super.regularMethod() can be called at any line.
      }
    }

    What are the advantages of Object Oriented Programming Languages (OOPL)? How does the Object Oriented approach improve software development?

    The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, Customer etc. The features of the OO programming languages like polymorphism, inheritance and encapsulation make it powerful.
    The key benefits are:
  • Re-use of previous work: using implementation inheritance and object composition.
  • Real mapping to the problem domain: Objects map to real world and represent vehicles, customers, products etc: with encapsulation.
  • Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.
  • The increased quality and reduced development time are the by-products of the key benefits discussed above. If 90% of the new application consists of proven existing components then only the remaining 10% of the code have to be tested from scratch.

    How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between composition and aggregation?

    The "is a" relationship is expressed with inheritance and "has a" relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
    Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.
    Which one to favor, composition or inheritance? The guide is that inheritance should be only used when subclass "is a" superclass.
    • Don't use inheritance just to get code reuse. If there is no "is a" relationship then use composition for code reuse. Overuse of implementation inheritance (uses the "extends" key word) can break all the subclasses, if the superclass is modified.
    • Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse
    What is the difference between aggregation and composition?
    Aggregation : Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole.For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship. Composition : Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. For example An order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship.

    What do you mean by polymorphism, inheritance, encapsulation, and dynamic binding?

    Polymorphism means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code that uses the polymorphic classes or interfaces. When you send a message to an object even though you don't know what specific type it is, and the right thing happens, that's called polymorphism. The process used by object-oriented programming languages to implement polymorphism is called dynamic binding.

    Inheritance is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of refactoring process to improve maintainability of your code by avoiding code duplication. The existing class is called the superclass and the derived class is called the subclass. Inheritance can also be defined as the process whereby one object acquires characteristics from one or more other objects the same way children acquire characteristics from their parents. There are two types of inheritances:

    • Implementation inheritance (aka class inheritance): You can extend an application’s functionality by reusing functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only inherit from one superclass. Implementation inheritance promotes reusability but improper use of class inheritance can cause programming nightmares by breaking encapsulation and making future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using implementation inheritance, make sure that the subclasses depend only on the behavior of the superclass, not on the actual implementation. For example in the above diagram, the subclasses should only be concerned about the behavior known as area() but not how it is implemented.
    • Interface inheritance (aka type inheritance): This is also known as subtyping. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.
    Which one to use? Prefer interface inheritance to implementation inheritance because it promotes the design concept of coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object composition. If you look at Gang of Four (GoF) design patterns, you can see that it favors interface inheritance to implementation inheritance.

    Encapsulation : refers to keeping all the related members (variables and methods) together in an object. Specifying member variables as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy.
    Being able to encapsulate members of a class is important for security and integrity. We can protect variables from unacceptable values.

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

    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 class
    • Have executable methods and abstract methods.
    • Can only subclass one abstract class.
    Interface
    • Have no implementation code.
    • All methods are abstract.
    • A class can implement any number of interfaces.
    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
    When to use an interface?:
    For polymorphic interface inheritance, where the client wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract. CO Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. For example: The Spring framework's dependency injection promotes code to an interface principle. Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritance. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this diamond problem.

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

    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. Example java.io.Serializable , java.lang.Cloneable, java.util.EventListener etc. Marker interfaces are also known as "tag" interfaces since they tag all the derived classes into a category based on their purpose.

    Java Fundamentals 2 >>>


    Home Clouds