what is java

Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

History of java

Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them.

how to check java version and set java path

Java Version

checkJavaVersion

Set path in java

TsetJavapath

First Java Programme

HelloWorld

Class

java code start from any class , so class keyword used in java.

Public

Public is access specifire in java which jvm access publicly

static

static is the keyword which save the memory. In Main class ,when jvm call, static does not create object of class

void

void mean does not return any thing

String args

This is command line argument which is string type

System.out.println

System is a final class and out is a static member field of system class and println is method of PrintStream class

Compile the First programme

JavaFirstProgramme_compile

After compilation , it create .class file like- className.class

Java Token Set

A Java program is basically a collection of classes. A class is defined by a set of declaration statements and methods containing executable statements. Most statements contain expressions, which describe the actions carried out on data. Smallest individual unit in a program are known as tokens. The compiler recognizes them for building up expressions and statements.

Tokens are the various Java program elements which are identified by the compiler. A token is the smallest element of a program that is meaningful to the compiler.

Java language includes six types of tokens and they are:

  • Reserved Keywords
  • Identifiers
  • Literals
  • Variables
  • Operators
  • Comments

    Reserved Keywords ? Reserved keywords are java tokens with predefined meaning. Java has 60 reserved keywords.e.g int,class,break,continue etc.

    Identifiers ? Identifiers are java tokens designed and decided by the java programmer. Examples for java tokens namely identifiers are: name for the class, name for members of the class, and temporary variables in class methods.

    Literals ? Literals are java tokens containing set of characters. Literals are used to represent a constant that has to be stored in a variable.e.g 2,5,4.6,etc.

    Operators ? Operators are java tokens containing a special symbol and predefined meaning in Java. Operators can be used with one or more operands to achieve a result.e.g unary,binary,ternary operators

    Variables ? Variables are used to hold the value.

    Comments - Comments are used by humans to clarify source code. Comments are ignored by the compiler while compiling a code.

    Data types

    A data type in a programming language is a set of data with values having predefined characteristics. Examples of data types are: integer,floating point unit number,character, string, and pointer.

    boolean -->A binary value , true or false

    byte --> signed value 8 bit, value of range is -128 to 127

    short --> signed value 16 bit, value of range is -32768 to 32767

    char --> Unicode character 16 bit

    int --> signed value 32 bit, value of range is -2.147.483.648 to 2.147.483.647

    long --> signed value 64 bit, value of range is -9.223.372.036.854.775.808 to 9.223.372.036.854.775.808

    float --> floating point value 32 bit

    double --> floating point value 64 bit

    Classes in Java

    A class specifies the design of an object.It states what data an object can hold and the way it can behave when using the data.

    class is a template which contains fields, variable, methods, object instance and it is a complete behaviour is called class.

    Object

    some methods of Object class

  • equals
  • toString()
  • wait()
  • notify()
  • notifyAll()
  • hashCode()
  • clone()
  • Let see example

     class javaClass{
    		int x=10, int y=12;
    		String strName;
    		public int addition(int x, int y);
           }
    

    Control statements in Java(if,ifelse statement)

    The control statement is used to control the flow of execution of the program . This execution order depends on the supplied data values and the conditional logic.

    public class IfElseConditonExample {
    	public static void main(String args[]) {
    		int marks = 90;
    		if (marks < 50) {
    			System.out.println("you got third division");
    		} else if (marks < 60) {
    			System.out.println("you got second division");
    		} else {
    			System.out.println("you got first division");
    		}
    	}
    
    }	
    	

    Output

    you got first division

    Jump Statement and Switch Statement

    In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.

    class BreakStatement
        {
            public static void main(String args[])
            {
                int a=1;
    
                while(a<=7)
                {
                    if(a==5)
                        break;
    
                    System.out.println("Statement : " + a);
                    a++;
    
                }
    
                System.out.println("End of Program.");
            }
        }
    	
    

    output

    Statement : 1
    Statement : 2
    Statement : 3
    Statement : 4
    End of Program.
    	
    	class ContinueStatement
        {
            public static void main(String args[])
            {
                int a=0;
    
                while(a<7)
                {
    
                    a++;
    
                    if(a==5)
                        continue;
    
                    System.out.println("Statement ->" + a);
    
                }
                System.out.println("End of Program.");
        }
    

    output

    Statement ->1
    Statement ->2
    Statement ->3
    Statement ->4
    Statement ->6
    Statement ->7
    End of Program.
    
    

    Abstract class in java

    An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:

  • Define methods which can be used by the inheriting subclass.
  • Define abstract methods which the inheriting subclass must implement.
  • Provide a common interface which allows the subclass to be interchanged with all other subclasses.
  •  abstract public class AbstractJavaClass
    {
        abstract public void abstractJavaMethod();
        public void implementedJavaMethod() { 
    	   System.out.print("implementedJavaMethod()"); 
    	}
        final public void finalJavaMethod() {
        	System.out.print("finalJavaMethod()"); 
    	}
    }
     

    abstractJavaMethod() method did not have any body. so if we implement AbstractJavaClass class then abstract method must be override.

     public class ImplementingJavaClass extends AbstractJavaClass
    {
        public void abstractJavaMethod() {
    		System.out.print("abstractJavaMethod()"); 
    	}
        public void implementedJavaMethod() {
    		System.out.print("implementedJavaMethod Overridden!");
    	}
    }
     

    Encapsulation and Inheritance

    What is encapsulation in Java

    Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.

    The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class

    example

     class Person 
     {
    	String name;
    	int age;
    	
    	void talk() {
    	}
    	
    	void think() {
    	}
    	
    	void work() {
    	}
    	
    	void play() {
    	}
    }
     

    Advantages of encapsulation:

    it is because encapsulation has a number of advantages that increase the reusability, flexibility and maintainability of the code.

    Flexibility: It is more flexible and easy to change the encapsulated code with new requirements. For example, if the requirement for setting the age of a person changes, we can easily update the logic in the setter method setAge().

    Reusability: Encapsulated code can be reused throughout the application or across multiple applications. For example, the Person class can be reused whenever such type of object is required.

    Maintainability: Application ode is encapsulated in separate units (classes, interfaces, methods, setters, getters, etc) so it is easy to change or update a part of the application without affecting other parts, which reduces the time of maintenance.

    what is Inheritance in java

    Inheritance means a class can acquire some properties of another class.

    Base class: The parent class that originally has a set of properties (methods).

    Derived class: The child class that can inherit the methods from the parent class.

    The keyword extends is used to inherit a base class. For e.g.

    class A extends B

    A is the derived class.

    B is the base class.

    In this case, depending upon the access specifiers, the properties of class B will be acquired by class A. So, an object of A can call a method or override a method defined in class B.

    Example

    class Father{
      public void Building10(){
      System.out.println("This is the property of father");
      }
    }
    
    class Son extends Father{
      public void Building10(){
      System.out.println("Now, This is the property of son which inherit father property");
      }
    }
    

    Polymorphism

    Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

    Polymorphism in java is a concept of OOPS in which this concept support many forms , where poly means many , and morph means form

    Polymorphism is ability to change the charchater of variable , method or object or any muliple forms. The most common use for polymorphism in OOPS occur when a parent class used to refrence of child class object.

    there are two way to support polymorphism

  • Compile time Polymorphism (method overloading or static binding)
  • Run time polymorphism ( method overriding or dynamic binding)
  • Compile time Polymorphism (method overloading or static binding)

    compile time polymorphism refers to a process in which a call to an overloaded method is resolved at compile time rather than at run time. Method overloading is an example of compile time polymorphism. Method Overloading is a feature that allows a class to have two or more methods having the same name but the arguments passed to the methods are different. Unlike method overriding, arguments can differ in:

    1. Number of parameters passed to a method

    2. Datatype of parameters

    3. Sequence of datatypes when passed to a method.

    class Mathematics {
     static int add( int x, int y){
        return x + y;
      }
      static double add( double m, double n){
        return m +n ;
      }
      
      public static void main(String arsg[]){
         Mathematics math = new Mathematics();
    	 System.out.println(math.add(10,10));
    	 System.out.println(math.add(10.20, 20.10));
      }
    }
    
    

    Compiletime Polymorphism :

    Invocation of Overloaded method is example of Compiletime polymorphism. Flow of execution will be decided at compilation of java program.

    ublic class CompiletimePooly {
    
    	public void method() {
    	      System.out.println("Method with no parameter.");
    	   }
    
    	   public void method(String name) {
    	      System.out.println("Method with single parameter.");
    	   }
    
    	   public void method(String... name) {
    	      System.out.println("Method with dynamic parameter");
    	   }
    
    	   public void invoke() {
    		   CompiletimePooly compile = new CompiletimePooly();
    	      compile.method();
    	      compile.method("First Name");
    	      compile.method("First name","Last name");
    	   }
    }
    

    Run time polymorphism ( method overriding or dynamic binding)

    runtime polymorphism refers to a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this, a reference variable is used to call an overridden method of a superclass at run time. Method overriding is an example of run time polymorphism

    class Bank {
       public void AcoountName() {
          System.out.println("This is Bank Account holder name");
       }
    
       public void parentMethod() {
          System.out.println("This is method in Bank class.");
       }
    }
    
    interface Running {
       public void OpenTime();
    }
    
    class SBI extends Bank implements Running {
    
       @Override
       public void OpenTime() {
          System.out.println("Bank is open now.");
       }
    
       @Override
       public void AcoountName() {
          System.out.println("This is SBI account name holder.");
       }
    }
    

    Final Keyword in java

    The Final Keyword in java is used to restrict the user. It can be used in many contexts. Final can be a variable, a method or a class.

    Final Variable: if any variable is final , then value of this variable can not changed

    package JUnit;
    
    public class FinalClass {
    	public final int i =100;
    	
    	public void finalVariable(){
    		i = 101;
    	}
    
    }
    

    finalVariable

    Final method: if method any class is final, then we can not override the same method.

    package JUnit;
    
    public class Mother {
    	public  final void surName(){
    		System.out.println("Mother surname to be always follows by sons");
    	}
    
    }
    
    public class Daughter extends Mother{
    	public final void surName() {
    		System.out.println("Sory mom, i will change surename");
    	}
    	
    }
    
    

    HelloWorld

    Final Class: if class is final, then we can not inheritance by other class, mean classes can not be subclass.

    package JUnit;
    
    public final  class FinalClass {
    	public final int i =100;
    	
    	public void finalVariable(){
    		i = 101;
    	}
    	
    	
    	
    
    }
    
    public subClass extends FinalClass{
    	//compiler error
    }
    
    

    Enum,Static Variable,Static Void and Static Method

    Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java. The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class.

    	public enum Currency {PENNY, NICKLE, DIME, QUARTER};
    	
    	
    	public enum Currency { 
    	PENNY(1), NICKLE(5), DIME(10), QUARTER(25); 
    	private int value; private Currency(int value) { 
    	this.value = value; 
    	} };
    

    Benefits of using Enums in Java

    1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is a compiler error to assign something else, unlike the public static final variables used in Enum int pattern and Enum String pattern.

    2) Enum has its own namespace.

    3) The best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type. We will also see an example of using java enum in switch statement in this java enum tutorial.

    4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.

    static members belong to the class instead of a specific instance.

    It means that only one instance of a static field exists, even if you create a million instances of the class or you donnot create any. It will be shared by all instances.

    Static is a Non Access Modifier. The static keyword belongs to the class than instance of the class. can be used to attach a Variable or Method to a Class.

    Static keyword CAN be used with:

    Method

    Variable

    Class nested within another Class

    Initialization Block

    CAN'T be used with:

    Class (Not Nested)

    Constructor

    Interfaces

    Method Local Inner Class(Difference then nested class)

    Inner Class methods

    Instance Variables

    Local Variables

    Imagine the following example which has an instance variable named count which in incremented in the constructor:

    package pkg;
    
    class StaticExample {
        int count = 0;// will get memory when instance is created
    
        StaticExample() {
            count++;
            System.out.println(count);
        }
    
        public static void main(String args[]) {
    
            StaticExample c1 = new StaticExample();
            StaticExample c2 = new StaticExample();
            StaticExample c3 = new StaticExample();
    
        }
    }
    

    Output:

    1 1 1
    

    Now if we change the instance variable count to a static one then the program will produce different output:

    package pkg;
    
    class StaticExample {
        static int count = 0;// will get memory when instance is created
    
        StaticExample() {
            count++;
            System.out.println(count);
        }
    
        public static void main(String args[]) {
    
            StaticExample c1 = new StaticExample();
            StaticExample c2 = new StaticExample();
            StaticExample c3 = new StaticExample();
    
        }
    }
    

    Output:

    1 2 3
    

    Static with Final:

    The global variable which is declared as final and static remains unchanged for the whole execution. Because, Static members are stored in the class memory and they are loaded only once in the whole execution. They are common to all objects of the class. If you declare static variables as final, any of the objects can?t change their value as it is final. Therefore, variables declared as final and static are sometimes referred to as Constants. All fields of interfaces are referred as constants, because they are final and static by default.

    Static

    Static variables : -> If any variable we declared as static is known as static variable

    class BankClass{
     static Srtring bankName ="SBI";
     String accountName ;
     int accountNo;
    }
    
    class Bank{
      BankClass bnk = new BankClass();
      bnk.accountName ="Ravi";
      bnk.accountNo=123456789;
      System.out.println(bnk.accountName);
      System.out.println(bnk.accountNo);
      System.out.println(BankClass.bankName);
      
       BankClass bnk1 = new BankClass();
      bnk1.accountName ="Ravi verma";
      bnk1.accountNo=12345678921;
      System.out.println(bnk1.accountName);
      System.out.println(bnk1.accountNo);
      System.out.println(BankClass.bankName);
      
      
    }
          
    

    output

    Ravi
    123456789
    SBI
    Ravi verma
    12345678921
    SBI
    

    above example bankName is common of all account name holder so it share by both bnk and bnk1 object.

    A static method is a method that has no notion of this; it is defined on the class and doesnot know about any particular instance of that class unless a reference is passed to it

    Exception Handling in Java

    What is exception in java

    Java exception is a abnormal condition when excution during programme stop the flow of programme and it disturb the flow of programme excution. Basicaly , it happens either by mistake of code or some external error like hardware failure or network error.

    When an exception can occur

    It can be occur in two condition either compile time or run time of programme

    Reasons for Exceptions

    There can be several reasons for an exception. For example, following situations can cause an exception ?

  • Network connection problem
  • class file missing which was supposed to be loaded
  • Operands being manipulated are out of prescribed ranges
  • Opening a non-existing file
  • user input data invalid
  • and so on..

    Difference between error and exception

    Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.

    Exceptions are conditions within the code. A developer can handle such conditions and take necessary corrective actions. Few examples ? DivideByZero exception, NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException,...

    Errors: Errors are exceptional scenarios that are out of scope of application and it?s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That?s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError

    Why to handle exception

    Handing exception is a convering system error to human understable message, which show on view page. when exception arise during running program then it is jvm work and responsible to throw message accounding to exception type, but on same time user can manage and write the exception message that is human understable.

    example..

     Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5)

    Some method of Exception which handle

    public String getMessage() : This method returns the message String of Throwable and the message can be provided while creating the exception through it is constructor.

    public String getLocalizedMessage() : This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.

    public synchronized Throwable getCause() : This method returns the cause of the exception or null id the cause is unknown.

    public String toString() : This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

    public void printStackTrace() : This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream.

    Types of exceptions

    There are two types of exceptions is following :

    1 .Checked exceptions

    2. Unchecked exceptions

    Checked exceptions

    All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, it will give compilation error.

    Checked Exceptions example

    ClassNotFoundException,IllegalAccessException,NoSuchFieldException,EOFException etc.

    Unchecked Exceptions

    Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it is the duty of the programmer to handle these exceptions and provide a safe exit.

    These exceptions need not be included in any method is throws list because compiler does not check to see if a method handles or throws these exceptions.

    Unchecked Exceptions Examples

    ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NegativeArraySizeException etc.

    -----------------------------------------

    try catch

    The try-catch block contains one or more legal lines of code that could throw an exception.

     public void divisionMethod(){
            try {
                int result = divide(2,1);
                System.out.println(result);
            } catch (BadNumberException e) {
                //do something clever with the exception
                System.out.println(e.getMessage());
            }
            System.out.println("Division attempt done");
        }

    The BadNumberException parameter e inside the catch-clause points to the exception thrown from the divide method, if an exception is thrown.

    If no exeception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed.

    Nested try catch

    One try-catch block can be present in the another try is body. This is called Nesting of try catch blocks. Each time a try block does not have a catch handler for a particular exception, the stack is unwound and the next try block is catch

    ....
    //Main try block
    try
    {
       statement 1;
       statement 2;
       //try-catch block inside another try block
       try
       {
          statement 3;
          statement 4;
       }
       catch(Exception e1)
       {
           //Exception Message
       }
       //try-catch block inside another try block
       try
       {
           statement 5;
           statement 6;
       }
       catch(Exception e2)
       {
           //Exception Message
       }
    }
    catch(Exception e3) //Catch of Main(parent) try block
    {
          //Exception Message
    }
    ....
    
    public class NestedTry {
    
    	public static void main(String args[]){
    		 //Parent try block
    	     try{
    	    	//Child try block1
    	         try{
    	            System.out.println("Inside block1");
    	            int b =34/0;
    	            System.out.println(b);
    	         }
    	         catch(ArithmeticException e1){
    	            System.out.println("Exception: e1");
    	         }
    	         //Child try block2
    	         try{
    	            System.out.println("Inside block2");
    	            int b =34/0;
    	            System.out.println(b);
    	         }
    	         catch(ArrayIndexOutOfBoundsException e2){
    	            System.out.println("Exception: e2");
    	         }
    	        System.out.println("Just other statement");
    	    }
    	    catch(ArithmeticException e3){
    	    	 System.out.println("Arithmetic Exception");
    	         System.out.println("Inside parent try catch block");
    	    }
    	    catch(ArrayIndexOutOfBoundsException e4){
    	    	System.out.println("ArrayIndexOutOfBoundsException");
    	         System.out.println("Inside parent try catch block");
    	    }
    	    catch(Exception e5){
    	    	System.out.println("Exception");
    	         System.out.println("Inside parent try catch block");
    	     }
    	     System.out.println("Next statement..");
    	  }
    }
    
    

    output

    Inside block1
    Exception: e1
    Inside block2
    Arithmetic Exception
    Inside parent try catch block
    Next statement..
    

    The above example shows NestedTry class try catch use in Java. we can see that there are two try-catch block inside main try block is body. we have marked them as block 1 and block 2 in above example.

    Block1: I have divided an integer by zero and it caused an arithmetic exception however the catch of block1 is handling arithmetic exception so Exception: e1 got printed.

    Block2: In block2 also, ArithmeticException occurred but block 2 catch is only handling ArrayIndexOutOfBoundsException so in this case control jump back to Main try-catch(parent) body. Since catch of parent try block is handling this exception that is why Inside parent try catch block got printed as output.

    Parent try Catch block: Since all the exception handled properly so program control didnot get terminated at any point and at last Next statement.. came as output.

    finally block

    The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling ? it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

    public class FinallyBlock {
    	public static void main(String[] args) {
    		 double p = 7.0D;
    		    String str = "acda";
    		    try{
    		        p = Double.valueOf(str);
    		    }
    		    catch(Exception ex){
    		        System.out.println("Exception Happened");
    		        return;  //return statement here!!!
    		    }finally{
    		        System.out.println("Finally");
    		    }
    		    System.out.println("After finally");
    	}
    	
    
    }
    

    output

    Exception Happened
    Finally
    

    when the finally block doesnot execute

  • The death of a Thread
  • Using of the System. exit() method
  • Due to an exception arising in the finally block
  • Finally block without catch

    public class FinallyBlock {
    	
    	public static void main(String[] args) {
    		 double p = 7.0D;
    		    String str = "acda";
    		    try{
    		        p = Double.valueOf(str);
    		    }
    		    finally{
    		    	
    		        System.out.println("Finally");
    		    }
    		    System.out.println("After finally");
    	}
    	
    
    }
    

    Finally block and System.exit()

    when System.exit() called then finally block never execute

    public class FinallyBlock {
    	
    	public static void main(String[] args) {
    		 double p = 7.0D;
    		    String str = "acda";
    		    try{
    		        p = Double.valueOf(str);
    		        System.exit(0);
    		    }
    		    finally{
    		    	
    		        System.out.println("Finally");
    		    }
    		    System.out.println("After finally");
    	}
    	
    
    }
    

    try-catch-finally

    public class TryFinalExceptions {
    	static void myMethod(int testnum) throws Exception {
    	      System.out.println ("start - myMethod");
    	      if (testnum == 90) 
    	         throw new Exception();
    	      System.out.println("end - myMethod");
    	      return;	
    	   }
    	   public static void main(String  args[]) {
    	      int testnum = 90;
    	      try {
    	         System.out.println("try - first statement");
    	         myMethod(testnum);
    	         System.out.println("try - last statement");
    	      }
    	      catch ( Exception ex) {
    	         System.out.println("An Exception");
    	      }
    	      finally {
    	         System. out. println( "finally") ;
    	      }
    	      System.out.println("Out of try/catch/finally - statement");
    	   }
    
    }
    

    output

    try - first statement
    start - myMethod
    An Exception
    finally
    Out of try/catch/finally - statement
    

    throw exception in java

    Java has already provided some exception like.. NullPointerException, ArrayIndexOutOfBoundsException, NumberForamatException etc. These are condition arrise exception then JVM throw some predefined message error.

    public class throwEx {
    	
    		   public static void main(String args[]){
    		      try{
    			   char array[] = {'a','b','g','j'};
    			   System.out.println(array[78]);
    		      }catch(ArithmeticException e){
    			    System.out.println("Arithmetic Exception!!");
    		       }
    		   }
    	
    }
    

    output

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 78
    	at JUnit.throwEx.main(throwEx.java:8)
    

    How to throw your own exception explicitly using throw keyword

    package javacodepoint;
    
    public class MyOwnException extends Exception {
    	   public MyOwnException(String msg){
    		      super(msg);
    		   }
    }
    
    package javacodepoint;
    
    public class EmployeeTest {
    	static void  employeeAge(int age) throws MyOwnException{
    	      if(age < 0)
    	         throw new MyOwnException("Age can't be less than zero");
    	      else
    	         System.out.println("Input is valid!!");
    	   }
    	   public static void main(String[] args) {
    	       try {
    	            employeeAge(-2);
    	       }
    	       catch (MyOwnException e) {
    	            e.printStackTrace();
    	       }
    	   }
    
    }
    
    

    Output

    javacodepoint.MyOwnException: Age can't be less than zero
    	at javacodepoint.EmployeeTest.employeeAge(EmployeeTest.java:6)
    	at javacodepoint.EmployeeTest.main(EmployeeTest.java:12)

    throw keyword in java

    When any exception come during program excution , then JVM automatically throw exception to user information but programmer can defined own message depend on needed.

    package javacodepoint;
    
    public class ThrowExampleJava {
    	static void checkEligibiltyForVoting(int stuage, int stuweight){ 
    	      if(stuage<18 && stuweight<90) {
    	         throw new ArithmeticException("Person is not eligible for registration"); 
    	      }
    	      else {
    	         System.out.println("Entries Valid!!"); 
    	      }
    	   } 
    
    	   public static void main(String args[]){ 
    	     System.out.println("Welcome to the Registration process!!");
    	     checkEligibiltyForVoting(10, 39); 
    	     System.out.println("Have a nice day.."); 
    	 } 
    
    }
    

    output

    Exception in thread "main" java.lang.ArithmeticException: Person is not eligible for registration
    	at JUnit.ThrowExampleJava.checkEligibiltyForVoting(ThrowExampleJava.java:6)
    	at JUnit.ThrowExampleJava.main(ThrowExampleJava.java:15)
    Welcome to the Registration process!!
    

    throws keyword in Java

    1. The throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.

    2. When defining a method you must include a throws clause to declare those exceptions that might be thrown but doesnot get caught in the method.

    3. If a method is using throws clause along with few exceptions then this implicitly tells other methods that ? If you call me, you must handle these exceptions that I throw.

     class ThrowsDemo
    {
       static void throwMethod() throws NullPointerException
       {
           System.out.println ("Inside throwMethod");
           throw new NullPointerException (ThrowsDemo); 
       } 
       public static void main(String args[])
       {
           try
           {
              throwMethod();
           }
           catch (NullPointerException exp)
           {
              System.out.println ("The exception get caught" +exp);
           }
        }
    }
     

    Object Serialization and Persistence

    Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the objects data as well as information about the objects type and the types of data stored in the object. Object persistence, is the term you often hear used in conjunction with the issue of storing objects in databases.

    Multithreading and Synchronization

    In java when two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.

    Collection of Framework

    The collection framework provides a unified interface to store, retrieve and manipulate the elements of a collection, regardless of the underlying and actual implementation. This allows the programmers to program at the interfaces, instead of the actual implementation. Collection of Framework

    package java.io-> EOFException

    Signals that an end of file or end of stream has been reached unexpectedly during input.

    This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.

    package java.io-> Externalizable

    ans: Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

    The writeExternal and readExternal methods of the Externalizable interface are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. These methods supersede customized implementations of writeObject and readObject methods

    void writeExternal(ObjectOutput out) throws IOException

    void readExternal(ObjectInput in) throws IOException, ClassNotFoundException

    package java.io->Serializable

    Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

      private void writeObject(java.io.ObjectOutputStream out)
          throws IOException
      private void readObject(java.io.ObjectInputStream in)
          throws IOException, ClassNotFoundException;
      private void readObjectNoData()
          throws ObjectStreamException;
      

    The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

    The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput

    package java.io->StreamTokenizer

    The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

    package java.io->BufferedReader

    Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

    The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

      BufferedReader in
        = new BufferedReader(new FileReader("foo.in"));
      

    java.lang ->ArithmeticException

    Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

    java.lang->ArrayIndexOutOfBoundsException

    Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

    package java.lang -> AssertionError

    Thrown to indicate that an assertion has failed.

    The seven one-argument public constructors provided by this class ensure that the assertion error returned by the invocation:

          new AssertionError(expression)
      

    package java.lang -> Boolean

    The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

    In addition, this class provides many methods for converting a boolean to a String and a String to a code boolean, as well as other constants and methods useful when dealing with a boolean.

    package java.lang -> Byte

    The Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte.

    In addition, this class provides several methods for converting a byte to a String and a String to a byte, as well as other constants and methods useful when dealing with a byte.

    package java.lang -> Character

    The {@code Character} class wraps a value of the primitive type {@code char} in an object. An object of type {@code Character} contains a single field whose type is {@code char}.

    In addition, this class provides several methods for determining a characters category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.

    Character information is based on the Unicode Standard, version 6.2.0.

    The methods and data of class {@code Character} are defined by the information in the UnicodeData file that is part of the Unicode Character Database maintained by the Unicode Consortium. This file specifies various properties including name and general category for every defined Unicode code point or character range.

    package java.lang -> Class

    Instances of the class {@code Class} represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a {@code Class} object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code int}, {@code long}, {@code float}, and {@code double}), and the keyword {@code void} are also represented as {@code Class} objects.

    The following example uses a {@code Class} object to print the class name of an object:

          void printClassName(Object obj) {
              System.out.println("The class of " + obj +
                                 " is " + obj.getClass().getName());
          }
      

    package java.lang -> ClassCastException

    Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

          Object x = new Integer(0);
          System.out.println((String)x);
      

    package java.lang -> ClassLoader

    A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

    The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machines built-in class loader, called the bootstrap class loader, does not itself have a parent but may serve as the parent of a ClassLoader instance.

    Normally, the Java virtual machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the virtual machine loads classes from the directory defined by the CLASSPATH environment variable.

    The methods and constructors of objects created by a class loader may reference other classes. To determine the class(es) referred to, the Java virtual machine invokes the {@link #loadClass loadClass} method of the class loader that originally created the class.

    For example, an application could create a network class loader to download class files from a server. Sample code might look like:

        ClassLoader loader = new NetworkClassLoader(host, port);
        Object main = loader.loadClass("Main", true).newInstance();
             . . .
      

    java.lang ->ClassNotFoundException

    Thrown when an application tries to load in a class through its string name using:

    • The forName method in class Class.
    • The findSystemClass method in class ClassLoader .
    • The loadClass method in class ClassLoader.

    but no definition for the class with the specified name could be found.

    package java.lang -> Cloneable

    A class implements the Cloneable interface to indicate to the {@link java.lang.Object#clone()} method that it is legal for that method to make a field-for-field copy of instances of that class.

    Invoking Objects clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

    By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See {@link java.lang.Object#clone()} for details on overriding this method.

    Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

    package java.lang -> Comparable

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the classs natural ordering, and the classs compareTo method is referred to as its natural comparison method.

    The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

    Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals.

    Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

    package java.lang -> Compiler

    The Compiler class is provided to support Java-to-native-code compilers and related services. By design, the Compilerclass does nothing; it serves as a placeholder for a JIT compiler implementation.

    When the Java Virtual Machine first starts, it determines if the system property java.compiler exists. (System properties are accessible through {@link System#getProperty(String)} and {@link System#getProperty(String, String)}. If so, it is assumed to be the name of a library (with a platform-dependent exact location and type); {@link System#loadLibrary} is called to load that library. If this loading succeeds, the function named {@code java_lang_Compiler_start()} in that library is called.

    package java.lang -> Deprecated

    A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code

    package java.lang -> Error

    An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a ,normal, condition, is also a subclass of Error because most applications should not try to catch it.

    A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

    package java.lang -> Exception

    The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

    The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

    java.lang -> llegalStateException

    Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

    java.lang -> Iterable

    Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller.

    java.lang ->NullPointerException

    Thrown when an application attempts to use null in a case where an object is required. These include:

    • Calling the instance method of a null object.
    • Accessing or modifying the field of a null object.
    • Taking the length of null as if it were an array.
    • Accessing or modifying the slots of null as if it were an array.
    • Throwing null as if it were a Throwable value.

    java.lang ->Object

    Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

    Returns the runtime class of this {@code Object}. The returned Class object is the object that is locked by static synchronized methods of the represented class

    public final native Class getClass();

    Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by {@link java.util.HashMap}.
    public native int hashCode();

    Indicates whether some other object is "equal to" this one.

     public boolean equals(Object obj) {
            return (this == obj);
        }

    Creates and returns a copy of this object. The precise meaning of copy may depend on the class of the object. The general intent is that, for any object {@code x}, the expression:

          x.clone() != x
    will be true, and that the expression:
    	  
    protected native Object clone() throws CloneNotSupportedException;

    Returns a string representation of the object. In general, the {@code toString} method returns a string that textually represents this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

     public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }

    Wakes up a single thread that is waiting on this object monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object monitor by calling one of the {@code wait} methods.

     public final native void notify();

    Wakes up all threads that are waiting on this object monitor. A thread waits on an objects monitor by calling one of the {@code wait} methods.

     public final native void notifyAll();

    Causes the current thread to wait until either another thread invokes the {@link java.lang.Object#notify()} method or the {@link java.lang.Object#notifyAll()} method for this object, or a specified amount of time has elapsed.

     public final native void wait(long timeout) throws InterruptedException;

    Causes the current thread to wait until another thread invokes the {@link java.lang.Object#notify()} method or the {@link java.lang.Object#notifyAll()} method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

      public final void wait(long timeout, int nanos) throws InterruptedException {
            if (timeout < 0) {
                throw new IllegalArgumentException("timeout value is negative");
            }
    
            if (nanos < 0 || nanos > 999999) {
                throw new IllegalArgumentException(
                                    "nanosecond timeout value out of range");
            }
    
            if (nanos > 0) {
                timeout++;
            }
    
            wait(timeout);
        }

    Causes the current thread to wait until another thread invokes the {@link java.lang.Object#notify()} method or the {@link java.lang.Object#notifyAll()} method for this object. In other words, this method behaves exactly as if it simply performs the call {@code wait(0)}.

    public final void wait() throws InterruptedException {
            wait(0);
        }

    Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the {@code finalize} method to dispose of system resources or to perform other cleanup.

    protected void finalize() throws Throwable { }

    java.lang ->OutOfMemoryError

    Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

    java.lang ->Runnable

    The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

    A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods.

     public abstract void run();

    java.lang ->StackOverflowError

    Thrown when a stack overflow occurs because an application recurses too deeply.

    java.lang ->StackTraceElement

    An element in a stack trace, as returned by {@link Throwable#getStackTrace()}. Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created.

    java.lang ->String

    The {@code String} class represents character strings. All string literals in Java programs, such as {@code "abc"}, are implemented as instances of this class.

    Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

          String str = "abc";
      

    is equivalent to:

          char data[] = {a, b, c};
          String str = new String(data);
      

    Here are some more examples of how strings can be used:

          System.out.println("abc");
          String cde = "cde";
          System.out.println("abc" + cde);
          String c = "abc".substring(2,3);
          String d = cde.substring(1, 2);
      

    java.lang ->StringBuffer

    A thread-safe, mutable sequence of characters. A string buffer is like a {@link String}, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

    String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

    java.lang ->StringBuilder

    A mutable sequence of characters. This class provides an API compatible with {@code StringBuffer}, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for {@code StringBuffer} in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to {@code StringBuffer} as it will be faster under most implementations.

    The principal operations on a {@code StringBuilder} are the {@code append} and {@code insert} methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The {@code append} method always adds these characters at the end of the builder; the {@code insert} method adds the characters at a specified point.

    java.lang ->System

    The System class contains several useful class fields and methods. It cannot be instantiated.

    Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

    java.lang ->Thread

    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

    Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

    When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

    • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
    • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

    overloading java

    OverLoading is the mechanism of object oriented programming in which allow the class having two or more method have same same but different parameters is called OverLoading.

    Rules of overloading:

    1) types of parameters and order of parameters of both method should be different, either it is inheritance class or same class.

    Rules of overloading

    2) change in return type and parameters must change, otherwise it show compile time error.

    Rules of overloading

    package OverLoading;
    public class Addition {
    	public int addition(int x, int y){
    		return (x+y);
    	}
    	public int addition(int x, int y, int z){
    		return (x+y+z);
    	}
    	public double addition(double d, double b){
    		return (d+b);
    	}
    	public float addition(float a, float b){
    		return (a+b);
    	}
    	public static void main(String args[]){
    		System.out.println("Calling all method one by one for overloading..");
    		Addition additionObject = new Addition();
    		System.out.println("additon of int two argument ->"+additionObject.addition(10, 20)); 
    		System.out.println("additon of int three argument ->"+additionObject.addition(10, 10, 10));
    		System.out.println("additon of double two argument ->"+additionObject.addition(12.34, 34.12));
    		System.out.println("additon of float two argument ->"+additionObject.addition(40.1, 40.12));
    	}
    }
    
    
    output
    
    Calling all method one by one for overloading..
    additon of int two argument ->30
    additon of int three argument ->30
    additon of double two argument ->46.459999999999994
    additon of float two argument ->80.22
    

    Advantage of OverLoading

    1) Its increase the readibilty of java developers, no need to remember the same of function, only to take care of arguments only.

    Overriding java

    Overriding

    The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides.

    Rules of Overriding

    1) The method is must be inheritance in sub class.

    The method is must be inheritance in sub class

    2) Parameters and return type should be same name as per super class.

    The method is must be inheritance in sub class

    3) we can change the return type in child class, otherwise it gives incompatible with Overriding.addition(int, int) error

    we can change the return type in child class1

    4) we cannot reduce the access visibility of method in child class.

    we cannot reduce the access visibility of method in child class

    5) we can increase the access visibility of method in child class.

    we cannot reduce the access visibility of method in child class

    6) final, private and static can not be override in java.

    final, private and static can be override in java

    static can be override in java

    Advantage of overriding

    Child class (sub class) gives specific implementation to inheritance method without modifing parent class (base class). Overriding always happened on run time only.

    package Overriding;
    class company {
    		public int millage(){
    			return (20);
    	}}
    	class Hero extends company{
    		public int millage(){
    			return (50);
    		}}
    	class Bajaj extends company{
    		public int millage(){
    			return (60);
    		}}
    	class TVS extends company{
    		public int millage(){
    			return (90);
    	}}
    public class Overriding{
    	public static void main(String[] args) {
    		Hero hero = new Hero();	Bajaj bajaj = new  Bajaj();	TVS tvs = new TVS();
    		System.out.println("Hero ->"+hero.millage());
    		System.out.println("Bajaj ->"+bajaj.millage());
    		System.out.println("TVS ->"+tvs.millage());
    	}}
    

    Compile the First programme

    JavaFirstProgramme_compile

    After compilation , it create .class file like- className.class

    Two class in one java class

    TwoClassINSingleFile

    In this situation, you should compile this file by name of file like.. java1.java is the file name which have two class JavaFirstProgramm and JavaFirstProgramm1

    compile command: javac java1.java

    run :java JavaFirstProgramm

    run :java JavaFirstProgramm1

    CoVariant

    CoVariant is a return type, in which one method overrids , then return type of one overriding method is allow to same as sub type of overriding methods

    class CoVariant {
    	CoVariant getMessage() {
    		return this;
    	}
    }
    
    class CoVariantSub extends CoVariant {
    	CoVariantSub getMessage() {
    		return this;
    	}
    
    	void message() {
    		System.out.println("this is example of covariant overriding..");
    	}
    
    	public static void main(String args[]) {
    		new CoVariantSub().getMessage().message();
    	}
    }
    
    this is example of covariant overriding..
    

    what is advantage of rest web services over soap web services?

    1) SOAP means Simple Object Access Protocol but Rest mean Representational State Transfer.

    2) SOAP is a protocal but Rest is architecture of concept , it use like json, xml, text or any html resources for data exchange.

    3) SOAP use interface to expose the busineslogin like, @webservices interface servicesname, @webmethod methodname, but rest use URI to expose services like @path("/webservices")

    4)SOAP only work on xml for communication of data so this is heavy weigth, but Rest use json which is very light weigth.

    5) SOAP use WSDL(Web Services Description Language) but Rest use WADL (Web Application Description Language)

    6)SOAP use SMTP but Rest use http

    7) SOAP use only POST method to send data but REST use both POST and GET.

    Interface changes in Java 8

    default

    default is a keyword, but now we add default to make default method in interface. we prefix as default.

    public interface Java8InterFace {
    
    	 void method();
    	 default void method1(){
    		 System.out.println("default method impl inside interface");
    	 }
    }
    

    If you define method without default , it gives compiler error.

    Interface changes in Java 8

    What happens , when 2 interface has same default method, which inherit in main class ?

    Java8InterFace

    Interface changes in Java 8

    Java8InterFace2

    Interface changes in Java 8

    mainClass

    Interface changes in Java 8

    how can we resolve the same imbiguity issue in java8, during implementing interfaces

    Interface changes in Java 8

    Link
    Eng. Ravi Kumar Verma

    Simple and dept learning technology is very important part in software development. Same story has been implemented at this site, so learn and implement the inovative things, Thanks

    Ravi Kumar Verma