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.
Tuesday, October 13, 2020
Java Virtual Machine (JVM) Stack Area
Monday, October 12, 2020
Verification in Java (JVM)
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.
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));
}
}
Friday, October 9, 2020
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.
Wednesday, October 7, 2020
Collator compare(Object, Object) method in Java with Example
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:
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.
When to use what?
- 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).
- 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.