Tuesday, October 13, 2020

JVM

Java Virtual Machine (JVM) Stack Area

For every thread, JVM creates a separate stack at the time of thread creation. The memory for a Java Virtual Machine stack does not need to be contiguous. The Java virtual machine only performs two operations directly on Java Stacks: it pushes and pops frames. And stack for a particular thread may be termed as Run – Time Stack. Each and every method call performed by that thread is stored in the corresponding run time stack including parameters, local variables, intermediate computations, and other data. After completing a method, corresponding entry from the stack is removed. After completing all method calls the stack becomes empty and that empty stack is destroyed by the JVM just before terminating the thread. The data stored in the stack is available for the corresponding thread and not available to the remaining threads. Hence we can say local data is thread safe. Each entry in the stack is called Stack Frame or Activation Record.

Java Virtual Machine (JVM), Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Study Material

Stack Frame Structure


The stack frame basically consists of three parts: Local Variable Array, Operand Stack & Frame Data. When JVM invokes a Java method, first it checks the class data to determine the number of words (size of the local variable array and operand stack, which are measured in words for each individual method) required by the method in the local variables array and operand stack. It creates a stack frame of the proper size for invoked method and pushes it onto the Java stack.

1. Local Variable Array (LVA):


◉ The local variables part of stack frame is organized as a zero-based array of words.

◉ It contains all parameters and local variables of the method.

◉ Each slot or entry in the array is of 4 Bytes.

◉ Values of type int, float, and reference occupy 1 entry or slot in the array i.e. 4 bytes.

◉ Values of double and long occupy 2 consecutive entries in the array i.e. 8 bytes total.

◉ Byte, short and char values will be converted to int type before storing and occupy 1 slot i.e. 4 Bytes.

◉ But the way of storing Boolean values is varied from JVM to JVM. But most of the JVM gives 1 slot for Boolean values in the local variable array.

◉ The parameters are placed into the local variable array first, in the order in which they are declared.

For Example: Let us consider a class Example having a method bike() then local variable array will be as shown in below diagram:

// Class Declaration
class Example
{
  public void bike(int i, long l, float f, 
               double d, Object o, byte b)
  {
    
  } 

}     

Java Virtual Machine (JVM), Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Study Material

2. Operand Stack (OS):


◉ JVM uses operand stack as work space like rough work or we can say for storing intermediate calculation’s result.

◉ Operand stack is organized as array of words like local variable array. But this is not accessed by using index like local variable array rather it is accessed by some instructions that can push the value to the operand stack and some instructions that can pop values from operand stack and some instructions that can perform required operations.

◉ For Example: Here is how a JVM will use this below code that would subtract two local variables that contain two ints and store the int result in a third local variable:

Java Virtual Machine (JVM), Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Study Material

◉ So here first two instructions iload_0 and iload_1 will push the values in operand stack from local variable array. And instruction isub will subtract these two values and stores the result back to the operand stack and after istore_2 the result will pop out from the operand stack and will store into local variable array at position 2.

Java Virtual Machine (JVM), Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Study Material

3. Frame Data (FD):


◉ It contains all symbolic reference (constant pool resolution) and normal method return related to that particular method.

◉ It also contains a reference to Exception table which provide the corresponding catch block information in the case of exceptions.

Monday, October 12, 2020

Verification in Java (JVM)

Verification Java (JVM), Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Exam Prep

After the class loader in the JVM loads the byte code of .class file to the machine the Bytecode is first checked for validity by the verifier and this process is called as verification. The verifier performs as much checking as possible at the Linking so that expensive operation performed by the interpreter at the run time can be eliminated. It enhances the performances of the interpreter.

Some of the checks that verifier performs:

◉ Uninitialized Variables

◉ Access rules for private data and methods are not violated.

◉ Method calls match the object Reference.

◉ There are no operand stack overflows or underflows.

◉ The arguments to all the Java Virtual Machine instructions are of valid types.

◉ Ensuring that final classes are not subclassed and that final methods are not overridden

◉ Checking that all field references and method references have valid names, valid classes, and a valid type descriptor.

If any of these checks fails JVM throws a “java.lang.VerifyError” error. However, we can disable these checks using

java -noverify VerifyOracleJavaFile

One might think how a program could have been manipulated since compiler checks these above validations before generating .class file. But the class file is vulnerable to change before JVM loads it. The bytecode used in the class file is well documented and someone having some knowledge of hex can change the values of hex codes in the .class file thus change the behavior of the program.

Verification Java (JVM), Oracle Java Certification, Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Exam Prep

For example : The Applets in the web browsers do not download source code instead they download precompiled class files. The browser on your computer determines whether this class file is trustworthy to run or the file have been exploited by a “hostile compiler”.

Consider this Simple Program

// A Java program to demonstrate working 

// of the verification process 

class VerifyOracleJavaFile 

// your initial bank bal 

private float bal; 

// Method to deposit money 

float depositBalance(int bal) 

int myBal = bal; 

this.bal += myBal; 

return this.bal; 

// Driver Method 

public static void main(String[] args) 

VerifyOracleJavaFile obj = new VerifyOracleJavaFile(); 

System.out.println(obj.depositBalance(4000)); 

Output
4000.0

Then execute this in command line to see the byte code in mnemonic form:-

javap -c VerifyOracleJavaFile

Output:

float depositBalance(int);
    Code:
       0: iload_1
       1: istore_2
       2: aload_0
       3: dup
       4: getfield      #2                  // Field bal:F
       7: iload_2
       8: i2f
       9: fadd
      10: putfield      #2                  // Field bal:F
      13: aload_0
      14: getfield      #2                  // Field bal:F
      17: freturn

Here if we change the initial value of myBal or leave it uninitialized using a hex editor, unexpected results are returned. Java verification process protects us from all of these pitfalls.

Friday, October 9, 2020

JVM

How JVM Works – JVM Architecture?

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java enabled system without any adjustment. This is all possible because of JVM.

When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM.

Oracle Java Learning, Oracle Java Certification, Oracle Java Prep,  JVM, JVM Architecture

Class Loader Subsystem

It is mainly responsible for three activities.

◉ Loading
◉ Linking
◉ Initialization

Loading : The Class loader reads the .class file, generate the corresponding binary data and save it in method area. For each .class file, JVM stores following information in method area.

◉ Fully qualified name of the loaded class and its immediate parent class.
◉ Whether .class file is related to Class or Interface or Enum
◉ Modifier, Variables and Method information etc.

After loading .class file, JVM creates an object of type Class to represent this file in the heap memory. Please note that this object is of type Class predefined in java.lang package. This Class object can be used by the programmer for getting class level information like name of class, parent name, methods and variable information etc. 

// A Java program to demonstrate working of a Class type 
// object created by JVM to represent .class file in 
// memory. 
import java.lang.reflect.Field; 
import java.lang.reflect.Method; 

// Java code to demonstrate use of Class object 
// created by JVM 
public class Test 
public static void main(String[] args) 
Student s1 = new Student(); 

// Getting hold of Class object created 
// by JVM. 
Class c1 = s1.getClass(); 

// Printing type of object using c1. 
System.out.println(c1.getName()); 

// getting all methods in an array 
Method m[] = c1.getDeclaredMethods(); 
for (Method method : m) 
System.out.println(method.getName()); 

// getting all fields in an array 
Field f[] = c1.getDeclaredFields(); 
for (Field field : f) 
System.out.println(field.getName()); 

// A sample class whose information is fetched above using 
// its Class object. 
class Student 
private String name; 
private int roll_No; 

public String getName() { return name; } 
public void setName(String name) { this.name = name; } 
public int getRoll_no() { return roll_No; } 
public void setRoll_no(int roll_no) { 
this.roll_No = roll_no; 

Output:

Student
getName
setName
getRoll_no
setRoll_no
name
roll_No

Note : For every loaded .class file, only one object of Class is created.

Student s2 = new Student();
// c2 will point to same object where 
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true

Linking : Performs verification, preparation, and (optionally) resolution.

◉ Verification : It ensures the correctness of .class file i.e. it check whether this file is properly formatted and generated by valid compiler or not. If verification fails, we get run-time exception java.lang.VerifyError.

◉ Preparation : JVM allocates memory for class variables and initializing the memory to default values.

◉ Resolution : It is the process of replacing symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity.

Initialization : In this phase, all static variables are assigned with their values defined in the code and static block(if any). This is executed from top to bottom in a class and from parent to child in class hierarchy.
In general, there are three class loaders :

◉ Bootstrap class loader : Every JVM implementation must have a bootstrap class loader, capable of loading trusted classes. It loads core java API classes present in JAVA_HOME/jre/lib directory. This path is popularly known as bootstrap path. It is implemented in native languages like C, C++.
◉ Extension class loader : It is child of bootstrap class loader. It loads the classes present in the extensions directories JAVA_HOME/jre/lib/ext(Extension path) or any other directory specified by the java.ext.dirs system property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class.
◉ System/Application class loader : It is child of extension class loader. It is responsible to load classes from application class path. It internally uses Environment Variable which mapped to java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class.

// Java code to demonstrate Class Loader subsystem 
public class Test 
public static void main(String[] args) 
// String class is loaded by bootstrap loader, and 
// bootstrap loader is not Java object, hence null 
System.out.println(String.class.getClassLoader()); 

// Test class is loaded by Application loader 
System.out.println(Test.class.getClassLoader()); 
}  

Output:

null
sun.misc.Launcher$AppClassLoader@73d16e93

Note : JVM follow Delegation-Hierarchy principle to load classes. System class loader delegate load request to extension class loader and extension class loader delegate request to boot-strap class loader. If class found in boot-strap path, class is loaded otherwise request again transfers to extension class loader and then to system class loader. At last if system class loader fails to load class, then we get run-time exception java.lang.ClassNotFoundException.

Oracle Java Learning, Oracle Java Certification, Oracle Java Prep,  JVM, JVM Architecture

JVM Memory.

Method area : In method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource.

Heap area : Information of all objects is stored in heap area. There is also one Heap Area per JVM. It is also a shared resource.

Stack area : For every thread, JVM create one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which store methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be destroyed by JVM. It is not a shared resource.

PC Registers : Store address of current execution instruction of a thread. Obviously each thread has separate PC Registers.

Native method stacks : For every thread, separate native stack is created. It stores native method information.

Oracle Java Learning, Oracle Java Certification, Oracle Java Prep,  JVM, JVM Architecture

Execution Engine

Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and information present in various memory area and execute instructions. It can be classified in three parts :-

◉ Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required.

◉ Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the entire bytecode and changes it to native code so whenever interpreter see repeated method calls,JIT provide direct native code for that part so re-interpretation is not required,thus efficiency is improved.

◉ Garbage Collector : It destroy un-referenced objects.

Java Native Interface (JNI) :

It is an interface which interacts with the Native Method Libraries and provides the native libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to hardware.

Native Method Libraries :

It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

Wednesday, October 7, 2020

Collator compare(Object, Object) method in Java with Example

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Exam Prep

The compare() method of java.text.Collator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result.

Syntax:

public int compare(Object o1, Object o2)

Parameter: This method takes two objects between which comparison is going to take place.

Return Value: if the first object is equals, grater or lesser than the other object than it will return zero, positive and negative value respectively.

Exception: This method throws ClassCastException if the arguments cannot be cast to Strings.

Below are the examples to illustrate the compare() method:

Example 1:

// Java program to demonstrate 

// compare() method 

import java.text.*; 

import java.util.*; 

import java.io.*; 

public class GFG { 

public static void main(String[] argv) 

try { 

// Creating and initializing Collator Object 

Collator col = Collator.getInstance(); 

// Creating an initializing 

// object for comparison 

Object obj1 = "ab"; 

// Creating an initializing 

// Object for comparison 

Object obj2 = "Ab"; 

// compare both object 

// using compare() mehtod 

int i 

= col.compare((String)obj1, (String)obj2); 

// display result 

if (i < 0) 

System.out.println("ab is less than Ab"); 

else if (i > 0) 

System.out.println("ab is greater than Ab"); 

else

System.out.println("ab is equal to Ab"); 

catch (ClassCastException e) { 

System.out.println("Exception thrown : " + e); 

Output:


ab is less than Ab

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Exam Prep
Example 2:


// Java program to demonstrate 
// compare() method 

import java.text.*; 
import java.util.*; 
import java.io.*; 

public class GFG { 
public static void main(String[] argv) 
try { 

// Creating and initializing Collator Object 
Collator col = Collator.getInstance(); 

// Creating an initializing object for comparison 
Object obj1 = "ab"; 

// Creating an initializing Object for comparison 
Object obj2 = 1234; 

// compare both object 
// using compare() mehtod 
int i = col.compare((String)obj1, (String)obj2); 

// display result 
if (i < 0) 
System.out.println("ab is less than Ab"); 
else if (i > 0) 
System.out.println("ab is greater than Ab"); 
else
System.out.println("ab is equal to Ab"); 

catch (ClassCastException e) { 

System.out.println("Exception thrown : " + e); 
}
}
}

Output:


Exception thrown :
 java.lang.ClassCastException:
 java.lang.Integer cannot be cast to java.lang.String

Monday, October 5, 2020

Difference between Abstract Class and Interface in Java

Prerequisite

Interface

An interface is an abstract "class" that is used to group related methods with "empty" bodies: To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends ).

Abstract Class

Abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

Abstraction: Hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction.

Abstract class vs Interface

1. Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also.

2. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.

3. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.

4. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.

5. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”.

6. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.

7. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

// Java program to illustrate the 
// concept of abstract class 

import java.io.*; 

// abstract class 
abstract class Shape 
// declare fields 
String objectName = " "; 
Shape(String name) 
this.objectName = name; 
// declare non-abstract methods 
// it has default implementation 
public void moveTo(int x, int y) 
System.out.println(this.objectName + " " + "has been moved to"
+ " x = " + x + " and y = " + y); 
// abstract methods which will be 
// implemented by its subclass(es) 
abstract public double area(); 
abstract public void draw(); 

class Rectangle extends Shape 
int length, width; 
// constructor 
Rectangle(int length, int width, String name) 
super(name); 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle extends Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius, String name) 
super(name); 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape class reference. 
Shape rect = new Rectangle(2,3, "Rectangle"); 
System.out.println("Area of rectangle: " + rect.area()); 
rect.moveTo(1,2); 
System.out.println(" "); 
// creating the Objects of circle class 
Shape circle = new Circle(2, "Cicle"); 
System.out.println("Area of circle: " + circle.area()); 
circle.moveTo(2,4); 

Output:

Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2
 
Area of circle: 6.28
Cicle has been moved to x = 2 and y = 4

In you don’t have any common code between rectangle and circle then go with interface.

// Java program to illustrate the 
// concept of interface 
import java.io.*; 

interface Shape 
// abstract method 
void draw(); 
double area(); 

class Rectangle implements Shape 
int length, width; 
// constructor 
Rectangle(int length, int width) 
this.length = length; 
this.width = width; 
@Override
public void draw() 
System.out.println("Rectangle has been drawn "); 
@Override
public double area() 
return (double)(length*width); 

class Circle implements Shape 
double pi = 3.14; 
int radius; 
//constructor 
Circle(int radius) 
this.radius = radius; 
@Override
public void draw() 
System.out.println("Circle has been drawn "); 
@Override
public double area() 
return (double)((pi*radius*radius)/2); 

class GFG 
public static void main (String[] args) 
// creating the Object of Rectangle class 
// and using shape interface reference. 
Shape rect = new Rectangle(2,3); 
System.out.println("Area of rectangle: " + rect.area()); 

// creating the Objects of circle class 
Shape circle = new Circle(2); 
System.out.println("Area of circle: " + circle.area()); 

output

Area of rectangle: 6.0
Area of circle: 6.28

When to use what?


Consider using abstract classes if any of these statements apply to your situation:

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep

  • In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
  • You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
  • You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:

  • It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
  • A class can implement more than one interface. It is called multiple inheritance.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

Friday, October 2, 2020

Difference between Inheritance and Polymorphism in Java and Object Oriented Programming

Both Inheritance and Polymorphism are key OOP concepts and similar to Abstraction and Encapsulation, they are also closely related to each other. Because of their similarities, many OOP programmers, especially beginners get confused between Inheritance and Polymorphism. Even though they are closely related and you need Inheritance to support runtime Polymorphism they are a totally different concept. Inheritance refers to the ability for classes or objects to inherit properties of other classes or interfaces. It means you can write code for common functionalities and reuse it at different places by just using Inheritance and not re-writing those codes again and again. For example, you can write code to

Inheritance vs Polymorphism in Java and Object-Oriented Programming

Let's revisit some key differences between Inheritance and Polymorphism in object-oriented programming

1) Class vs Object

Inheritance is used to define a class or interface hierarchy. You extract common functionality on superclass and allow derived classes to get more specific by adding specific functionality. On the other hand, Polymorphism allows you to do the same operation differently depending upon which context and which object is doing the operation.

2)  Code Reuse

One of the key advantages of Inheritance is code reuse. You don't need to write the same code again and again if it is needed by multiple classes. You can extract the common functionality on the base class and let other classes simply use inheritance to get that functionality. In another word, it reduces the amount of duplicate code and promotes DRY practice.

For example, if you are designing a class hierarchy for Finance and Insurance industry, you can create a base class called Insurance, which should have basic properties like covered, the sum assured, premium, etc.

Now, if your application needs to support automobile insurance like the CarInsurance, it just needs to extend the Insurance base class to add specific details required by car insurance companies like the registration number of the car, brand, etc.

Similarly, Health Insurance applications can reuse the same base class for calculating premiums, keeping a record of sum assured, and other basic details. They can further enrich the derived class by adding more specific details required by health insurance companies like pre-existing diseases, co-payment details, etc.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

Polymorphism can also come handy here to write code for calculating premiums. Assuming, the premium is calculated differently for different types of insurance then you can override the calculatePremium() method in derived or subclasses to represent different types of premium calculation.

The benefit of using Polymorphism here is that all the common functionality like report generations, sending premium receipts, or premium reminders can still use the same the calculatePreimum() method for performing their duty. They don't need to worry about the fact that different types of insurance are calculating premium using different formulas.

3)  Flexibility

If Inheritance provides "code re-usability" then Polymorphism provides the "flexibility" to your code. As I mentioned in my previous example, you can add a new kind of Insurance without re-writing code to generate receipts, premium reminders, and other kinds of reports.
By using Polymorphism, you can encapsulate the code which is different inside the same method declared by the superclass. The Clean Code by Uncle Bob has a good write up and example on this.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

4)  Right Usage

One of the best practices in the OOP world is using Inheritance for defining type hierarchies using the interface. This is also advised in Effective Java 2nd Edition by Joshua Bloch. By defining types, you create a path for Polymorphism.

5) extends vs implements

Inheritance in Java is implemented using "extends" and "implements" keyword. A class can extend another class or implement one or more interfaces. When it does that, the parent-child relationship is established between two classes or interfaces.

For example, in the following code, the MyClass is now a child or both Canvas and Runnable:

public class MyClass extends Canvas implements Runnable{

@Overide
public void paint(Graphics g){
   ... some code
  }

@Override
public void run(){
  ... some code
  }

}

This means you a reference variable of Runnable or Canvas can point to an object of MyClass and if you call paint() or run() method then these methods will be called instead of paint() method defined in Canvas and run() method defined in Runnable. This is the power of Polymorphism which comes from Inheritance.

Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Material, Java Prep, Java Certification

Source: javarevisited.blogspot.com