Showing posts with label OOP. Show all posts
Showing posts with label OOP. 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.

Java: Attempting to Assign Weaker Access Privileges Error

Access Specifiers in Method Overriding – Java

As per the rules of method overriding, you cannot use a weaker access specifier in the child class when overriding a method from the parent class.

For example, if the parent class has a method display() with a protected access specifier, the child class can override it using protected or public, but cannot use private.

Access Level

  1. Public

  2. Protected

  3. Default (package-private)

  4. Private

Access specifiers play an important role in inheritance and method overriding in Java.

Example:

/*
 * @Author TechBytes
 */

class AccessTest {

    protected void display() {
        System.out.println("Hello AccessTest:Display");
    }
}

class TestWithMain extends AccessTest {

    // Trying to override with a weaker access specifier
    // This will result in a compilation error.

    private void display() {
        System.out.println("Hello TestWithMain:display");
    }

    public static void main(String[] str) {

        AccessTest acObj = new TestWithMain();
        acObj.display();
    }
}

Error:

TestWithMain.java:8: display() in TestWithMain cannot override
display() in AccessTest;
attempting to assign weaker access privileges; was protected

private void display() {

The error occurs because the parent class method is protected, while the overriding method in the child class is private.

Correct Approach:

You can change the access specifier of the child method to protected or public.

Using public:

public void display() {
    System.out.println("Hello TestWithMain:display");
}

OR

Using protected:

protected void display() {
    System.out.println("Hello TestWithMain:display");
}

Both approaches work because the child class is not reducing the visibility of the parent method.

Note:

An overriding method can have the same or wider access than the method in the parent class, but it cannot reduce the access level.

Hope it helps you understand access specifiers and method overriding in Java.


Access Modifiers in Method Overriding: Rules and Examples in Java

As per the rule in overriding , you cannot apply weaker access specifier over a stronger access specifier.Suppose , your parent class has a method Display() with stronger access specifier like Public, then you cannot use weaker access specifier like private or public when you are overriding the Display() method.

Note :-


 Public is the 1st stronger access specifier
 Protected is the 2nd stronger access specifier
 Default is the 3rd stronger access specifier
 Private is the most weaker access specifier

 Always keep in mind about the access specifiers has vital role in inheritance (OOPS concept).

 Example :-


class AccessTest{
    protected void display(){ //Stronger Access specifier
        System.out.println("Hello AccessTest:Display");
    }
}

class TestWithMain extends AccessTest{
    // I am trying to override with weaker specifier , it show error
    // You can use public or protected (higher or same level of access specifier)
    private void display(){
        System.out.println("Hello TestWithMain:display");
    }   
    public static void main(String str[]){       
        AccessTest acObj=new TestWithMain();
        acObj.display();
    }   
}
 
 Error :-

 TestWithMain.java:8: display() in TestWithMain cannot override display() in AccessTest;
 attempting to assign weaker access privileges; was protected
    private void display(){

   

So, now if you change the access specifier to protected or public then it will work properly.

Changed executable code :-

   public void display(){
        System.out.println("Hello TestWithMain:display");
    }

   
    OR
   
    protected void display(){
        System.out.println("Hello TestWithMain:display");
    }

  Hope it will help you.

Static Block vs Instance Initialization Block in Java (With Example)

 

In Java, understanding the order of execution between static blocks and instance initialization blocks is essential for managing class-level and object-level setup.

  • Static Block (static { ... }): Belongs to the class itself, not to any specific object. It executes exactly once when the class is loaded into memory by the JVM, well before any instances are constructed.

  • Instance Initialization Block ({ ... }): Belongs to individual object instances. It executes every time a new object is created, running immediately before the constructor body.

 Code Example - InitBlockStaticBlock.java

 public class InitBlockStaticBlock {

    // 1. Static Initialization Block: Runs once when the class is loaded
    static {
        System.out.println("Executing static block (Class loaded)");
    }

    // 2. Instance Initialization Block: Runs once per object instantiation
    {
        System.out.println("Executing instance init block (Object created)");
    }

    public static void main(String[] args) {
        System.out.println("--- Inside main method ---");

        InitBlockStaticBlock obj1 = new InitBlockStaticBlock();
        InitBlockStaticBlock obj2 = new InitBlockStaticBlock();
        InitBlockStaticBlock obj3 = new InitBlockStaticBlock();
    }
}
 

Output :- 

Executing static block (Class loaded)
--- Inside main method ---
Executing instance init block (Object created)
Executing instance init block (Object created)
Executing instance init block (Object created) 

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.