Showing posts with label Object Oriented Programming. Show all posts
Showing posts with label Object Oriented Programming. Show all posts

Monday, September 7, 2026

5 Common Java Interview Questions About Objects and Object Class

5 Common Java Interview Questions About Objects and Object Class

These are some common questions asked in Java/J2EE interviews. These questions are based on Java objects and their behavior.

Q.1. How can you define an object? How is it related to the real world and how does it behave? With Example.

Ans: This question is often asked in Java interviews for candidates with 1-8 years of experience. As we know, an object is a real-world entity. It has three basic properties i.e. State, Behavior and Identity. Simply we can say that a class is a blueprint for creating objects, and an object is an instance of a class. Anything around you can be represented as an object. But yes, it has the above three properties by which we can define an object.

State: what the object has. Dog has a name, age, color, etc. It is implemented by variables in Java.

Behavior: what the object does. Dog can bark, bite, run, etc. It is implemented by methods in Java.

Identity: what makes the object unique. Identity is what makes one object distinguishable from another object. It does not necessarily mean that every object must have a unique id variable. Different objects can also have the same hash code.

Example - Suppose there are many dogs. But, you can't say that is an object. You need to take one dog which has name - Dick, age - 8, color - white and it can be distinguished from other objects. And now we can say Dick is a dog object. And this Dick can bark, bite and run. These are the behaviors that the object can do, and they are implemented by methods.

Q.2. How many constructors & methods are in Object class?

Ans: The Object class has one constructor and several methods. The exact list depends on the Java version. It is available inside the java.lang package.

Constructor :-

public Object()

Methods :-

clone() - This creates and returns a copy of the object.
equals() - This is used to compare whether some other object is equal to this object or not.
toString() - Converts and returns a string representation of the object.
finalize() - An old mechanism associated with garbage collection. It is deprecated and should not be relied upon for resource cleanup.
getClass() - This returns the runtime class of this object.
hashCode() - Returns a hash code for this object. The hash code is not guaranteed to be unique.
notify() - Wakes up a single thread that is waiting on this object's monitor.
notifyAll() - Wakes up all threads that are waiting on this object's monitor.
wait() - This makes the current thread wait until another thread notifies it.

Q.3. Why are wait() and notify() methods inside Object class instead of Thread class?

Ans: This is a FAQ for any Java interview. The wait() and notify() methods are used in a multi-threaded environment. These methods are inside the Object class because we are doing the monitoring work over an object. Whenever we are calling these methods, we are calling them on an object, not on a thread.

The wait() and notify() methods are used for thread coordination through an object's monitor.

Q.4. How many ways can we create an object in Java?

Ans: There are basic four ways for creating an object in Java as below:-

By using new keyword -

Object obj = new Object();

By using Class.forName() -

Dog dogObj = (Dog) Class.forName("jdeveloperguide.lab.Dog")
        .getDeclaredConstructor()
        .newInstance();

By using deserialization -

ObjectInputStream inStream = new ObjectInputStream(anInputStream);
Dog dogObject = (Dog) inStream.readObject();

By using clone() -

Dog dogObj = new Dog();
Dog dogObj2 = dogObj.clone();

The class must implement the Cloneable interface and provide appropriate cloning support.

Q.5. How does JVM allocate objects in memory? What is heap and stack memory?

Ans: Normally, objects are allocated on heap memory. Heap memory is a dynamic memory area used for objects during runtime.

Each thread has its own stack for method calls and local variables. Objects are generally allocated on the heap, while references and local variables may be stored in the stack depending on the JVM implementation and optimization.

Every thread creates a stack (call stack), and when the thread completes, its stack is no longer needed and its memory can be reclaimed.

Stack operations are generally simpler and faster than heap allocation, but the actual behavior depends on the JVM and its optimizations.

You can share your interview experience with asked questions and answers for publishing on this blog.

Understanding Interfaces in Java: Definition, Syntax, and Implementation

As there are ample of technology in the area of Computer science, that has many contribution to mankind.When I was a student of computer science, I had many doubts about my future .On which platform or language I should work ? What will be my profession? Out of all I choose Java as soul of my profession.

Rally java has many features and scopes.But when I go for the interface ( like an important organ in the java body) , really I can not calculate the face value of interface.How much essential it is for java followers?The face value of interface is undefined.As we know that interface makes java popular.

The Term  "Interface"

And it is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies inside interface. Interfaces cannot be instantiated and interfaces can only be implemented by classes or extended by other interfaces.Its a protocol of communication between objects.

How to Define an Interface ?

It is quite simple to define an interface. The modifier 'interface' is used to define an interface.The naming convention shall be follows like declaring a class.A class can implement more than one interface separated by comma.And also an interface can extends more than one interface separated by comma.And it contains only signature of the method , no implementation.

public interface SymbolInterface extends int_face1, int_face2, int_face3,int_face4 {
//Declare your member here
}

OR


public class ImplementSymbolInterface implements SymbolInterface,OtherInterfaces {
//Declare your member here
}


It is recommended to make your interface public, so that it can be used by other packages, or it can only visible to that implemented class.And you quite sure that the body of the  interface is always having any number method (without method body) or closing with semicolon.Those method has no implementation inside that interface. For implementing that you may need implementation class.

Except, method an interface can contain constant declaration with few modifiers public,static and final. These method & constant declarations are completely optional, i.e. you can declare an interface without any method or any constants. And when an interface does not contain any method or constants that interface is called Marker Interface.

Note:- Yes, Marker interface is good question asked by major MNC .You can find more details about marker interface from the post A Moment with with Marker Interface in Java Development, What is Marker Interface.

How to Implement an Interface ?

Yes, this is the point that you need in your real life program. Before going to implement you have some brief idea about the term interface & its usage.

Use, implements keyword for implement the interface over a class . Follow few code below :-

Declare an interface :


public interface InterfaceSymbol {

    public void symbolAdd();
    public void symbolDiv();
    public void symbolMul();
    public void symbolSub();
   
}

Implement the above interface for a class :

public class SymbolImplementa implements InterfaceSymbol{

    public void symbolAdd(){
        System.out.println("I am In Add");
    }
    public void symbolSub(){
        System.out.println("I am In Sub");
        }
    public void symbolMul(){
        System.out.println("I am In Mul");
    }
    public void symbolDiv(){
        System.out.println("I am In Div");
    }
}


As per the rule you must have to override the methods of interface in the implementation class. But , remember it is not mandatory , you can avoid it by using :

1--- Adapter Class
2--- Make that implementation class as Final. ( Final is a keyword)

Here I am not describing how to avoid for overriding all methods of interface.This is beyond of this post.You follow other posts related to interface.

Also , like a class one interface can extend ( defined keyword) another interface.And the behavior of that interface will remains same.When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

This is main function where the implementation is done.

public  class MainImplementationClass  extends SymbolImplementa implements InterfaceSymbol{

    /**
     * @param args
     */
    public void symbolAdd(){
        System.out.println("inside ");
    }
    public static void main(String[] args) {
        testf fobj=new testf();
        SymbolImplementa impobj;
        //fobj.symbolAdd();
        impobj=fobj;
        impobj.symbolAdd();
        System.out.println("I am in Main.........");
       
    }

}




The word of Caution.

Then you need to rewrite an interface, be careful about the pitfall. In the above example  InterfaceSymbol interface is implemented by the class SymbolImplementa , but  If you make few changes in the old interface , all classes that implement the old InterfaceSymbol interface will break because they don't implement the interface anymore. Programmers relying on this interface will oppose deeply.So, enjoy the flavor of interface in java programming.







Understanding the super Keyword and Constructors in Java

Understanding the super Keyword and Constructors in Java

When talking about inheritance in Java, it is important to understand that constructors are not inherited by a subclass.

A subclass can, however, invoke a constructor of its super class using the super keyword.

A few points about the super keyword

  1. super is a Java keyword.

  2. It can be used to access members of the super class, such as fields and methods.

  3. It can be used to invoke a super class constructor.

  4. When calling a super class constructor using super(...), it must be the first statement in the subclass constructor.

Example

class SUP {

    public SUP(String s) {
        System.out.println("Hi Super: " + s);
    }
}

// SUB class extending SUP class
class SUB extends SUP {

    public SUB(String p) {

        // Explicitly call the super class constructor
        // super(...) must be the first statement
        super(p);

        System.out.println("Hi SUB: " + p);
    }

    public static void main(String[] args) {
        new SUB("Rahul Sharma");
    }
}

Output

Hi Super: Rahul Sharma
Hi SUB: Rahul Sharma

When the SUB object is created, its constructor first invokes the SUP constructor using super(p). After the super class constructor completes, the remaining statements in the SUB constructor are executed.

What happens if super() is not written?

If the super class has an accessible no-argument constructor, Java automatically inserts a call to super() as the first statement of the subclass constructor, provided you don't explicitly call another super class constructor.

For example:

class SUP {

    public SUP() {
        System.out.println("Hi Super");
    }
}

class SUB extends SUP {

    public SUB() {
        // Compiler automatically inserts super();
        System.out.println("Hi SUB");
    }
}

The output is:

Hi Super
Hi SUB

However, if the super class does not have an accessible no-argument constructor, the subclass must explicitly invoke one of the available super class constructors.

Important point

Constructors are not inherited in Java. They are invoked as part of object construction.

The super keyword allows a subclass to explicitly invoke a super class constructor and access super class members.

Monday, February 26, 2018

Wells Fargo Java interview questions for 4-8 years experience

Java/J2ee interview questions asked by Wells Fargo for 4-8 years of experience. These interview questions had asked in the 1st round of technical interview.


1. About your current project.
2. What is Abstract class and interface, when we need to use them.
3. What is the significance of concurrency API ? What are the API you have used ?
4. What is difference between Hashmap and Hashset.
5. What is use of Linked list over ArrayList
6. What is Concurrent Hashmap? Give me the internal implementation of Concurrent HashMap.
7. Can we declare final inside abstract class and interface both.
8. Tell some critical situation in your current project or solution,you have handled. 
9. Give a design level understanding on abstract class and interface implementation.While design, you need consider the system scalability, robustness , few software designing principle.

10. Write a utility using some design pattern ?
11. Write your own hibernate DAO and IMPL for persist and update the record.
12. Which Jar we need for spring annotation.
13. What is importance of @RestControllor ?
14. What is the underlined design pattern implemented in hibernate ?


Saturday, September 20, 2014

Capgemini Interview Questions and Answers for Java 3-8 Year Experience

Experience Java/J2ee interview Questions asked by Capgemini.

1. Tell me about yourself ?

Ans : Give your brief introduction.

2. Explain about your current project?

Ans : It’s quite easy to describe your projects and your key role on this project. But, be careful and get ready about the functionality when you are describing your working module / part of the project. Show your confidence that you have done the major part and you can face challenges in future.

3. How many types of literals are there in JAVA ?

Ans : The literals means the value you are assigning to variable. You can specify the below types of literal in java.As per the primitive data types(int,short,long,float,double,boolean,char ,etc there is respective literal. Some literal needs to be ended with a specific character.Read More.

           long var=20L; //specify L or l for long literal
int var=20; // If not mentioned any character then its can be short or int
char var=’A’;
float var=10.44f; //specify f or F for float literal
double var=10.44;
boolean var=true; //or false
               

4. What is meant by Garbage collection ?

Ans :  Garbage collection is a automatic feature of java for cleaning the unused object from heap. It helps to developer for releasing the reserved memory without any extra effort by developer. It helps developer to save time and extra mental tension for handling object allocation in memory. When there is no reference to an object found, it will clean that object from memory . You can run the garbage collection explicitly by using System.gc() .    

5. Difference between string s= new string (); and string s = "Hi Dude"; ?

Ans : Both statements are different to each other. Always ‘new’ keyword is used to create object.

String s=new String(); // This statement creates new object in heap. S is the object here.
String s=”Hi Dude” ; // This statement do not create object, its creating reference and its storing in String Constant Pool.S is the reference here.


6. What is singleton class? where is it used ?


7. What is the difference between JSP and Servlets ?

Ans : As simple JSP is per-compiled but Servlets are not. JSP is specially use for displaying/populating the data on browser. If we take an example of MVC architecture JSP plays the role of View (V). But, Servlets are used to handle the request and process the business logic. In MVC architecture Servlets are knows as Controller (C) .

8. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

Ans : Both are taking String parameter, but request.getRequestDispatcher() will dispatch the request inside the application. Where as context.getRequestDispatcher() will dispatch the request outside the context also. If you are using absolute path for dispatching then both are similar.

9. How the JSP file will be executed on the Server side ?

Ans : First its converted to java file. Then its compiled  by java compiler and creates the .class file.Now once you get the .class file you can execute it. Internally a JSP converts into respective servlet.

Conversion => Compilation => Execution

10. What is ActionServlet ?

Ans : ActionServlet provides the controller in struts application with MVC (Model-View-Controller) Model 2. 
ActionServlet is a sub class of javax.servlet.http.HttpServlet.It has few methods like
doGet(),doPost(),destroy(),etc.


11. What is Struts Validator Framework ?
Ans : Struts provides a convenient way to validate. Basically we are using two xml configuration file for configuring such as Validator.xml and validation-rule.xml . validation-rule.xml defines the rule of validation like number format validation,email validation. Apart from this ActionForm having validate() method which we can implement for validating the form data.


12. What is the difference between the Session and SessionFactory in hibernate ?

Ans : Session and SessionFactory are playing a prominent role in hibernate. SessionFactory is used to create Session  and its created once during starting of the application. You can have only one SessionFactory per application. SessionFactory is also called 2ndlevel cache. But, Session could be many per application. Session is being created by using SessionFactory object.Session is called 1st level cache.

13. What is HQL ? 

Ans : HQL stands for Hibernate Query Language. Its fully object oriented and quite similar with SQL.It supports association and joins for effective entity relationship.

Thursday, September 11, 2014

Singleton Design Pattern in Java – A Quick Guide

Singleton design pattern is the most useful pattern in real time scenario.Singleton pattern will ensure that there is only one instance of a class is created in the JVM. This implementation restrict the user to create multiple access point or instance. This is a recreational design pattern. It has many implementation over java language, but singleton is an anti-pattern or bad practice.

There is 2 basic way for implementing singleton behavior.

  • Eager/Early Loading
  • Lazy Loading
Eager/Early Loading

Eager/Early loading is basically load of objects before actually use. But, sometimes it’s not recommended, if the object creation is expensive.

A simple example of eager or early loading.
/**
 * Eager/Early Loading
 * @author javalang
 *
 */
public class SingleTon {

private static final SingleTon OBJSINGLETON=new SingleTon();

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw new IllegalStateException("This is singleton, object already exist");
};

public static SingleTon getInstance(){
      return OBJSINGLETON;
}

}

Lazy Loading


Lazy loading means the object will be load when it’s required. When we need the object that time only we need to create object. It’s useful and recommended. But the use of singleton is depends on the context or requirement. It’s always recommended when the operation is really expensive.

A simple example of lazy loading.


package com.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Call this method & create object only when required
public static SingleTon getInstance(){
      if(OBJSINGLETON==null){
            OBJSINGLETON=new SingleTon();
      }
      return OBJSINGLETON;
}

}

But, in the above example the singleton object is not useful for multi-threaded 
environment. This above singleton objects are not thread safe. 
You can use ‘synchronized’ keyword to make the object creation thread safe. 
A simple example with synchronized keyword.
 
package com.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Call this method & create object only when required
public static SingleTon getInstance(){
            synchronized (SingleTon.class) {
                  OBJSINGLETON=new SingleTon();
            }          
      return OBJSINGLETON;
}
} 

In the above example the synchronized block allow the object creation thread safe. But the member variable is not thread safe yet. The member variable OBJSINGLETON is not thread safe here. 


Here is one important question for interview. How to make a variable thread safe?


Ans : By using volatile keyword.



But, there is one another better approach which will help us to cross check the implementation. By implementing the “Double-checked locking” we can make the singleton object more secure. This ensure the expensive operation of creating object is the very first call. 

package com.jdeveloperguide.lab;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon {

private static volatile SingleTon OBJSINGLETON=null;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Create object only when required
public static SingleTon getInstance(){
      //1st Check
      if(OBJSINGLETON==null){
            synchronized (SingleTon.class) {
                  //2nd Check
                  if(OBJSINGLETON==null)
                  OBJSINGLETON=new SingleTon();
            }          
      }
      return OBJSINGLETON;
}
}

Now the singleton object OBJSINGLETON is thread safe. But, there is one more issue with singleton when we go for serialization. Because, during deserialization process it creates new object and it violate the singleton strategy. So, we should make sure that there is no new objects are created during deserialization. To avoid this issue you can use readResolve() method in serializable.

A simple example using readResolve() method.

package com.jdeveloperguide.lab;

import java.io.Serializable;

/**
 * Lazy Loading
 * @author jdeveloperguide
 *
 */
public class SingleTon implements Serializable {

private static volatile SingleTon OBJSINGLETON=null;
public static final long serialVersionUID=0L;

private SingleTon(){
      if(OBJSINGLETON!=null)
            throw newIllegalStateException("This is singleton, object already exist");
};

//Create object only when required
public static SingleTon getInstance(){
      //2nd Check
      if(OBJSINGLETON==null){
            synchronized (SingleTon.class) {
                  //2nd Check
                  if(OBJSINGLETON==null)
                  OBJSINGLETON=new SingleTon();
            }          
      }
      return OBJSINGLETON;
}

//This ensure the protection on serialization
@SuppressWarnings("unused")
private SingleTon readResolve(){
      return OBJSINGLETON;
}
}

 All the above example with implementations are traditional , which are not recommended by java 5 and above. There is one more better way to implement singleton strategy by using Enum. A simple example below using Enum.


package com.jdeveloperguide.lab;

/**
 * Singleton behavior using Enum
 * @author jdeveloperguide
 *
 */
public enum SingleTonEnum {
SINGLETONINSTANCE;
public void javaProgrammingStuff(){
      //Here is your stuffs
}
}
Enum provides lazy loading approach. Enum gives guaranty for thread safety and safety during serialization.

Interview Questions :


Q – What is serialVersionUID ?

Ans :- This maintain version number in complied class. It’s useful during deserialization process. During deserialization it maintains the similar copy as similar as serialization process.


Q – What is readResolve() method ?

Ans :- This method ensure a unique object during deserialization. It’s useful when implementing serialization over singleton object. It avoid to create new object during deserialization.