Saturday, March 7, 2020

JVM

JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine), JVM Study Materials, Java Exam Prep, Java Guides

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM


It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.

2. An implementation Its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

What it does


The JVM performs following operation:

◉ Loads code
◉ Verifies code
◉ Executes code
◉ Provides runtime environment

JVM provides definitions for the:

◉ Memory area
◉ Class file format
◉ Register set
◉ Garbage-collected heap
◉ Fatal error reporting etc.

JVM Architecture


Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

JVM (Java Virtual Machine), JVM Study Materials, Java Exam Prep, Java Guides

1) Classloader


Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.

2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.

3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

//Let's see an example to print the classloader name  
public class ClassLoaderExample  
{  
    public static void main(String[] args)  
    {  
        // Let's print the classloader name of current class.   
        //Application/System classloader will load this class  
        Class c=ClassLoaderExample.class;  
        System.out.println(c.getClassLoader());  
        //If we print the classloader name of String, it will print null because it is an  
        //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader  
        System.out.println(String.class.getClassLoader());  
    }  
}     

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend the ClassLoader class.

2) Class(Method) Area


Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

3) Heap


It is the runtime data area in which objects are allocated.

4) Stack


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

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine


It contains:

1. A virtual processor

2. Interpreter: Read bytecode stream then execute the instructions.

3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.

Friday, March 6, 2020

Difference between int and Integer in Java?

Oracle Java Study Materials, Oracle Core Java, Oracle Java Tutorial and Material

Both int and Integer are two important data types in Java which often cause confusion between new Java developers. Both int and Integer used to represent numeric data and related to each other in the sense of primitive and Object. Int is a primitive data type that has 32-bit and stores values from  -2^31 to 2^31-1 while Integer is a class that wraps an int primitive inside it. In this article, you will learn why we need Integer Class in Java, particularly, if we already had the int data type, how to convert from int to Integer in Java, and various points on Integer in Java, ranging from basics to advanced BigInteger and AtomicInteger stuff.

Why Integer Class in Java is required?


The first question which comes in a Java trainee's mind is why we have two things int and Integer to represent the same numeric stuff. The reason for having int and Integer is that Many classes in Java work at a Class level and don't accept primitive as parameters.

The classic example is Java Collection framework classes like HashMap in Java doesn't support int primitive type as key, and you can not store int into Vector or ArrayList in Java. To facilitate these operations, Java provides a convenient wrapper class which converts primitive into Object.

How to convert int to Integer in Java?


With the introduction of autoboxing in Java, converting int to Integer in Java is trivial. You don't need to do anything special, and Java will convert an int to Integer automatically wherever requires. for example

Integer i = 30;  //valid from Java5 onwards

Even on method parameters where an Integer is expected, this will work.

public void setInteger(Integer i){}
setInteger(30);

Even if you are working on Java version less than 1.5 like JDK1.4 converting an int to Integer is easy.
see below example of converting int to Integer in JDK1.4

Integer number = new Integer(30); //int to integer in JDK1.4

How to convert Integer to int in Java?


Just like boxing, unboxing is also automatic from JDK5 onwards which makes the conversion of Integer to int in Java trivial. Compiler automatic converts an Integer object into int primitive whenever required as shown below an example of Integer to int in Java:

Integer i = 30;
int j = i; //Integer to int from Java5 onwards

public void setInt(int i);
setInt(i);

For JDK version less than 5 you can convert an Integer object into int in Java by using intValue() method of Integer class as shown in example:

Integer number = new Integer(30);
int j = number.intValue(); //Integer to int in JDK1.4

Difference between int and Integer in Java?


Though both int and Integer in Java easily interchangeable, there is quite a lot of difference between these two, as I have outlined below.

1.int is a primitive while Integer is an object in Java.

2. You can not use int in place of Integer like a key in HashMap, but with Java5, it's possible with autoboxing.

3.int is comparatively faster than Integer in Java.

4. Integer needs to be serialized and converted into bytes to be sent over RMI.

5. You can not assign null to int in Java. below would be compilation error:

    int number = null;

Integer Array vs. int array

You can create an array for both int and Integer in Java, and from Java 5 onwards, you can store Integer in place of int and vice versa as shown in the following example.

int[] intArray = {1,3,4};
Integer[] integerArray = {2, 3, 4};

you can also do like

int[0] = Integer.valueOf(5);

and

Integer[0] = 5;

Both are valid Java 5 onwards.


That's all about the difference between int and Integer in Java. Both represent integral data but there is a difference between them, int is a primitive type while Integer is a wrapper class. It's very important for a Java developer to know about this difference so that he can use both int and Integer class properly and avoid auto-boxing whenever possible.

Thursday, March 5, 2020

Simple Java Date and Time Example - LocalDate and MonthDay

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

The code is self-explanatory, so I won't elaborate on it in detail, but you should notice the use of LocalDate, which is a date without a time or a timezone, as well as the MonthDay class, that just represents a month with a day. Btw, if you have any doubt in understanding any concept or any part of the code then feel free to drop a note and I'll try to explain. If you think an explanation is needed, tell us an I may update the article as well.

package test;

import java.time.LocalDate;
import java.time.MonthDay;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner sysin = new Scanner(System.in);
        System.out.println("Please enter your first premium date, in year, month and day");
        int year = sysin.nextInt();
        int month = sysin.nextInt();
        int day = sysin.nextInt();
        LocalDate premiumStartDate = LocalDate.of(year, month, day);
        System.out.printf("Your first premium date was %s %n",
                                      premiumStartDate);
        System.out.printf("You have been paying premium from last %s years %n",
                                      getPaidYears(premiumStartDate));

        MonthDay primiumDay = MonthDay.from(premiumStartDate);
        System.out.printf("Your next premium is due on %s %n",
                                      getNextPremiumDate(primiumDay)) ;
    }

    /**
     * Calculate number of years from the first premium paid
     * good example of how to find days, month and year
     * between two dates in Java.
     * @param issueDate
     * @return number of years from first payment
     */
    private static long getPaidYears(LocalDate issueDate) {
        return ChronoUnit.YEARS.between(issueDate, LocalDate.now());
    }

    /**
     * Calculate Next premium date, return this years date if premium day
     * is today or after today, otherwise next years date
     * @param premiumDay
     * @return  next premium date
     */
    private static LocalDate getNextPremiumDate(MonthDay premiumDay) {
        LocalDate today = LocalDate.now();
        LocalDate nextPremiumDay = premiumDay.atYear(today.getYear());
        if(nextPremiumDay.isAfter(today) || nextPremiumDay.equals(today))
            return nextPremiumDay;
        return nextPremiumDay.plusYears(1);
    }
}

Output
Please enter your first premium date, in year, month and day
2010
02
15
Your first premium date was 2010-02-15
You have been paying premium from last 4 years
Your next premium is due on 2015-02-15

Please enter your first premium date, in year, month and day
2012
02
25
Your first premium date was 2012-02-25
You have been paying premium from last 2 years
Your next premium is due on 2014-02-25

Invalid value
2012
25
02
Exception in thread "main" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 25
               at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:309)
               at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:703)
               at java.time.LocalDate.of(LocalDate.java:259)

That's all about how to use Date and Time in Java 8. You should use LocalDate if your are dealing with just dates like BirthDate, Holiday, or any other date like premium start date, and premium renewal date.

Wednesday, March 4, 2020

Thread, code and data - Story of a Multithreading Program in Java

Oracle Java Thread, Oracle Java Multithreading, Oracle Core Java, Oracle Java Prep

There are certain things, which you don't learn on academics or training class, you develop those understanding after few years of work experience, and then you realize, it was very basic, how come I had missed that all those years. Understanding of how a multi-threaded Java program executes is one of such things. You definitely have heard about threads, how to start a thread, how to stop a thread, definitions like its independent path of execution, all funky libraries to deal with inter-thread communication, yet when it comes to debugging a multithreaded Java program, you struggle.

At least I can say this from my personal experience. Debugging is in my opinion real trainer, you will learn a subtle concept and develop an understanding which will last long, only through debugging.

In this article, I am going to talk about three important things about any program execution, not just Java, Thread, code, and data.

Once you have a good understanding of how these three work together, it would be much easier for you to understand how a program is executing, why a certain bug comes only sometimes, why a particular bug comes all time and why a particular bug is truly random.

How Thread, Code, and Data work together


What is a program? In short, it's a piece of code, which is translated into binary instruction for  CPU. CPU is the one, who executes those instructions e.g. fetch data from memory, add data, subtract data etc. In short, what you write is your program, the Code.

What varies between the different execution of the same program, is data. It's not just mean restarting the program, but a cycle of processing, for example, for an electronic trading application, processing one order is one execution. You can process thousands of order in one minute and with each iteration, data varies.

One more thing to note is that you can create Threads in code, which will then run parallel and execute code, which is written inside their run() method. The key thing to remember is threads can run parallel.

When a Java program starts, one thread known as main thread is created, which executed code written inside the main method, if you create a thread, then those threads are created and started by the main thread, once started they start executing code written in their run() method.

Oracle Java Thread, Oracle Java Multithreading, Oracle Core Java, Oracle Java Prep

So if you have 10 threads for processing Orders, they will run in parallel. In short, Thread executes code, with data coming in. Now, we will see three different kinds of issue, we talked about

1) Issues, which always comes

2) Issues, which comes only sometimes, but consistent with the same input

3) Issues, which is truly random

Issue one is most likely due to faulty code, also known as programming errors e.g. accessing the invalid index of an array, accessing Object's method after making it null or even before initializing it. They are easy to fix, as you know their place.

 You just need to have knowledge of programming language and API to fix this error.

The second issue is more likely to do with data than code. Only sometimes, but always come with the same input, could be because of incorrect boundary handling, malformed data like Order without certain fields for example price, quantity etc.

Your program should always be written robustly so that it won't crash if incorrect data is given as input. The impact should only be with that order, the rest of the order must execute properly.

The third issue is more likely coming because of multithreading, where order and interleaving of multiple thread execution causing race conditions or deadlocks. They are random because they only appear if certain random things happen e.g. thread 2 getting CPU before thread 1, getting a lock on incorrect order.

Remember, Thread scheduler and Operating system are responsible for allocating CPU to threads, they can pause them, take CPU from them at any time, all these can create a unique scenario, which exposes multithreading and synchronization issue.

Your code never depends upon the order of thread etc, it must be robust to run perfectly in all condition.

In short, remember thread executes code with data given as input. Each thread work with the same code but different data. While debugging issue, pay attention to all three, Thread, Code and data.

Tuesday, March 3, 2020

How to create and execute JAR file in Java – Command line Eclipse Netbeans

Oracle Java, Oracle Java Tutorial and Materials, Oracle Java Prep

Creating JAR file in java from command prompt is always been little tricky for many of us even if IDE like Netbeans and Eclipse provide support to export java program as JAR file simply because we don’t create jar often and not familiar with manifest file or jar command as whole. JAR file in Java is a kind of zip file which holds all contents of a Java application including Class files, resources such as images, sound files and optional Manifest file. JAR stands for Java Archive and provides a platform independent deliverable for java programs, libraries and framework. you can execute same jar file in any operating system e.g. Windows 7, windows 8, Macintosh or Linux. Apart from platform independence and standard delivery method jar file also provides compression of contents which results in faster download if you are downloading java program from internet specially in case of mobile devices where you install Java program by OTA. In this article we will some JAR command examples and learn how to create and execute jar file, how to view contents of jar file from command prompt and Eclipse and Netbeans.

How to create jar file in Java form command prompt


Example to create and execute JAR file in Java from Command line Eclipse and Netbeansjar command in Java allows you to create jar file from command prompt, what is required is that you must have jar command included in System PATH variable. you can check this by typing "jar" in command prompt if it doesn't throw error as "jar is not recognized as an internal or external command" they you are ready to go. When you create jar file in Java, command also creates Manifest file which is optional and you can control whether to create it or not by jar command line options, but if you want to create executable jar file they you must need Manifest file which we will discuss in further sections. Now here is jar command example to create jar file from command prompt, this will work both in windows and Linux operating system.

JAR command Examples in Java


javin@localhost:~/Java jar -cvf HelloWorld.jar HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

This command will crate Helloworld. jar which contains Helloworld.class file. this will also create manifest file but without Main-Class entry as shown below:

javin@localhost:~/Java cat MANIFEST.MF
Manifest-Version: 1.0
Created-By: 1.6.0-beta2 (Sun Microsystems Inc.)

This jar can not be executed and you will get error when you try to run this jar file:

javin@localhost:~/Java java -jar HelloWorld.jar
Failed to load Main-Class manifest attribute from HelloWorld.jar

You just need to provide Main-Class entry to get rid of this error which we will see in coming Section.

How to Create an executable JAR file in Java


To create an executable JAR in Java, you need to provide a manifest file and include your Main Class in Manifest. When you create jar file , jar command also creates manifest file inside META-INF as MANIFEST.MF but doesn't create Main-Class entry which is required for executable jar file. You can create executable jar file in Java by two ways either provide a self created Manifest file or specify entry point using "-e" jar option. If you provide external Manifest file than you need to use jar -m option to include that manifest file inside jar. Let's see example of both ways to create executable jar file in Java.

Executable JAR File Example with External Manifest

1.Create MANIFEST.MF file by using any text editor e.g. notepad in windows or Vim in Unix and add following entry in file, remember last line must end with either new line or carriage return:

Manifest-version: 1.0
Main-Class: HelloWorld

Important thing to remember is that we need to specified full classified class name here. suppose if our main class was inside com/example/HelloWorld than we should have to specify com.example.HelloWorld here, don't put .class extension here its not required. Apart from specifying Main-Class you can also specify Java Classpath in Manifest file which is important if your application is depended on external library jars. "Classpath" entry supersede both -cp and CLASSPATH environment variable.

2. Execute following jar command to create executable jar

javin@localhost:~/Java jar -cvfm HelloWorld.jar MANIFEST.MF HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

here -m is used for including manifest file and remember specify name of manifest file after jar name. now you have an executable jar file in java which you run by command specified earlier.

Creating Executable JAR File By entry point

This seems to me an easy way to create executable jars in Java, as you need not have to create manifest file explicitly and it will be create by jar command itself along with Main-Class entry. What you need to provide is a new jar option "-e" and you main class name while running jar command. here is example of jar command with entry option:

javin@localhost:~/Java jar -cvfe HelloWorld.jar HelloWorld HelloWorld.class
added manifest
adding: HelloWorld.class(in = 450) (out= 311)(deflated 30%)

jar -e for entry point and entry point or main class name should come after jar file name and before directory or file needs to be included in JAR. You can now run your executable jar file by issuing "java -jar" command as shown in following example:

javin@localhost:~/Java java -jar HelloWorld.jar
Executing Java Program from JAR file

How to execute Java Program from Jar file

Executing jar program from jar archive is very easy one thing required is jar must be executable and must have Main-Class entry in MANIFEST.MF file. here is a Java command example for running java program from jar file:

javin@localhost:~/Java java -jar HelloWorld.jar
Executing Java Program from JAR file

here we have specified jar file name with -jar option and it will run main class declared as “Main-Class” attribute in manifest file.

How to view contents of a JAR file in Java

jar command in Java allows you to view files and directories inside of a jar file without extracting or unzipping original jar. "-t" jar option is used to list files from jar archive as shown in jar command example below:

javin@localhost:~/Java jar -tvf HelloWorld.jar
0 Wed Dec 07 22:36:12 VET 2011 META-INF/
95 Wed Dec 07 22:36:12 VET 2011 META-INF/MANIFEST.MF
450 Wed Dec 07 21:36:04 VET 2011 HelloWorld.class

here "-t" for listing and "-v" and "-f" for verbose and jar file name.

How to extract contents of JAR File


use jar option "-v" for extracting files form JAR files as shown in jar command example below:

javin@localhost:~/Java jar -xvf HelloWorld.jar
created: META-INF/
inflated: META-INF/MANIFEST.MF
inflated: HelloWorld.class

here -x for extracting , -v is for verbose and -f specify jar file name.

How to create jar file in Eclipse


Creating JAR file in  Eclipse IDE is a cakewalk once you know the process. here is step by step guide of creating JAR file from Eclipse IDE: In Jar file main class is specified as “Main-Class” attribute inside manifest file and used as program entry point if you double click on JAR or run jar from java command.

1) Select Project for which you want to create jar file.
2) Go to File Menu and select Export
3) Expand Java folder and select JAR file

Now you just need to click next and follow instruction as displayed. you can select what contents you want to export to jar file and specify Main Class entry as well. If you like Eclipse IDE then you may like my earlier post on eclipse as well e.g. Java debugging tips in Eclipse.

How to create jar file in Netbeans


In Netbeans to create jar file you need to build the project which execute project ant file and creates JAR file inside dist folder. You can go on properties of project and specify main class there which will be run when you run the project and same will be used to create “Main-Class” attribute in JAR file.

jar is not recognized as an internal or external command


if you get this error while executing jar command from command prompt in Windows or Unix it means your Java Path is not set properly. JAR command is a binary which resides in JDK_HOME/bin folder where JDK_HOME is JDK installation directory. In order to use jar command from command prompt this bin folder must be in your System's PATH variable. Don't worry if its not there in PATH you can check this link to Set PATH for Java in Windows and Unix.It shows how you can do it in both Windows and Unix. Once your PATH is property set, you will see following output when you execute jar command from command  line:

javin@localhost:~ jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
-c  create new archive
-t  list table of contents for archive

and now you are ready to use jar from command prompt.

WAR and EAR -  related JAR like fies in Java


WAR file

WAR file in Java stands for Web application archive and it is used to package a Java application together you can package all your Servlet, JSP, CSS, images, html in one WAR file and then deploy it to any Java web or application server like Tomcat, Weblogic or webshere. WAR files provide a clean and faster way to package and deploy Java web application just like JAR file provides for core java apps. Since WAR file also compacts resources inside it is comparatively download faster than downloading individual components.

EAR file

EAR file stands for Enterprise Java Archive and used to package an Enterprise Java application, like earlier WAR and JAR file. What separates EAR archive to WAR file is inclusion of Enterprise Java Beans(EJB). EAR file contains all web resources including Servlet, JSP, html, javascript, css, images along-with EJB. You can not deploy EAR files into web servers like Tomcat because it doesn't support EJB and can only be deploy-able in Application servers like WebSphere or Weblogic.

JAR File format in Java


Few words about java jar file format, its similar to zip format and use .jar extension. you can open JAR file in windows by using either winzip or winrar zip utilities.

That’s all on how to create jar file from command line, Eclipse, Netbeans. How to extract contents, how to run Java program from jar file etc. Let me know if you face any issue while creating JAR file in java.

Monday, March 2, 2020

How to parse String to Enum in Java - Convert Enum to String with Example

Oracle Java Study Material, Oracle Java Learning, Oracle Certifications, Core Java

Converting Enum into String and parsing String to Enum in Java is becoming a common task with growing use of Enum. Enum is very versatile in Java and preferred the choice to represent bounded data and since is almost used everywhere to carry literal value it's important to know how to convert Enum to String in Java.

Enum to String to Enum in Java


This article is in continuation of other conversion-related posts e.g. how to convert Date to String in Java

As these are common needs and having the best way to do things in mind saves lot of time while coding.

Convert Enum to String in Java Example


Enum classes by default provide valueOf (String value) method which takes a String parameter and converts it into an enum. String name should match with text used to declare Enum in Java file. Here is a complete code example of String to Enum in Java
Code Example String to Enum:

/**
 * Java Program to parse String to Enum in Java with examples.
 */
public class EnumTest {

    private enum LOAN {
        HOME_LOAN {
            @Override
            public String toString() {
                return "Always look for cheaper Home loan";

            }
        },
        AUTO_LOAN {
            @Override
            public String toString() {
                return "Cheaper Auto Loan is better";
            }
        },
        PEROSNAL_LOAN{
            @Override
            public String toString() {
                return "Personal loan is not cheaper any more";
            }
        }
    }

    public static void main(String[] args) {    

        // Exmaple of Converting String to Enum in Java
        LOAN homeLoan = LOAN.valueOf("HOME_LOAN");
        System.out.println(homeLoan);

        LOAN autoLoan = LOAN.valueOf("AUTO_LOAN");
        System.out.println(autoLoan);

        LOAN personalLoan = LOAN.valueOf("PEROSNAL_LOAN");
        System.out.println(personalLoan);   
    }
}

Output:
Always look for cheaper Home loan
Cheaper Auto Loan is better
Personal loan is not cheaper anymore

Convert Enum to String in Java Example


Now let's do opposite convert an Enum into String in Java, there are multiple ways to do it one way is to return exact same String used to declare Enum from toString() method of Enum, otherwise if you are using toString() method for another purpose then you can use default static name() method to convert an Enum into String. Java by default adds name() method into every Enum and it returns exactly same text which is used to declare enum in Java file.

Code Example Enum to String

public static void main(String[] args) {    

        // Java example to convert Enum to String in Java
         String homeLoan = LOAN.HOME_LOAN.name();
        System.out.println(homeLoan);

        String autoLoan = LOAN.AUTO_LOAN.name();
        System.out.println(autoLoan);

        String personalLoan = LOAN.PERSONAL_LOAN.name();
        System.out.println(personalLoan);     
}

Output:
HOME_LOAN
AUTO_LOAN
PERSONAL_LOAN

That’s all on How to parse String to Enum in Java and convert Enum to String object . This tip will help you to quickly convert your data between two most versatile types Enum and String in Java. If you know any other way to change String to Enum in java then please let us know.