working – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 04 Jul 2022 06:39:26 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg working – Programmerbay https://programmerbay.com 32 32 Explain JVM Architecture in Java With diagram https://programmerbay.com/introduction-to-jvm-and-its-architecture/ https://programmerbay.com/introduction-to-jvm-and-its-architecture/#respond Mon, 14 Sep 2020 16:50:44 +0000 https://programmerbay.com/?p=5094 After compilation of java program by the compiler, the code turns into a respective .class file that contains Java bytecode. The file and the resources are then loaded onto JRE using Classloader.

jvm architecture

Class Loader Subsystem

In the classloader Subsystem there consists of three stages:-

1) Loading

2) Linking

3) Initialization

Loading

There are three kinds of loaders. Any program requires these three loaders to execute.

Bootstrap Classloader: It loads classes or packages that are essential for a program that resides in rt.jar file such as Java.lang.object, Java.lang.Thread etc.

Extension Classloader: It loads classes from installed optional packages and jar files that are required by JVM for the further processing program which resides within $JRE_HOME/lib/ext directory.

Application Classloader: It loads classes from the application path and this path can be set by using  -cp. It is also known as  system class loader.

Linking

It is responsible for verifying and preparing class or interface, however, the resolution is an optional process in linking. Class get loaded before linking and after that verified and prepared before initialization.

It has three steps:

1)Verification:- It checks whether a class or interface up to the JVM’S structural constraints or not. if not then it would throw VerifyError exception.

2) Preparation:- It initializes the instance variables of the class to its default value.

3) Resolution: It determines the actual value from symbolic references ( references of variables and methods are stored in class’s constant pool)  in runtime constant pool, dynamically.

Initialization

It invokes the class’s static initialization methods to initialize the static variable. It also initializes the class reference if it’s not initialized yet.

Runtime Data Area

It comprised of all the memories which are going to be used by JVM in order to execute a program. Out of these memories, some of them are created when JVM starts up and diminished when it ends up its execution.

  • Method area: It stores runtime constant pool, constructors, field and method data, and other meta data corresponding to a class. It is created when JVM starts up. By default the size of Method area are fixed and can be varied as per need.
  • Heap:- It is a memory area where all the objects with their properties and arrays get allocated. It is cleaned up and recycled by garbage collector because objects don’t get deallocated by itself. By default the size of Heap is almost one-fourth of the physical memory and can be varied as per need.
  • Java Stack: It consists frames which are created, whenever a method is invoked. Basically what t does is, it loads methods when they are invoked in a last-in-first-out manner and destroyed itself as task of the method finishes up. It stores data, partial results and return value of method.
  • Pc registers: It is a program counter which points to address of next instruction to be executed. It is responsible for thread management.
  • Native method stack:- It manages and stores native methods (methods written in a different language other than the JAVA). It is basically native operating dependent classes that are loaded to work with Java stack.

Execution engine

It is responsible for executing the bytecode. It has three subparts, these are:

Interpreter: It interprets bytecodes line by line and converts the bytecode to the machine understandable language.

Jit-compiler: Just-in-compiler comes into play when a single code inn program appears and executes multiple times. What it does is, it precompiles that particular piece of code and improves the performance by reducing the execution time.

Garbage collector: It cleans up the objects created by using new keyword which are not being used in heap memory area.

Java Native Interface

There may be situation where a programmer cannot writes his application entirely on Java language. In this situation, Java native Interface can be  used as it provides a way where native applications can communicate with JAVA application

]]>
https://programmerbay.com/introduction-to-jvm-and-its-architecture/feed/ 0
How does JVM convert bytecode into machine code? https://programmerbay.com/how-does-jvm-convert-bytecode-into-machine-code/ https://programmerbay.com/how-does-jvm-convert-bytecode-into-machine-code/#respond Sat, 15 Aug 2020 15:25:04 +0000 https://www.programmerbay.com/?p=4664 Java is known for its platform-independent feature which is based on the principle of “Write once, Run everywhere”.
The reason for being platform-independent is JVM (Java Virtual Machine) that produces bytecode and this bytecode provides the freedom to run anywhere and on any machine where JVM is installed.
However, the execution time slightly decreases as we compare to platform-dependent programming languages such as C, C++.
JVM makes Java codes portable and secure as it provides a sandbox where all the programs run and restrict untrusted code.

Key Terms :

bytecode: It is the intermediate code which is an optimized set of instructions generated by Java Compiler.
JVM( Java Virtual Machine):  It is a program responsible for the execution of bytecode. It provides a Java  Runtime environment to run a Java program.

 

How does a Java Program execute?

Jvm convert code
Figure 1 : How JVM converts bytecode to machine code

  • A Java source file is always is saved with .java extension
  • After Java file is created, Java compiler compiles the code into an intermediate code termed as bytecode with an extension of .class. This bytecode is packaged in a JAR file (Java Archive file)
  • Now, this newly created bytecode is accepted by JVM. JVM stands for Java Virtual Machine that converts the bytecode to native code.
  • This native code can be easily understood by System (OS)

 

JVM Converts Bytecode to Machine Code

Java converts code to machine code
Figure 2 : JVM Architecture

JVM ( Java Virtual Machine ) receives this bytecode which is generated by Java Compiler. In JVM, there are two main components that perform all the jobs to convert the bytecode to native code, Classloader, and Execution Engine.

Classloader   [ Click here to read  detailed working ] :

As the name suggests, it reads .class file (bytecode) and loads necessary files and resources onto JRE. It is responsible for loading, linking, and initialization in order to load, verify, prepare and initialize the class.
JVM uses memory in order to run a program, that memory area is referred to as Runtime Data Area which consists Method Area, Heap, Java Stack, Pc Registers and Native method Stack.

Execution Engine 

After the code successfully is loaded, the main task which is the execution of code is done by Execution Engine.
Execution  Engine is the second components where Interpreter, JIT compiler and Garbage collector comprised.
They are responsible for the execution of code.
  • Interpreter: It reads Java bytecode line by line and accountable for program execution. So, if we compare the performance then interpreter somewhere falls behind the compiler’s code execution.
  • JIT Compiler: It precompiles the portions of bytecode into native code as it is not possible to compile the entire Java program while multiple runtimes checks. Only essential parts are compiled and the remaining code is interpreted by the interpreter. Interpreter directly refers to this precompiled code without reinterpreting it. Hence, It boosts up the performance.

]]>
https://programmerbay.com/how-does-jvm-convert-bytecode-into-machine-code/feed/ 0
program to count a particular word occurrence in a Sequence of string without using loop https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/ https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/#respond Thu, 27 Feb 2020 07:19:02 +0000 https://programmerbay.com/?p=6131 Program:

public class Main {
   static int count = 0;
    String search;
    int len;
    String[] str;
    Main(String[] s,String srch){
str = s;
search = srch;
len = s.length;
    }

    int call_me(int len) {

        if (len < 1) // base case
        {
            return count;
        } else if (str[len].equals(search)) {
            ++count;
        }
        return call_me(len - 1);
    }

    public static void main(String[] args) {
        Main obj;
        String[] str = {"this","is","a","string","and","a","sequence","of","a","string","arr"};
        obj = new Main(str,"a");
        System.out.println(obj.search+" occurred "+obj.call_me(obj.len-1)+" times");

    }
}

Output:

a occurred 3 times

]]>
https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/feed/ 0
Java Exception handling and its hierarchy https://programmerbay.com/java-exception-handling-and-its-hierarchy/ https://programmerbay.com/java-exception-handling-and-its-hierarchy/#respond Sat, 14 Sep 2019 17:29:01 +0000 https://programmerbay.com/?p=5113 What is an Exception?

An exception is an event that occurs when a program fails to achieve the normal flow which leads to the termination of that program. In other orders, When a program doesn’t follow rules or constraints defined in Java language then it is said to be an exception.

What happens when an exception occurred?

new exception
  • When an exception is triggered, the method in which it has occurred creates an object, referred as exception object that contains the information of what type of exception this is and state of the program.
  • After creating an exception object, it hands over to JRE,  this stage is termed as throwing an exception.
  • Now, JRE keeps looking for an appropriate method having a block of codes from call stack (list of methods) to handle that exception called exception handler by tracing back all the way from the method where an error occurred to the appropriate exception handler.
  • Ones an exception handler is found, the exception object is thrown to that handler, this is known as catching an exception. if no handler is found for it, then the program would be terminated.
what happen is

Hierarchy of Exception

The throwable class covers entire exception handling in Java.

Exception Hierarchy

 Throwable class can be classified into two subclasses:-

Exception:  An exception which occurs when the problem is specifically triggered by our program and disrupts the normal flow of that program. For example, ArrayOutOfBound exception, I/O exception and more. In other words, an exception is often caused by a program itself. It is recoverable.

An exception can also be divided into two type:-

  • Unchecked Exception: These exceptions are those exceptions which are not identified at compile time by the compiler. For example, RuntimeException.
  • Checked Exception: Checked exceptions are those exceptions which are identified at the compile time by the compiler. For example, FileNotFound exception.

Error: An error occurs when the system in which our JRE executes has insufficient resources for our own program. For example, stack overflow. It is not recoverable.

]]>
https://programmerbay.com/java-exception-handling-and-its-hierarchy/feed/ 0