0% found this document useful (0 votes)
25 views8 pages

Understanding JVM Architecture and Execution

The document provides an overview of the Java Virtual Machine (JVM) architecture, detailing its components such as Classloader, Heap, Stack, and Execution Engine. It also explains the structure of a Java program, including sections like Documentation, Package Declaration, Import Statements, and the main method. Additionally, it covers concepts related to static variables and methods, the String class, and methods associated with it.

Uploaded by

haiitzmex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views8 pages

Understanding JVM Architecture and Execution

The document provides an overview of the Java Virtual Machine (JVM) architecture, detailing its components such as Classloader, Heap, Stack, and Execution Engine. It also explains the structure of a Java program, including sections like Documentation, Package Declaration, Import Statements, and the main method. Additionally, it covers concepts related to static variables and methods, the String class, and methods associated with it.

Uploaded by

haiitzmex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JVM (Java Virtual Machine) Architecture

● JVM is a virtual machine that enables the execution of Java bytecode.

JVM Architecture

Classloader
● It is a subsystem of JVM.
● It is used to load class files.
● There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: It loads the [Link] file, it contains all class files of Java
Standard Edition like [Link] package classes, [Link] package classes, [Link]
package classes, [Link] package classes, [Link] package classes etc.
2. Extension ClassLoader: It loads the jar files located inside the
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: It loads the class files from classpath.

Class(Method) Area

● It stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.
Heap
● It is the runtime data area, objects are allocated.

Stack
● It stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.

Program Counter Register


● It contains the address of the JVM currently being executed.

Native Method Stack


● It contains all the native methods used in the application.

Execution Engine
● It contains a virtual processor, A Interpreter and Just-In-Time(JIT) compiler.

Java Native Interface


● It is a framework.
● It provides an interface to communicate with another application written in another
language like C, C++, Assembly etc.

Structure of Java Program


Documentation Section
● It is an optional for a Java program.
● It includes basic information about a Java program.
● The information includes the author's name, date of creation, version, program name,
company name, and description of the program.

Package Declaration
● The package declaration is optional.
● Declare the package name in which the class is placed.
● There can be only one package statement in a Java program.

(Eg) package javatpoint; //where javatpoint is the package name

Import Statements
● It contains many predefined classes and interfaces.
● If we want to use any class of a particular package, we need to import that class.
● The import statement represents the class stored in the other package.

(Eg)import [Link].*; //it imports all the class of the [Link] package

Interface Section
● It is an optional section.
● An interface is slightly different from the class.
● It contains only constants and method declarations

interface car
{
void start();
void stop();
}

Class Definition
● It contains information about user-defined methods, variables, and constants.
● Every Java program has at least one class that contains the main() method.

class Student //class definition

{
}

Class Variables and Constants


● The variables and constants are defined just after the class definition.
● The variables and constants store values of the parameters.
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}

Main Method Class


● The execution of all Java programs starts from the main() method.
● It must be inside the class.

public static void main(String args[])

{
}

Methods and behavior


● The methods are the set of instructions that we want to perform.
● These instructions execute at runtime and perform the specified task.

Program

class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}

Java main() method


A Java program is executed, the Java Virtual Machine (JVM) looks for the main() method to
begin execution.
Program

public class HelloWorld {


public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Output:

Hello, World!

● Public
○ It is an access specifier.
○ A public keyword used before the main() method, so that JVM can identify the
execution point of the program.
● Static
○ It invokes without creating the objects, so do not need any object to call the
main() method.
● Void
○ keyword acknowledges the compiler that the main() method does not return any
value.
● Main ()
○ It is called by JVM to execute a program line by line and end the execution after
completion of this method.
● String args[]:
○ The main() method accepts some data from the user. It accepts a group of strings,
which is called a string array.

Java Console Output([Link])

● Java [Link]() is used to print an argument that is passed to it.

Parts of [Link]()

1. System - It is a final class defined in the [Link] package.


2. Out - This is an instance of PrintStream type, it is a public and static member field of the
System class.
3. println() - The PrintStream class has a public method println(). It prints any argument
passed to it and adds a new line to the output.
Java Console Input

● There are different ways to read input from the user in the command line
environment(console).

● Using Buffered Reader Class


a. This method is used by wrapping the [Link] (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader.
b. Example
BufferedReader reader = new BufferedReader(
new InputStreamReader([Link]));
String name = [Link]();
● Using Scanner Class
○ it is also used to read input from the user in the command line.
○ Example
Scanner in = new Scanner([Link]);
String s = [Link]();

Static Data
● Declare any variable as static, it is known as a static variable.
● It is used to refer to the common property of all objects for example, the company name
of employees,
● It gets memory only once in the class area at the time of class loading.
● It is used to initialize the default values if not explicitly initialized by the programmer.
● It is shared among all instances of the class
● eg
static String college ="ITS";//static variable

Static Method
● A static keyword with any method, it is known as a static method.
● It belongs to the class rather than the object of a class.
● It can be invoked without the need for creating an instance of a class.
● It can access static data members and can change their value of it.

Program
class Student{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display(){[Link](rollno+" "+name+" "+college);}
}
public class TestStaticMethod{
public static void main(String args[]){
[Link]();
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
[Link]();
[Link]();
}
}

Output:
111 Karan BBDIT
222 Aryan BBDIT

String Class
● It is a sequence of characters.
● Objects of the String class are immutable it means they cannot be changed once created.

Program
import [Link].*;
class GFG {
public static void main (String[] args) {
String s="Geeks for Geeks String in Java";
[Link](s);
}
}
Output
Geeks for Geeks String in Java

Creating a String
● There are two ways to create string in Java:
○ 1. Using String literal
String s = “GeeksforGeeks”;
● Using new keyword
String s = new String (“GeeksforGeeks”);

String Constructors
String(char[] char_arr) - Allocates a new String from the given Character array.

String Methods
1. int length() - Returns the number of characters in the String.
2. Char charAt(int i) - Returns the character at ith index.
3. String substring (int i) - Return the substring from the ith index character to end.
4. String concat( String str) - Concatenates specified string to the end of this string.
5. String replace (char oldChar, char newChar) - Returns new string by replacing all occurrences
of oldChar with newChar.

String Buffer Class

Common questions

Powered by AI

Static variables in Java are associated with the class rather than any individual instance. They are declared with the 'static' keyword and get memory allocation once during class loading into the JVM, making them shared across all instances of the class . This contrasts with instance variables, which are unique to each instance of a class and get memory allocation every time an object is created . Since static variables hold a common property for all objects, such as a company name or a constant value, they can be accessed directly using the class name without needing an object .

The execution engine in the JVM utilizes both an interpreter and a Just-In-Time (JIT) compiler to execute Java bytecode effectively. Initially, the interpreter reads and executes the bytecode instructions one by one, which is straightforward but can be slower due to repeated interpretation processes . To optimize execution, the JIT compiler compiles frequently executed code sections into native machine code, which is stored and reused, thereby significantly improving performance . This hybrid approach allows Java programs to start quickly with the interpreter, while the JIT compiler accelerates subsequent execution by optimizing performance-critical code paths.

Java's System.out.println() method can aid debugging by allowing developers to print variable values and execution checkpoints to the console, helping trace program flow and identify issues . The main components of System.out.println() are: 1. System: A final class within the java.lang package providing input and output facilities . 2. Out: A static member of System, representing an instance of the PrintStream class responsible for standard output . 3. println(): A method of PrintStream that prints an argument followed by a newline, improving readability of diagnostic messages . This method is simple yet effective for logging program state and errors.

Static methods in Java differ from instance methods in that they belong to the class itself rather than any specific instance of the class. They can be called without creating an instance of the class and can only access other static members of the class directly . In contrast, instance methods require an object instance and have access to both static and instance variables of the class. For object-oriented design, using static methods can limit modularity and encapsulation because they do not operate on object data, potentially leading to designs that are less flexible. Static methods are beneficial for utility or helper functions that do not modify instance state, but reliance on them can make testing and maintenance more challenging as they inherently require a different testing approach compared to instance methods .

The Classloader subsystem in the JVM architecture is responsible for loading class files during the execution of a Java program. It manages three types of classloaders: 1. Bootstrap ClassLoader: Loads core Java API classes from the rt.jar file, which includes classes from standard packages such as java.lang and java.util . 2. Extension ClassLoader: Loads classes from the JRE's lib/ext directory, allowing for additional extensions to the standard Java classes . 3. System/Application ClassLoader: Loads classes from the classpath provided by the system, typically representing the user-defined classes and libraries needed by the application . This layered approach ensures that classes are loaded efficiently and in an organized manner.

The Program Counter Register plays a crucial role in maintaining execution order during the execution of a Java program by holding the address of the current instruction being executed by the JVM . This register enables the JVM to keep track of program control flow, ensuring that instructions are executed in a logical sequence and aiding in the branching operations required by method invocations and returns. However, a limitation of the Program Counter is that it operates at a low level, which may lead to difficulties when debugging high-level code as it only provides insights into the instruction execution sequence rather than conceptual program flow. Efficient management of this register is essential for system stability and accurate exception handling, helping synchronize instruction execution across threads.

The Java Native Interface (JNI) facilitates runtime communication between Java applications and native modules written in languages like C or C++ by providing a framework that allows Java code to interact with native libraries and applications . JNI supports the invocation of native methods and access to native resources, enabling Java programs to utilize system-level resources and functionalities that are outside the Java environment . It includes mechanisms to manage data type conversions and method calls across the Java and native language boundaries, making it possible for Java to achieve tasks that require high performance or direct hardware manipulation.

Java's heap and stack memory areas complement each other during application execution to manage memory efficiently. The heap is used for dynamic memory allocation and stores objects and class instances, providing memory management through garbage collection to reclaim memory of unused objects . The stack, conversely, manages function call execution by holding local variables and execution states via frame stacks, automatically allocates and deallocates memory for method execution . Issues in memory management can include memory leaks in the heap, caused when objects persist unnecessarily, consuming resources and eventually leading to OutOfMemoryError. In the stack, excessive deep recursion can lead to StackOverflowError due to exhaustion of stack space . Proper memory management strategies must be observed to balance resource use between these two areas, maintaining optimal application performance.

The Buffered Reader class provides efficient reading of character-based input by using buffers, making it more suitable for reading large amounts of data quickly compared to Scanner . It reads input data as a stream of characters, allowing for input operations that are both fast and memory-efficient. However, BufferedReader lacks the ability to parse input data, requiring additional logic to convert input strings to other data types. In contrast, the Scanner class is more user-friendly due to its tokenizing capabilities, allowing easy parsing of primitive types from input strings, which can be more convenient in applications requiring complex input processing . The tradeoff is that Scanner is generally slower due to parsing overhead and less efficient for handling large input streams.

Java handles multiple threads of execution within the execution engine by allowing concurrent thread management, with each thread operating independently while sharing resources and memory space, facilitating multitasking . The JVM's execution engine coordinates these threads, which execute bytecode concurrently, through Java's threading framework. Potential challenges in multi-threading include issues like race conditions, where threads compete for shared resources leading to inconsistent states, and deadlocks, where two or more threads block each other permanently by each holding a lock resources needed by the others . Proper synchronization and resource handling mechanisms, such as locks and concurrent utilities, are essential to prevent these challenges and ensure thread-safe operations.

You might also like