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

Write Your First Groovy Program

Write your first Groovy Program

If you remember we already discussed in my previous post about adding Groovy to your resume. Adding new skills will always help and increase your chance of getting your dream job.

Before everything you should have hands on experience on groovy programming. Lets see how to write a simple groovy program. As a newbie for groovy , you should start a basic hello world program.

Before start your first groovy program , you should make sure you have groovy installed in your machine (Desktop/Laptop). I am using Linux (Ubuntu) here to demonstrate this example.

You can check in your terminals and I have already installed Groovy. Below command I have used to check whether groovy is installed and what version of groovy I am using.
root@jdg-HP-ProBook-6450b:~/grovytest$ type groovy
groovy is hashed (/usr/bin/groovy)
root@jdg-HP-ProBook-6450b:~/grovytest$ groovy -version
Groovy Version: 1.8.6 JVM: 1.7.0_121 Vendor: Oracle Corporation OS: Linux
Now, we can write our first groovy program. Usually groovy files are saved with extension xxx.groovy. Groovy program doesn't required semicolon (;) to close like java.This is very simple and reduce the developer effort of coding.

Open vi editor or text pad. Lets start writing your first program. 

Below is a Sample groovy program :-

HelloWorld.groovy

println "Say Hello to Groovy"

Now save this file with extension .groovy. In this example I have given the file name as HelloWorld.groovy.

Now you need to execute this .groovy file using below command  on terminal and check the output. 

root@jdg-HP-ProBook-6450b:~/grovytest$ groovy HelloWorld.groovy
Say Hello to Groovy

Now you can see the output I have highlighted in color. This is a simple groovy program. Find more programs on my subsequent posts.


Hope this 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) 

How to Generate a Thread Dump in Java (Quick Guide)

A Thread Dump helps you track the exact activity of every running thread in your Java application at a specific point in time. It is essential for diagnosing high CPU usage, hanging tasks, and deadlocks.

How to Generate a Thread Dump

Method 1: Using the Command Line (Recommended)

You don't need keyboard shortcuts. Use the built-in JDK tool jcmd:

  1. Find the Java process ID:
    1.  jps -l
  2. 2. Print the thread dump to a file:
    1. jcmd <PID> Thread.print > threaddump.txt 

Method 2: Keyboard Shortcut (Console Window Only)

If you run the application directly inside an interactive command terminal:

  • Windows: Press Ctrl + Break (or Ctrl + Fn + B on modern laptops).

  • Linux / Mac: Press Ctrl + \ (or run kill -3 <PID>).

Simple Test Program

Run this program in your terminal, then trigger a thread dump using either method above to view the active thread stack traces:


Program :- LoopTest.java

public class LoopTest {
    public static void main(String[] args) throws InterruptedException {
        while (true) {
            System.out.println("Running...");
            Thread.sleep(1000); // Prevents console spamming
        }
    }
}



Saturday, September 5, 2026

Java: JVM Inside — The Story Behind JVM (Part 2)

In the previous post, we discussed some basic concepts about the JVM and its role in the Java platform. If you haven't read it yet, you can read Java: JVM Inside — The Story Behind the JVM before continuing with this post.

In this post, let's look a little deeper into what happens inside the JVM and some of the important runtime areas used while a Java application is running.

From Java Source Code to Bytecode

Java source code is compiled by the Java compiler (javac) into bytecode. The bytecode is stored in .class files.

A Java application may contain many classes, so multiple .class files can be packaged together into a JAR (Java Archive) file for easier distribution.

The Java application launcher, java, can be used to start a Java application. The JVM loads the required classes and executes the bytecode.

A JVM may interpret bytecode and can also use Just-In-Time (JIT) compilation to compile frequently executed code into native machine code at runtime. This allows the JVM to optimize application execution while the program is running.

There are also other approaches, such as Ahead-of-Time (AOT) compilation, which can compile code ahead of execution for particular environments.

JVM Runtime Areas

The JVM specification defines several runtime data areas. Some are created for each thread, while others are shared by threads. Important areas include:

  1. Program Counter (PC) Register

  2. JVM Stack

  3. Heap

  4. Method Area

  5. Runtime Constant Pool

  6. Native Method Stack

The JVM specification defines these runtime areas as part of the JVM architecture.

Bytecode Verification

Before bytecode is executed, the JVM performs verification as part of the class loading and linking process.

Bytecode verification helps ensure that class files satisfy the structural and type-safety requirements expected by the JVM.

For example, verification helps check that:

  1. Instructions are used correctly.

  2. Type information is used consistently.

  3. Branches and control-flow information are valid.

  4. Access-control rules are respected.

The JVM specification describes verification as part of the linking process.

JVM Stack

Each JVM thread has its own JVM stack.

The JVM stack contains frames, and a new frame is created when a method is invoked. A frame contains information such as local variables, an operand stack, and information used for dynamic linking.

For example:

Thread
  |
  +-- JVM Stack
        |
        +-- Frame for main()
        |
        +-- Frame for methodA()
        |
        +-- Frame for methodB()

When a method completes, its frame is removed from the stack.

The JVM specification defines JVM stacks and frames as important parts of the runtime environment.

Heap

The heap is the runtime data area from which memory for objects and arrays is allocated.

For example:

Employee employee = new Employee();

When the new operation creates an Employee object, the object is allocated in the heap.

Java does not require developers to manually free this object using a free() operation as in languages such as C or C++. Instead, Java uses Garbage Collection (GC) to automatically reclaim heap memory that is no longer reachable by the application.

Garbage collection is one of the important features of the Java runtime.

A simple way to visualize this is:

JVM
 |
 +-- Heap
 |     |
 |     +-- Object 1
 |     +-- Object 2
 |     +-- Array
 |
 +-- JVM Stack
       |
       +-- Local variables
       +-- Object references

It is common to explain that an object reference can be held in a stack frame while the actual object is located in the heap. However, the exact implementation details of references and memory placement are JVM-implementation dependent, so this should be treated as a conceptual model rather than a strict physical-memory rule.

Arrays in Java are objects, so they are also managed as heap objects.

Method Area

The Method Area is a JVM runtime data area that is shared among threads.

It stores per-class structures such as the runtime representation of classes, methods, fields, and other class-related information.

The method area is not simply a place where "all bytecode is stored." Class files are loaded and linked by the JVM, and the JVM maintains the runtime representation required for execution.

The JVM specification defines the Method Area conceptually, while the exact implementation is JVM-specific.

Runtime Constant Pool

Each class or interface has a runtime constant pool associated with it.

It contains information derived from the constant pool in the class file, including constants and symbolic references used by the class.

The runtime constant pool is important for operations such as dynamic linking.

Final Thoughts

The JVM is much more than a simple program that executes .class files.

It provides a complete runtime environment for loading classes, verifying bytecode, managing memory, executing methods, handling threads, performing garbage collection, and optimizing frequently executed code.

Understanding these JVM runtime areas helps Java developers understand what happens behind the scenes when a Java application runs.

Java: JVM Inside — The Story Behind the JVM

The JVM (Java Virtual Machine) is a core component of the Java platform. JVM stands for Java Virtual Machine.

The JVM is software that provides an execution environment for running Java bytecode. It acts as an abstraction layer between Java bytecode and the underlying operating system and hardware.

Java source code is first compiled into bytecode, which is stored in .class files. The JVM then loads and executes this bytecode.

A simple way to understand the process is:

Java Source Code → Java Compiler (javac) → Bytecode → JVM → Operating System / Hardware

The important point is that the same Java bytecode can generally run on different operating systems as long as a compatible JVM implementation is available.

This is one of the key ideas behind Java's well-known WORA (Write Once, Run Anywhere) concept.

For example, the same .class file can be executed using a compatible JVM on different platforms:

                 Java Source File (.java)
                           |
                           |
                     Java Compiler
                       (javac)
                           |
                           |
                    Bytecode (.class)
                           |
              +------------+------------+
              |            |            |
             JVM          JVM          JVM
              |            |            |
           Windows        Linux        macOS

The JVM specification defines how Java class files and bytecode are handled, while JVM implementations provide the actual runtime environment for a particular platform.

Why is JVM important?

The JVM provides several important capabilities, including:

  • Loading and executing Java class files

  • Managing memory and runtime data areas

  • Garbage collection

  • Bytecode verification

  • Exception handling

  • Supporting Java's platform-independent execution model

  • Providing runtime services needed by Java applications

The JVM specification defines areas such as the heap, JVM stacks, method area, runtime constant pool, and native method stacks.

Therefore, the JVM is one of the fundamental components that makes the Java platform portable across different operating systems and hardware environments.


Friday, September 4, 2026

Java/Tomcat: Understanding Out of Memory Error (OOME)

Out of Memory Error (OOME) in Tomcat

What is an Out of Memory Error, and why does it happen?

The basic cause of an OutOfMemoryError (OOME) is that the JVM cannot allocate enough memory for an application to continue running. In a Tomcat environment, this can result in an application failure or, depending on the situation, the Tomcat process being unable to continue.

The error itself is not particularly difficult to understand. The difficult part is finding the actual root cause.

A stack trace may show where the JVM ran out of memory, but it does not always identify why the application consumed so much memory. In many cases, the problem is related to the web application running inside Tomcat rather than Tomcat itself.

The code causing the problem may also look perfectly normal. For example, an application might load a large amount of data into memory, retain objects longer than necessary, or create too many objects during processing. This makes it difficult to identify which part of the application is actually responsible for the problem.

Here are some common causes of an OutOfMemoryError:

  • The JVM heap size is too small for the application's workload.
  • The application loads a very large file or a large amount of data into memory.
  • The application creates a large number of objects or collections.
  • Objects are unintentionally retained for longer than necessary, causing memory usage to grow.
  • Excessive recursion can cause a StackOverflowError rather than a heap OutOfMemoryError, so this should be considered a separate problem.
  • Too many threads can cause memory-related problems, although this may also result in errors such as Unable to create new native thread.
  • Running out of file descriptors is a separate operating-system resource issue and is not itself an OutOfMemoryError.
  • In older Java applications, a large number of web applications or classloaders could contribute to PermGen exhaustion.

Finding the Root Cause

Increasing the JVM heap size can sometimes reduce or temporarily resolve an OutOfMemoryError, but it does not necessarily fix the underlying problem. If the application continues to consume memory, increasing -Xmx only delays the failure.

For this reason, it is important to investigate the application's memory usage using appropriate JVM monitoring or profiling tools and identify which objects or parts of the application are consuming memory.

Note: PermGen applies to older Java versions. Java 8 removed PermGen and replaced it with Metaspace. Therefore, PermGen space errors are relevant mainly when troubleshooting older Java applications.

Error: java.lang.OutOfMemoryError: PermGen space

In J2EE development, this is one of the common and frequent errors that developers may face. Sometimes it can be difficult to identify the actual cause, especially when the application runs out of JVM memory.

PermGen space or heap size (OutOfMemoryError) issues can be addressed by increasing the JVM memory allocated to Tomcat. The following are some approaches that can be used.
 

Solution 1: Set CATALINA_OPTS

Set the `CATALINA_OPTS` environment variable before starting Tomcat.
 

Linux / Unix — ksh / bash

export CATALINA_OPTS="-Xms512m -Xmx512m"

Linux / Unix — tcsh / csh

setenv CATALINA_OPTS "-Xms512m -Xmx512m"

Windows

set CATALINA_OPTS="-Xms512m -Xmx512m"

Stop the Tomcat server, set the `CATALINA_OPTS` environment variable, and then restart Tomcat.

You can check `tomcat-install/bin/catalina.sh` or `catalina.bat` to see how `CATALINA_OPTS` is used.
 

CATALINA_OPTS vs JAVA_OPTS


In `catalina.bat` or `catalina.sh`, you may notice that `CATALINA_OPTS`, `JAVA_OPTS`, or both can be used to specify JVM options.

The difference is that `CATALINA_OPTS` is intended specifically for Tomcat, whereas `JAVA_OPTS` can also be used for other Java applications.

I prefer to use `CATALINA_OPTS` when configuring options specifically for Tomcat, so that Tomcat does not unnecessarily pick up JVM options intended for other applications.
 

Solution 2: Change catalina.bat

Another option is to modify the `catalina.bat` file under the Tomcat `bin` directory.

Open:

tomcat-install/bin/catalina.bat
 

Search for:
 

CATALINA_OPTS, If `CATALINA_OPTS` is not already configured, you can set the required JVM options there.

For older Java versions, an example configuration was:

-Xms256m -Xmx512m -XX:MaxPermSize=256m

If this does not work, check the command used to start Java near the end of the `catalina.bat` file. Look for a line containing `%_EXECJAVA%` and `%JAVA_OPTS%`.

The JVM options can be added to that command. For example:


%_EXECJAVA% %JAVA_OPTS% -Xms256m -Xmx512m -XX:MaxPermSize=256m %DEBUG_OPTS% -Djava.endorsed.dirs="%JAVA_ENDORSED_DIRS%" -classpath "%CLASSPATH%" -Dcatalina.base="%CATALINA_BASE%" -Dcatalina.home="%CATALINA_HOME%" -Djava.io.tmpdir="%CATALINA_TMPDIR%" %MAINCLASS% %CMD_LINE_ARGS% %ACTION%

In this example, `CATALINA_OPTS` has been removed from the command to avoid specifying the same JVM parameters more than once.
 

Important Note About MaxPermSize

`-XX:MaxPermSize` applies to older Java versions that used the PermGen memory area. Java 8 removed PermGen and replaced it with Metaspace.

Therefore, for Java 8 and later, do not use:

-XX:MaxPermSize=256m

For modern Java versions, the relevant options are typically `-Xms` and `-Xmx` for heap size, and `-XX:MaxMetaspaceSize` can be used when there is a specific need to limit Metaspace.

The exact JVM options should depend on the Java version being used by Tomcat.

Java: Fixing JVM Heap Size Errors in Eclipse and MyEclipse

I have used this setting in my IDE. I got this type of error when my team was working on a social-network-type project using the Struts framework. I was really in trouble and was looking for a solution. Finally, I found the solution, and it helped me. I hope it helps you too.

Follow these simple steps to change the Heap Size of Tomcat in Eclipse.

  1. Open the Servers tab in Eclipse and double-click the Tomcat server to open the Server Configuration.


2. In Server Configuration, click on the Launch Configuration link under General Information.
3. Under Arguments tab, add following values in VM arguments.
1
-Xms64m -Xmx256m

Java: JVM Heap Size and OutOfMemoryError: Java Heap Space

What Is JVM Heap Size and How Does It Affect Application Performance?

If you encounter the following error while running a Java application:

java.lang.OutOfMemoryError: Java heap space

it generally means that the JVM could not allocate enough memory in the Java heap for the application.

The Java heap is the memory area used by the JVM to store objects created by the application. If the application cannot allocate additional objects within the available heap, the JVM may throw an OutOfMemoryError.

Increasing the JVM heap size can help when the application genuinely needs more memory. However, simply increasing the heap size is not always the solution. Excessive object creation, memory leaks, or inefficient application code can also cause high memory usage.

How to Increase the Heap Size

For a Java application, you can specify the initial and maximum heap sizes when starting the application:

java -Xms65m -Xmx512m YourJavaFile

For a Tomcat application, JVM options can be configured through the appropriate Tomcat startup environment variables. For example, on Windows:

set CATALINA_OPTS=-Xms256m -Xmx1024m

Here:

-Xms
Specifies the initial Java heap size.

-Xmx
Specifies the maximum Java heap size.

-Xss
Specifies the Java thread stack size.

For example, -Xmx1024m sets the maximum Java heap size to 1024 MB. The JVM can use heap memory up to this limit as required, subject to the system's available memory and other JVM constraints.

Increasing the heap size may improve application stability when the configured heap is genuinely too small. However, if the application has a memory leak or creates more objects than expected, the underlying problem should also be investigated.


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 ?


Tuesday, January 24, 2017

Adding Groovy to Your Resume: Why Learn Groovy?

Adding Groovy to your Resume.


Are you adding groovy to your resume this year ? As a developer with 3-8 year experience you need heterogeneous number of technical skills. To compete a challenging goal and if you are seeking a challenging position , you need many skill sets . Only Java skills will not help you crack the interview.

Now-a-days most of the organizations are expecting a resource with full stack development experience.You can find more about full stack development in another post.


By adding Groovy to your resume will help you to build a positive impression for shortlisting your profile. Interview will always have a positive and negative result. But, shortlisting your profile is most important factor.

Groovy is quite old, but still you need Groovy for certain solution design. Once you added Groovy to your resume , make sure you are ready with all possible questions from interviewer. Sometimes , even you have hands on experience but you can't prompt your answer.

If you see what exactly Groovy is , you can say It's a kind of scripting language. It's a dynamic language with features similar to those of Python, Ruby, Perl, etc. It can be used as a scripting language for the Java Platform, is dynamically compiled to Java Virtual Machine (JVM) byte code, and interoperates with other Java code and libraries.  

Groovy uses a Java-like curly-bracket syntax and its really very easy to implement.

Finally again, its very clear that adding Groovy in your resume will help to shortlist your profile.This will increase the chance of hiring. Apart from job chance, this will impress the interviewer , if you are prompting with right answer :) :)

Find more posts  related to Groovy Programming Language.


Hope this will help you!!!