Java Tutorial in Details

What is Java?

Java is a object oriented programming language and it developed by Sun Micro systems in 1995. Java is platform independent and java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Java   compiler compiles the source code into byte code. At the run time, Java Virtual  Machine (JVM) interprets this byte code and generates machine code which will be  directly executed by the machine in which java program runs.

  • Java is object oriented programming language.  
  • Java is platform independent programming language which means compile once and run anywhereBetter portability than other languages across operating systems.
  • Java provides functionality for Thread, collection, File IO etc.
  • Java support for multi-threading, socket communication, memory management, web-based applications (Applet, Servlet and JSP), distributed applications (sockets, RMI, EJB etc.) and network protocols with the help of APIs.

Java fundamental concepts

1. Objects
2. Classes
3. Instance
4. Polymorphism
5. Inheritance
6. Encapsulation
7. Abstraction

1. Objects:


Object is an instance of a class and entity that has state and behaviour e.g. pencil, book, table, car. State is  value of an object and behaviour is functionality of an object such as writing.

2. Classes:

Class is a template or blueprint that describe the behaviours and states of a particular entity. A class defines new data type and can be used to create object of that type.

A class is declared using class keyword and it can be either abstract, final or default normal class.. The variables defined within a class are called instance variables and instance variables and methods are known as class members.


Class declarations can include following order
o    Modifiers :      A class can be public or default access specifier.

o    Class name:    The name should begin with a initial capital letter.

o    Super class:    Can use extends keyword for inherit.

o    Interfaces:      Can use comma separated implements keyword for inherit.

o    Body :             The class body surrounded by braces, { }.

             Example:     

                    public class Student {

                      String name;

                      String rollNo;

                      int age;

                     String address;

                 }


Here Student is a class and name, rollNo, age, address are properties of Student class.

3. Instance:


An instance is a copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate memory for that class instance.



Example of create instance of class.

Student  std = new Student();

Here std is instance of Student class, new keyword creates the physical copy of the object and assign it to the std variable.


4. Polymorphism:

 

Polymorphism is the ability to many forms of an object. The most common use of Polymorphism is parent class reference is used to a child class object.


There are two types of Polymorphism in java

    1. Compile time Polymorphism (method overloading). 
    2. Runtime Polymorphism (method overriding).

    1. Compile time Polymorphism (method overloading). 


Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature.


Example:


class TestOverloading

{

    public void display(char c)

    {

         System.out.println(c);

    }

    public void display(char c, int num) 

    {

         System.out.println(c + " "+num);

    }

}

class TestMainClass

{

   public static void main(String args[])

   {

       TestOverloading obj = new TestOverloading ();

       obj. display('a');

       obj. display('a',10);

   }
         }

    2. Runtime Polymorphism (method overriding).


Overriding is run time polymorphism having same method with same   parameters   or signature, but associated in a class & its subclass.


Example:


class Eat{
   //Overridden method
   public void eat()
   {
      System.out.println("Eating");
   }
}
class Rice extends Eat {
   //Overriding method
   public void eat(){
      System.out.println("He is eating rice");
   }
   public static void main( String args[]) {
      Rice obj = new Rice ();
      //This will call the child class version of eat()
      obj.eat();
   }
                }
  

5. Inheritance:

The process by which one class access the properties, data and methods of another class is called inheritance

The purpose of inheritance is re-usability code so that a class has to write only the features and rest of the common properties and functionalities can be extended from the another class.

importance in Inheritance


1. Sub class or Child Class.

The class that extends another class and use the features is known as Sub class or Child class.

2. Super Class or Parent Class.

The inherited class whose properties and functionalities are using in another class is known as Parent class / Super class or Base class.

  
Example:

class class Calculator {
   int value;
        
   public void sum(int x, int y) {
      value = x + y;
      System.out.println("The sum of the given numbers is "+value);
   }
        
   public void difference(int x, int y) {
      value = x - y;
      System.out.println("The difference between the given numbers is  "+value);
   }
}

public class MainCalculator extends Calculator {
   public void multiple(int x, int y) {
      value = x * y;
      System.out.println("The multiple of the given numbers is "+value);
   }
        
   public static void main(String args[]) {
      int a = 30, b = 10;
      MainCalculator obj = new MainCalculator ();
      obj.sum(a, b);
      obj.difference(a, b);
      obj.multiple(a, b);
   }
}




Types of Inheritance

1. Single Inheritance. 

2. Multilevel Inheritance.


1. Single Inheritance


In single inheritance, sub classes inherit the features of one super class.

Example:

class class Calculator {
   int value;
        
   public void sum(int x, int y) {
      value = x + y;
      System.out.println("The sum of the given numbers is "+value);
   }
        
   public void difference(int x, int y) {
      value = x - y;
      System.out.println("The difference between the given numbers is  "+value);
   }
}

public class MainCalculator extends Calculator {
   public void multiple(int x, int y) {
      value = x * y;
      System.out.println("The multiple of the given numbers is "+value);
   }
        
   public static void main(String args[]) {
      int a = 30, b = 10;
      MainCalculator obj = new MainCalculator ();
      obj.sum(a, b);
      obj.difference(a, b);
      obj.multiple(a, b);
   }
}




2. Multilevel Inheritance.


In Multilevel Inheritance, a subclass/ derived  class inherit the features of more than one class.

Java does not support multiple inheritance with classes. We can achieve multiple inheritance only through Interfaces.

Example:

public interface InterfaceIA {

         public void sum(int x,int z);
}

public interface InterfaceIB {

         public void subtraction(int x,int z);
}



public class Impl implements InterfaceIA, InterfaceIB, InterfaceIC {

         @Override
         public void sum(int x,int z) {

                 System.out.println("Addition is "+(x+z));
         }

         @Override
         public void substraction(int x,int z) {
                 System.out.println("Subtraction is "+(x-z))
         }

         public static void main(String[] args) {

                 Impl obj= new Impl();

                 obj.sum();

                 obj.subtraction();

             }

   }



6. Encapsulation:


Encapsulation is the process of wrap the data and code into single unit. The variables of a class will be hidden from other classes, and can be accessed by methods of their current class.

Make encapsulation in following way.

1. Declare variables as private.
2. Declare public setter and getter methods to access or modify the value.


Example:

public class Employee {
        private int id;
        private String name;
        private int age;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
       } 
}



7. Abstraction:

Abstraction is the process of hiding the implementation details, only showing the functionality.

In other words, Abstraction is the process to reduce complexity and taking out the important characteristics of a class.


There are two ways to achieve abstraction in java

1.     Abstract class

2.     Interface


1. Abstract class

Abstract class defines a class that contains the abstraction without providing a complete implementation of method. The abstract keyword is used for abstract class and abstract method.

Abstract classes are used if you want to create a super class that only defines the variables and methods and sub class will be accessed the variables and methods for implementation.

Rule of Abstract class.

        1.   Abstract classes may or may not contain abstract methods.
        2.   Must be declared abstract keyword if a class has at least one abstract method.
        3.     The class cannot be instantiated if abstract is declared.
        4.     Must be provided implementations of all the abstract methods, If you inherit            an abstract class.
         
         Example:

abstract class Figure {
    
      double dim1;
      double dim2;
    
      Figure(double d1,double d2){
            dim1 = d1;
            dim2 = d2;
      }
    
      abstract void area();

  }

   class Rectangle extends Figure{
    
      Rectangle(double d1,douple d2){
            super(d1,d2);
      }
      //Override area of rectangle
      void area(){
            System.out.println("area of rectangle is"+ dim1*dim2);
          
      }
   }

   class Demo{
      public static void main(String args[]){
            Figure f = new Rectangle(4,7);
            f.area();
   }


  Output:

      area of rectangle is 28


2.     Interface

The interface in java provides abstraction. We can create only abstract method in interface and can’t create implementation or method body. It is used to achieve abstraction and multiple inheritance in Java.  It has static constants and abstract methods.

Rule of Interface

1.        All interface Methods are implicitly public and abstract
2.        All variables in Interface by default constant(public, static, final).
3.        Interface Methods can not be static.
4.        Interface Methods can not be final.
5.        One Interface can extend one or more Interface.

Example:


interface Area
{
  final static float pi = 3.14f;
  float findArea(float x);
}


class Circle implements Area

{
  public float findArea(float x)
   {
     return (x*x*xpi);
   }
}


class Square implements Area

{
  public float findArea(float x)
  {
   return(x*x);
  }
}


public class InterFaceDemo

{
 public static void main(String args[])
 {
  Circle c = new Circle();
  Square s= new Square();
  Area area;
  area = c;
  System.out.println("Area of Circle is" + area.findArea(10));
  area = s;
  System.out.println("Area of Square is" + area.findArea(30));

 }









Java Architecture

Java combines both the approaches of compilation and interpretation. First,    java  compiler compiles the source code into byte code. At the run time,Java Virtual  Machine (JVM) interprets this byte code and generates machine code which will be  directly executed by the machine in which  java   program runs. So java is both  compiled and interpreted language.
                      
Compile Java Class


1.  Java Development Kit(JDK)

JDK contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.


2.  Java Runtime Environment (JRE)

Java Runtime Environment contains JVM, class libraries and other supporting components. Java source code is compiled into byte code by  Java compiler. This byte code will be stored in class files. During runtime,this byte code will be loaded, verified and   JVM interprets the byte code into machine code which will be executed in the machine in which the Java program runs.

        A Java Runtime Environment performs the following main tasks respectively.
                                   

1. Class Loader Loads the class

The Java Class loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually classes are only loaded on demand.

2. Verifies the byte code

This is done by byte code verifier. checks the byte code and ensures the followings.
(i).   The code follows JVM specifications.
(ii).  There is no unauthorized access to memory.
(iii). The code does not cause any stack overflows.
(iv).  There are no illegal data conversions in the code such as float to  object                references.

3. Interprets the byte code

             This is done by the JVM


3.  Java Virtual Machine (JVM)

JVM is a component which provides an environment for running Java programs.  JVM interprets the byte code into machine code  which will be executed the machine in which  the Java program runs.







How Java Program Work? / Java Program Life Cycle


Step 1: Write Java Program.

Step 2: Compile java file to class file and generate byte code.

Step 3: Byte code translate to machine code and run on JVM.

Java class compile to byte code



How to Compile and Run Java Program Using Command Prompt?



     1. Save the program. After using a text editor, such as NotePad, to create your Java program, save the program with a .java extension.

2. Open Command Prompt.
3. Navigate to the correct folder.
4. Set path.
5. Compile the program.
6. Run the program.



Create class as Demo and save as Demo.java in correct folder. Class name and file name should be same.

public class Demo {
   public static void main(String args[]){
       System.out.println("First java program is successed");
   } 
}


Create java class





Set path in Java


Right click on My computer and click on  properties option.

Set Path In Java


Click on Advanced system settings.

Java Home Path in Enverionment Variable



Click on Environment Variables.

Set JAVA_HOME in Enverionment Variable




Set JAVA_HOME (to java home path)

Example:  C:\Program Files\Java\jdk1.8.0_111

Java Class Path Setting



Set Java PATH(Path to Java bin directory)

Example:  C:\Program Files\Java\jdk1.8.0_111\bin

Java Path Setting in My Computer


Compile the program in command prompt

Example:  javac Demo.java

Run Java Classin Command Prompt


Run the program in command prompt 

Example: java Demo(Class name)

Output will be showing on command prompt on press enter button after writing the run command.


How to run java program in command line







Hello World in Java - Step By Step


Step 1. Write Java Program in any editor such as Note Pad.

Step 2. Save the program with  .java extension.

Step 3. Open command prompt.

Step 4: Compile java file by typing "javac HelloWorld.java" in command prompt.

Step 5: Run it by typing  "java HelloWorld in command prompt.


Example:

Step 1: Write Java Program in any editor such as such as Note Pad.

public class HelloWorld {
   public static void main(String[] args) {
   System.out.println("Hello World");
 }




Step 2. Save the program with  .java extension.




Hello World Java Program





Step 4: Compile java file by typing "javac HelloWorld.java" in command prompt.
     
             

Compile Java Filein Command Line
                   Java compiler compile java file to class file and generate byte code


Step 5: Run it by typing  "java HelloWorld"  in command prompt.


                                           
How to run jan class file in command prompt

             Byte code translate to machine code and run on JVM.

Output is "Hello World".




Java Fundamental concepts (Object and Classes) - Step in Step in Details


Java is a object oriented programming language Java supports the following fundamental concepts

1. Objects
2. Classes
3. Instance
4. Polymorphism
5. Inheritance
6. Encapsulation
7. Abstraction

1. Objects:


Object is an instance of a class and entity that has state and behaviour e.g. pencil, book, table, car. State is  value of an object and behaviour is functionality of an object such as writing.

2. Classes:

Class is a template or blueprint that describe the behaviours and states of a particular entity. A class defines new data type and can be used to create object of that type.

A class is declared using class keyword and it can be either abstract, final or default normal class.. The variables defined within a class are called instance variables and instance variables and methods are known as class members.


Class declarations can include following order
o    Modifiers :      A class can be public or default access specifier.

o    Class name:    The name should begin with a initial capital letter.

o    Super class:    Can use extends keyword for inherit.

o    Interfaces:      Can use comma separated implements keyword for inherit.

o    Body :             The class body surrounded by braces, { }.

             Example:     

                    public class Student {

                      String name;

                      String rollNo;

                      int age;

                     String address;

                 }


Here Student is a class and name, rollNo, age, address are properties of Student class.

3. Instance:


An instance is a copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate memory for that class instance.



Example of create instance of class.

Student  std = new Student();

Here std is instance of Student class, new keyword creates the physical copy of the object and assign it to the std variable.


4. Polymorphism:

 

Polymorphism is the ability to many forms of an object. The most common use of Polymorphism is parent class reference is used to a child class object.


There are two types of Polymorphism in java

    1. Compile time Polymorphism (method overloading). 
    2. Runtime Polymorphism (method overriding).

    1. Compile time Polymorphism (method overloading). 


Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature.


Example:


class TestOverloading

{

    public void display(char c)

    {

         System.out.println(c);

    }

    public void display(char c, int num) 

    {

         System.out.println(c + " "+num);

    }

}

class TestMainClass

{

   public static void main(String args[])

   {

       TestOverloading obj = new TestOverloading ();

       obj. display('a');

       obj. display('a',10);

   }
         }

    2. Runtime Polymorphism (method overriding).


Overriding is run time polymorphism having same method with same   parameters   or signature, but associated in a class & its subclass.


Example:


class Eat{
   //Overridden method
   public void eat()
   {
      System.out.println("Eating");
   }
}
class Rice extends Eat {
   //Overriding method
   public void eat(){
      System.out.println("He is eating rice");
   }
   public static void main( String args[]) {
      Rice obj = new Rice ();
      //This will call the child class version of eat()
      obj.eat();
   }
                }
  

5. Inheritance:

The process by which one class access the properties, data and methods of another class is called inheritance

The purpose of inheritance is re-usability code so that a class has to write only the features and rest of the common properties and functionalities can be extended from the another class.

importance in Inheritance


1. Sub class or Child Class.

The class that extends another class and use the features is known as Sub class or Child class.

2. Super Class or Parent Class.

The inherited class whose properties and functionalities are using in another class is known as Parent class / Super class or Base class.

  
Example:

class class Calculator {
   int value;
        
   public void sum(int x, int y) {
      value = x + y;
      System.out.println("The sum of the given numbers is "+value);
   }
        
   public void difference(int x, int y) {
      value = x - y;
      System.out.println("The difference between the given numbers is  "+value);
   }
}

public class MainCalculator extends Calculator {
   public void multiple(int x, int y) {
      value = x * y;
      System.out.println("The multiple of the given numbers is "+value);
   }
        
   public static void main(String args[]) {
      int a = 30, b = 10;
      MainCalculator obj = new MainCalculator ();
      obj.sum(a, b);
      obj.difference(a, b);
      obj.multiple(a, b);
   }
}




Types of Inheritance

1. Single Inheritance. 

2. Multilevel Inheritance.


1. Single Inheritance


In single inheritance, sub classes inherit the features of one super class.

Example:

class class Calculator {
   int value;
        
   public void sum(int x, int y) {
      value = x + y;
      System.out.println("The sum of the given numbers is "+value);
   }
        
   public void difference(int x, int y) {
      value = x - y;
      System.out.println("The difference between the given numbers is  "+value);
   }
}

public class MainCalculator extends Calculator {
   public void multiple(int x, int y) {
      value = x * y;
      System.out.println("The multiple of the given numbers is "+value);
   }
        
   public static void main(String args[]) {
      int a = 30, b = 10;
      MainCalculator obj = new MainCalculator ();
      obj.sum(a, b);
      obj.difference(a, b);
      obj.multiple(a, b);
   }
}




2. Multilevel Inheritance.


In Multilevel Inheritance, a subclass/ derived  class inherit the features of more than one class.

Java does not support multiple inheritance with classes. We can achieve multiple inheritance only through Interfaces.

Example:

public interface InterfaceIA {

         public void sum(int x,int z);
}

public interface InterfaceIB {

         public void subtraction(int x,int z);
}



public class Impl implements InterfaceIA, InterfaceIB, InterfaceIC {

         @Override
         public void sum(int x,int z) {

                 System.out.println("Addition is "+(x+z));
         }

         @Override
         public void substraction(int x,int z) {
                 System.out.println("Subtraction is "+(x-z))
         }

         public static void main(String[] args) {

                 Impl obj= new Impl();

                 obj.sum();

                 obj.subtraction();

             }

   }



6. Encapsulation:


Encapsulation is the process of wrap the data and code into single unit. The variables of a class will be hidden from other classes, and can be accessed by methods of their current class.

Make encapsulation in following way.

1. Declare variables as private.
2. Declare public setter and getter methods to access or modify the value.


Example:

public class Employee {
        private int id;
        private String name;
        private int age;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
       } 
}



7. Abstraction:

Abstraction is the process of hiding the implementation details, only showing the functionality.

In other words, Abstraction is the process to reduce complexity and taking out the important characteristics of a class.


There are two ways to achieve abstraction in java

1.     Abstract class

2.     Interface


1. Abstract class

Abstract class defines a class that contains the abstraction without providing a complete implementation of method. The abstract keyword is used for abstract class and abstract method.

Abstract classes are used if you want to create a super class that only defines the variables and methods and sub class will be accessed the variables and methods for implementation.

Rule of Abstract class.

        1.   Abstract classes may or may not contain abstract methods.
        2.   Must be declared abstract keyword if a class has at least one abstract method.
        3.     The class cannot be instantiated if abstract is declared.
        4.     Must be provided implementations of all the abstract methods, If you inherit            an abstract class.
         
         Example:

abstract class Figure {
    
      double dim1;
      double dim2;
    
      Figure(double d1,double d2){
            dim1 = d1;
            dim2 = d2;
      }
    
      abstract void area();

  }

   class Rectangle extends Figure{
    
      Rectangle(double d1,douple d2){
            super(d1,d2);
      }
      //Override area of rectangle
      void area(){
            System.out.println("area of rectangle is"+ dim1*dim2);
          
      }
   }

   class Demo{
      public static void main(String args[]){
            Figure f = new Rectangle(4,7);
            f.area();
   }


  Output:

      area of rectangle is 28


2.     Interface

The interface in java provides abstraction. We can create only abstract method in interface and can’t create implementation or method body. It is used to achieve abstraction and multiple inheritance in Java.  It has static constants and abstract methods.

Rule of Interface

1.        All interface Methods are implicitly public and abstract
2.        All variables in Interface by default constant(public, static, final).
3.        Interface Methods can not be static.
4.        Interface Methods can not be final.
5.        One Interface can extend one or more Interface.

Example:


interface Area
{
  final static float pi = 3.14f;
  float findArea(float x);
}


class Circle implements Area

{
  public float findArea(float x)
   {
     return (x*x*xpi);
   }
}


class Square implements Area

{
  public float findArea(float x)
  {
   return(x*x);
  }
}


public class InterFaceDemo

{
 public static void main(String args[])
 {
  Circle c = new Circle();
  Square s= new Square();
  Area area;
  area = c;
  System.out.println("Area of Circle is" + area.findArea(10));
  area = s;
  System.out.println("Area of Square is" + area.findArea(30));

 }

}




8 comments:

  1. Very good tutorial. I have prepared this tutorial, its helped me to increase my java knowledge in details.

    ReplyDelete
    Replies
    1. Excellent Post. Are you looking for Laptops for your training? Click here to select your idle Laptop in budget.

      Delete
  2. Excellent Post. Are you looking for Laptops for your training? Click here to select your idle Laptop in budget.

    ReplyDelete
  3. Really very good article. the post has excellent tips which are very useful.


    laptop price

    ReplyDelete
  4. Really very good article. the post has excellent tips which are very useful.


    laptop price

    ReplyDelete
  5. Excellent Post. Are you looking for Laptops for your training? Click here Laptop Price to select your idle Laptop in budget.

    ReplyDelete