Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to Create, Compile and Execute a Java program

Introduction : -
Java is extensively used programming language. It is been loved by many programmers from beginners to experts. Java is surely programming language of the future. If we look into the phases of program development, we come across many phases such as:





Step 1 : Creation of a Java program :-
By creating of a Java program we mean of writing of a Java program on any editor or IDE. This includes modifying of the program on editor, even after program has been written once. Creation of a Java program is not limit to only write program on editor and than leave it. Generally, creating of a Java program means writing a program on a editor or IDE, making all the corrections needed and than saving the program on secondary storage device as hard drive. After creating a Java program you should provide .java extension to file. It signifies that the particular file is a Java source code. Also , whatever progress we do from writing, editing , storing and providing .java extension to a file , it basically comes under creating of a Java program.

















Step 2 : Compiling a Java Program
Our next step after creation of program is the compilation of Java program. Generally Java program which we have created in step 1 with a .java extension, it is been compiled by the compiler. Suppose if we take example of our program say WelcomeJavaPrograms.java, when we want to compile this we use command such as javac. We can call it as The Java compiler. After opening command prompt or shell console we compile Java program with .java extension as
javac WelcomeJavaPrograms.java.

After executing the javac command, if no errors occur in our program we get a .class file which contains the bytecode. It means that the compiler has successfully converted Java source code to bytecode. Generally bytecode is been used by the JVM to run a particular application. Java Virtual Machine or JVM is a virtual machine that lies between our bytecode and underlying operating system. The final bytecode created is the executable file which only JVM understands.


















Java source code with .java extension is the high level programming language that only a programmer understands. While bytecode produced after compilation is the low-level language that only JVM understands. JVM is implemented on many operating systems which helps programmer to just compile program once, because the same .class file can be executed on different platforms with same JVM. This portion also provides portabilty feature, that you don't have to write again-and-again Java source code for the different platforms. As Java compiler is invoked by javac command, the JVM is been invoked by java command. On the console window you have to type :

java WelcomeJavaPrograms
This command will invoke the JVM to take further steps for execution of Java program.






















Step 3 : Program loading into memory by JVM:-
JVM requires memory to load the .class file before its execution. The process of placing a program in memory in order to run is called as Loading. There is a class loader present in the JVM whose main functionality is to load the .class file into the primary memory for the execution. All the .class files required by our program for the execution is been loaded by the class loader into the memory just before the execution.


































Step 4: Bytecode Verification by JVM :-
In order to maintain security of the program JVM has bytecode verifier. After the classes are loaded in to memory , bytecode verifier comes into picture and verifies bytecode of the loaded class in order to maintain security. It check whether bytecodes are valid. Thus it prevent our computer from malicious viruses and worms.












Step 5 : Execution of Java program : -
Whatever actions we have written in our Java program, JVM executes them by interpreting bytecode. If we talk about old JVM's they were slow, executed and interpreted one bytecode at a time. Modern JVM uses JIT compilation unit to which we even call just-in-time compilation. These compilers executes several instructions in parallel. They are also called as Java HotSpot compiler because JVM uses them to find hot spots in bytecode. By the term hot spots we mean that JVM analyze bytecode by searching those spots in program which are executed frequently. These frequent executable bytecodes parts are being translated to faster machine language code by Java HotSpot compiler. Now the significance behind this is whenever JVM encounter such parts again in bytecode it processes machine language code which are much faster as compared to execution of one byte code at a time.If we analyse above steps , we will find that there are two compilation phases. One in which source code is translated to bytecodes and second when hot spot parts of bytecodes are translated to machine language.

































Video Tutorial for above post :- 


How to print a Fibonacci series on console through Java program ?.

Introduction
Learning Java by example is the most effective approach. Java is very simple and easy programming language, when it comes to code. In order to master Java you should code on daily basis. It can be any code, whether simple java example or advanced java example. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully. Let us start today with a simple and famous program that is : How to print Fibonacci Series in Java ?.
Fibonacci Series : 0, 1, 1, 2, 3, 5, 8, 13, 21, … Here this series starts with 0 and 1 and than each coming digit is the sum of previous two digits. That means it goes as 0+1 = 1, 1+1=2, 1+2 = 3, 2+3= 5 and so on ....In this hub I will be explaining you the code step by step that how a fibonacci number is calculated and printed on the console. The last section would be the code which will demonstrate the working of a fibonacci series.


A closer look at the program stated below :- 
Line 1- Import declarations : Java has the ability to reuse the code. There are many predefined classes in Java which we will be using in our fibonacci series program. On line-1 we are importing Scanner class which is been kept in java.util package. Generally to help compiler in locating the class used in the program we use it regularly. Line 3 to 5 - Our Java program on line - 3 begins with a declaration of class named Fibonacci this class is declared as public so that it can be accessible to all Java class. Class Fibonacci contains a main method which is the entry point for every Java program. It is a static method so it is called by the JVM without any objects creation on heap. On next line there is a Java statement which just prints the String written in "". The println method just prints whatever is given to it in double quotes. Here in below example it first ask user , "Enter the number of terms you want from fibonacci series :". It asks user to enter a number to which he wants to see the fibonacci series terms. Fibonacci Series Program Code:-
import java.util.Scanner;

public class Fibonacci {
    public static void main (String[ ] args) {
      System.out.println("Enter the number of terms you want from fibonacci series : "); 
      
      Scanner scanner = new Scanner(System.in);
      
      int i = scanner.nextInt();
     
      fiboPrint(i);
    }
public static final void fiboPrint(long n){
      
   int f0 = 0;
   int f1 = 1;

   for (int i = 0; i < n; ++i) {
      System.out.println(f0 + " ");

      final int temp = f1;
      f1= f1+ f0;
      f0 = temp;
} 
    } 
}
Line 7 to 11 :- On line 7, a new Scanner object is created on heap. The Scanner Class is used to read data from a keyboard or disk. Here variable name is scanner and type is Scanner. Here new operator is used to create a physical Scanner object on the heap. This Scanner object is used to read data from the keyboard. System.in passed into constructor of Scanner object generally reads data from the keyboard in bytes. It is the Scanner object which will convert bytes into types such as ints. Line 9 code uses Scanner method nextInt() to obtain user input as Integer, which he types on the keyboard. Generally upon execution of line, the program waits for user to type an int value from keyboard and press enter. Upon pressing enter value types by user gets assigned to int variable called as i. Line 11, calls an static method fiboPrint passing an int i to it. The int value which user entered is passed as an parameter to the method fiboPrint. Line 15 to 16 :- On line 11 fiboPrint method is called and value of int is passed to variable n which has a long data type. On line 15 to 16 we have two local variables by the name f0 and f1 which are int and initialized with value 0 and 1. Line 18 to 23:- On line 18, a for loop statement is written. This for loop has int i as initialization step. Loop also has boolean condition which compares int i to int n passed by the user in fiboPrint method. It has increment expression which increments i by value 1 each time after for loop gets executed. Line 19, prints the value of f0 each time the for loop gets executed. On line21, we create a temp variable who stores value f1. On line 22, f1 is assigned a value which is addition of f1 and f0. On line 23, we assign value temp to variable f0. If the user enters number as 5, the output would be 0, 1, 1, 2, 3, etc ....

How to Calculate Area and Circumference of Circle in a Java Program

In this post, I will teach you How to calculate Area of Circle and Circumference / Perimeter of Circle ? through Java source code. I assume you know how to write and understand simple Java program. For calculating Area and Circumference of Circle, you should know their formulas.

  • Area of Circle = PI * R* R , where PI = 22/7, R= Radius of given Circle.
  • Circumference of Circle = 2 * PI * R , where PI=22/7, R=Radius of given Circle.


Java program: To Calculate Area and Circumference of Circle

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Circle {
    public static void main(String[ ] args){
        int radius = 0;
        System.out.println("Enter radius of a circle : ");
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            radius = Integer.parseInt(br.readLine());
        }
        catch(NumberFormatException ne)
        {
            System.out.println("Invalid radius value" + ne);
            System.exit(0);
        }
        catch(IOException ioe)
        {
            System.out.println("IO Error :" + ioe);
            System.exit(0);
        }
        radius = 5;
        double perimeter = 2 * Math.PI * radius;
        double area = Math.PI * radius * radius;
        
        System.out.println("Area of a circle is " + area);
        System.out.println("Perimeter of a circle is " + perimeter);

        }
}  
Output of the program on Console window Enter radius of a circle : 7 Area of a circle is 78.53981633974483 Perimeter of a circle is 31.41592653589793 A Closer Look at the Sample Program Line 1 to 3 :- If we look at the source code of the program, the program starts with a import statements. Generally we have to import the classes which we require in our source code. These classes which we import are helper classes. Without importing these classes if you use them in your program, you get compile time errors. In this sample program we import three classes. Line 5 to 8 :- After importing the three classes, we create a Java class with a name Circle. In Circle.java class we have a main method which is the starting point for the execution of code. In main method we create a integer variable radius and assign it a value 0. Generally we will need this variable to store the radius provided by the user.Then we wrote a System.out.println(""); code, this prints String asking user to enter value of radius. Line 9 to 23 :- Moving ahead we wrote a try-catch statements which helps us in catching errors and issues. If we look into code two exception are been caught, i.e. NumberFormatException and IOException. If we enter an invalid integer then NumberFormatException occurs and if there is any errors in transferring of Strings from console then IOException occurs. BufferedReader class is used which creates buffer to store characters from InputStreamReader. The InputStreamReader converts byte stream to character stream. Next line we use parseInt() method of the Integer class, because this method has capability to convert numeric format to internal format. Now we use Math class which stores value for PI. Math class contains all defined mathematical functions and it is present in the package java.lang.*; Line 25 to 29 : - At last few lines of code Area and Perimeter is being calculated using the formulas stated above. Thus the final result is then printed.
 
© 2021 Learn Java by Examples Template by Hubberspot