Thursday, June 22, 2017

Java-Wrapper classes and Command Line Arguments

Wrapper classes
---------------
A wrapper class is a class which is used to represent primitives as objects i,e we can convert primitives to objects using wrapper classes.

We need to convert primitives to objects because there are situations where we need to use only objects like while working with collections we should use only objects.

For each primitive we have one wrapper class in java.

Primitive                wrapper
--------                 -------
char                     Character
byte                     Byte
short                    Short
int                      Integer
long                     Long
float                    Float
double                   Double
boolean                  Boolean


All the wrapper classes are available in java.lang.*

AutoBoxing and unboxing
-----------------------

Autoboxing
----------
The process of converting primitives to  objects is known as boxing.

Converting primitive to object automatically is known as autoboxing.


Program
-------
class Test
{
  public static void main(String args[])
  {
      int a=10;//primitive
      Object obj=a;//object
      System.out.println(obj);
  }
}



Autounboxing
------------
converting object to primitive  is known as unboxing.

Converting object to primitive automatically is known as Autoautoboxing.

Program
-------
class Test
{
  public static void main(String args[])
  {
      Object obj=10;
      int a=(int)obj;
      System.out.println(a);
  }
}


Methods of Wrappers
-------------------
parseXXX()
xxxValue()
valueOf()
toString()


Heirarchy of Wrappers
---------------------
Object
|
Number
|
Byte  Short  Integer Long  Float Double

All warapper classes implements Serializable interface.

parseXXX()
----------
This method is used to convert a String type of data into required primitive.

Every Wrapper class is having one parseXXX() method.


public static byte parseByte(String);
public static short parseShort(String);
public static int parseInt(String);
public static float  parseFloat(String);
public static double parseDouble(String);
public static long parseLong(String);
public static boolean parseBoolean(String);
mn
All the parseXXX() methods are static methods.

All the parseXXX() methods throws checked exception NumberFormatException.


CommandLine arguments
---------------------
These accepts values from command prompt.

The parameter to main() method in java is known as command line argument i,e String args[].


How to pass values from command prompt to command line arguments
----------------------------------------------------------------
syntax
------
java ClassName/fileName  value1 value2 value3 .....

ex:
java Test 10 20 30


Here we should pass command line arguments from command prompt while executing a java program.

Here First parameter is copied to args[0].
Here second parameter is copied to args[1].
Here Third parameter is copied to args[2].

and so on.

i,e 10 is copied to args[0]
    20 is copied to args[1]
    30 is copied to args[2]


The default size of command line argument is zero.

i,e the size of String args[] is zero(0) by default.

When we pass values from command prompt automatically size increases and the size of String args[] will be no of values we are passing from command prompt.

Program
-------
class Test
{
   public static void main(String args[])
   {
       int a=Integer.parseInt(args[0]);
       System.out.println(a);
   }
}
             

save as Test.java

compile
-------
javac Test.java

Run
---
java Test 10.

Program
-------
class Test
{
  public static void main(String args[])
  {
       int a=Integer.parseInt(args[0]);
       int b=Integer.parseInt(args[1]);
       int c=a+b;
       System.out.println(c);
   }
}

Note:we should pass proper string while passing to parse method otherwise it leads to NumberFormatException.

xxxValue()
----------
This method is used to convert a wrapper object to required primitive.


Methods
-------
public byte byteValue();
public short shortValue();
public int   intValue();
public long longValue();
public float floatValue();
public double doubleValue();
public boolean booleanValue()
public char charValue();

These methods are used to convert a wrapper object to its equivalent primitive automatically.They perform auto unboxing.

Program
-------
class Test
{
  public static void main(String args[])
  {
     
      Integer i=new Integer(10);//Autoboxing
      int j=i.intValue();//Autounboxing
       System.out.println(i);
       System.out.println(j);

 }
}


valueOf()
---------
This method is used to perform autoboxing i,e it converts a primitive to its equivalent wrapper object.

It is represented in the following forms

public static Integer valueOf(int);
This method converts a primitive(int) to wrapper(Integer).

public static Integer valueOf(String);
This method converts a integer string to wrapper(Integer).

similarly every wrapper class has  valueOf() method as shown below
public static Byte valueOf(byte);
public static Byte valueOf(String);
public static Short valueOf(short);
public static Sort valueOf(String);
public static Long valueOf(long);
public static Long valueOf(String);
public static Float valueOf(float);
public static Float valueOf(String);
public static Double valueOf(double);
public static Double valueOf(String);
public static Boolean valueOf(boolean);
public static Boolean valueOf(String);

Program
-------
class Test
{
  public static void main(String args[])
  {
       double d=10.5;
       Double val=Double.valueOf(d);
       System.out.println(val);  
 
  }
}

Program
-------
class Test
{
  public static void main(String args[])
  {
       String d="10.5";
       Double val=Double.valueOf(d);
       System.out.println(val);  
 
 }
}


toString()
----------
This method is used to convert any wrapper to String type


syntax
------
public String toString();

Program
-------
class Test
{
  public static void main(String args[])
  {
      Boolean b=true;
      String s=b.toString();  
      System.out.println(s);
   
 }
}

Dont use methods of wrapper convert primitive to wrapper.
Note:
we can also convert primitive to wrapper object or a numeric String to a warpper by using constructors of Wrapper classes.

Constructors summary
--------------------
Byte class
   Byte(byte)
   Byte(String)

Short class
   Short(short)
   Short(String)

Integer class
   Integer(int)
   Integer(String)

Long class
  Long(Long)
  Long(String)

Float class
  Float(float);
  Float(double);
  Float(String);

Double class
  Double(double)
  Double(String)

Boolean class
  Boolean(boolean)
  Boolean(String)

Character class
  Character(char)

Java-Exception Handling

Exception handling
------------------
Exception is a  runtime error which terminates a program abnormally.

Errors
------
It is a deviation in a program.

There are 3 types of errors

i)compiletime/syntax errors.
ii)Runtime errors.
iii)logical errors.

compile time errors
-------------------
Errors raised due to wrong syntax.

ex:
semicolon missing;
undefined symbol a
etc

Runtime error
-------------
A runtime error causes a program to terminate abnormally at the time of executing a program.

ex:
ArrayIndexOutOfBoundsException.
ArithmeticException.

Runtime errors is also called as Exceptions.

logical errors
--------------
It causes to get wrong output.


Program
-------
class Test
{
   public static void main(String args[])
   {
     int a=10,b=0,c;
     c=a/b;//line1
     System.out.println(c);
     System.out.println("The end");

   }
}

The above program raises runtime error @line1, because we are trying to divide a number by zero
saying

Exception in thread "main" java.lang.ArithmeticException: / by z
        at Test.main(Test.java:6).



An Exception is raised because of a risky statement in a program.

In the abovne code
c=a/b; is a risky statement.

A risky statement may raise exception but we can't guarantee that exception is always raised because of risky statement it depends on input provided by user.

Exception Handling
------------------
It is a mechanism which avoids abnormal termination of a program.

we implement execption handling using the following keywords

i)try
ii)catch
iii)finally
iv)throws
v)throw

try
---
A try block consists of   risky statements.

Whenever an execption is raised in try block then it is thrown to catch block.

syntax
------
try
{
//risky statements
}

catch
-----
A catch block catches the exception thrown from try block.

A catch catches the exception thrown from try block and avoids abnormal termination of a program

Here catch is handling the exception so catch block is called as EXception handler.

syntax
------
catch(ExceptionType reference)
{
//statements
}

we can handle exception by using try/catch block.
syntax
------
try
{
//risky statements
}
catch(ExceptionType reference)
{

}

Program
-------
class Test
{
   public static void main(String args[])
   {
     int a=10,b=0,c;
     try
     {
       c=a/b;
       System.out.println(c);
     }
     catch(ArithmeticException e)
     {

     }
     System.out.println("The end");
  }
}
Execution flow of try/catch
---------------------------
A catch block is executed only if an execption is raised in a try block otherwise a catch block is never executed.

finally
-------
A finally block is used to perform cleanup operations.

A finally block can be declared after try block or catch block.

syntax
------
try
{
}
catch()
{
}
finally
{
}

or
try
{
}
finally
{

}

Cleanup operations means closing connections like

closing file connections.
database connections.
network connections.

Program
-------
import java.util.Scanner;
import java.util.InputMismatchException;

class Test
{
  public static void main(String args[])
  {
    Scanner s=new Scanner(System.in);
    System.out.println("enter a");
    try
    {
      int a=s.nextInt();
      System.out.println(" a"+a);

    }
    catch(InputMismatchException e)
    {
         System.out.println(e);

    }
    finally
    {
        s.close();    

    }
    System.out.println("The end");

 
  }
}


Excecution flow try/catch/finally
---------------------------------
A try block is always executed.

A catch block is executed only when execption is raised in try block.

A finally block is always executed irrespective of exception.

A try block must be declared with a catch block or finally block.


which of the following declarations are valid?

i)try
  {
  }
  catch()
  {
  }

ii)try
  {
  }
  catch()
  {
  }
  finally
  {
  }
iii)
  try
  {
  }
  finally
  {
  }

iv)try
   {
   }
v)catch()
  {
  }


Exception Heirarchy
-------------------
    Object
      ^
      |
    Throwable
 ^                                     ^      
 |                                     |
Exception                              Error
|                                       |
IOException      RuntimeException      StackOverFlow
ServletException    |                  |Error
etc               ArithemeticException |Assertion
                  ArrayIndexOutOfBounds|Error
                  Exception
                  NullPointerException
                  etc



Object is the super class of all classes in java.

Throwable is the super class of Exception and Error.

Exception is used to handle programmatic issues.

Error is used to handle system issues.


Types of exceptions
-------------------
Exceptions are of 2 types
i)checked
ii)Unchecked

checked
-------
Exceptions which are checked by compiler are called checked exceptions.

Exception is always raised at runtime but compiler will raise an error if there any possibility of Exception at runtime such type of exceptions are checked exceptions.

Exceptions like IOException,ServletException etc are checked exceptions.

Unchecked
---------
Exceptions which are checked by jvm and not checked by compiler are called unchecked exceptions.

RuntimeException and its subclasses and Error and its subclasses are unchecked exceptions and remaining are checked exceptions

Exception and Throwable are partially checked exceptions because they has both checked and unchecked classes as subclasses.


Note:Majority of Exception classes are available in java.lang.* package.


throws
------
throws is used to throw or delegate an exeception from a method.

throws is used to throw only checked exceptions.

syntax
------
accessmodifier returntype methodname()  throws ExceptionType
{


}
Program to demonstrate handling checked exception IOException
-------------------------------------------------------------
Program
-------
import java.io.*;
class Test
{
  public static void main(String args[]) throws IOException
  {
     DataInputStream dis=new DataInputStream(System.in);
     String name=dis.readLine();
    System.out.println(name);
 
  }
}

DataInputStream is a class available in java.io.*;

readLine() is used to input value from keyboard.

readLine() method throws checked exeception,IOException.

we can handle a checked exeception in 2 ways

i)Using try/catch
ii)using throws keyword.

In the above code we are hadling IOException using throws,here we are simply forwarding(delegating) exception to jvm but we are not handling exception,it is jvm which handles exeception here.


Note:if we want to handle exception explicitly in the code itself then we should use try/catch block.

try with mutiple catches
------------------------
we can declare a try block with mutiple catch clocks.

if we declare muiptle risky statements in try block,to handle this multiple exceptions thrown from try we can use multiple catch blocks.

syntax
-----
try
{
//risky statement1
//risky statement2
.
.

}
catch(ExceptionType1 reference)
{
}
catch(ExceptionType2 reference)
{
}
.
.
.



program to handle AE and AIOOBE using try with multiple catches
---------------------------------------------------------------
import java.io.*;
class Test
{
  public static void main(String args[])
  {
    int a=10,b=0,c;
    int x[]={1,2,3,4,5};

    try{
      c=a/b;//line1
      System.out.println(c);
      System.out.println(x[6]);//line2
    }
    catch(ArithmeticException e)
    {
      System.out.println(e);
 
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
         System.out.println(e);
     
    }

    System.out.println("Byee");
 
  }
}


In the above code we are declaring 2 risky statements @line1,@line2


@line1 may raise ArithemeticException.

@line2 may raise ArrayIndexOutOfBoundsException


to  handle both the exceptions we are declaring  catch blocks,one with ArithemeticException and the other with ArrayIndexOutOfBoundsException.


If exception is raised @line1 then its corresponding catch block with ArithmeticException  is executed .

If exception is raised @line2 then its corresponding catch block with ArrayIndexOutOfBoundsException  is executed.


A catch block handling all the exceptions
-----------------------------------------
A cathc block can handle any exception thrown by try block if we declare the parameter of catch as super class i,e

if we declare "Throwable" class as a parameter it can handle any exception/error thrown from try block.

syntax
------
try
{

}
catch(Throwable e)
{
}


if we declare "Exception" as a parameter it can handle any exception thrown from try block but it cannot handle errors

syntax
------
try
{

}
catch(Exception e)
{
}

if we declare "Error" as a parameter it can handle any error thrown from try block but it cannot handle exceptions.

syntax
------
try
{

}
catch(Error e)
{
}

Program to handle mutiple exceptions using a catch block
--------------------------------------------------------

//what is the output of the following code?
class CatchTest
{
    public static void main(String args[])
    {
   
         int a=10,b=0,c;
         int x[]={1,2,3,4,5};
         
         try
         {
            c=a/b;
            System.out.println(c);
            System.out.println(x[4]);
         }
         catch(Exception e)
         {
              System.out.println(e);
         }
         catch(ArithmeticException e)
         {
              System.out.println(e);
         }
         catch(ArrayIndexOutOfBoundsException e)
         {
              System.out.println(e);
         }
       
    }
}
       
/*options
-------
i)CE
ii)RE
iii)compiles successfully
iv)compiles and executes*/


Reason
------
In the above code we get compilation error because the catch block with exception as parameter will handle all the excetions thrown from try block,and other catch blocks never get a chance for execution.

so we get a compilation error saying

"Exception ArithmeticException has already been  caught"

same for ArrayIndexOutOfBoundsException.


Note:
Whenever we are declaring mutiple catch blocks,always declare parameters to catch blocks from sub class to super calss i,e  declare a catch block with subclass as parameter first and then declare a catch block with its super class as as a parameter.


Rewriting above program to fix compilaion error
------------------------------------------------
class CatchTest
{
    public static void main(String args[])
    {
   
         int a=10,b=0,c;
         int x[]={1,2,3,4,5};
         
         try
         {
            c=a/b;
            System.out.println(c);
            System.out.println(x[4]);
         }
         catch(ArithmeticException e)
         {
              System.out.println(e);
         }
         catch(ArrayIndexOutOfBoundsException e)
         {
              System.out.println(e);

         }
         catch(Exception e)
         {
              System.out.println(e);
         }

   }
}



Here catch with subclasses as parameter is declared first and catch block with a superclass[Exception] is kept last in the heirarchy.


UserDefined exceptions
----------------------
Exceptions  are of 2 types

i)Built-in exceptions
ii)Userdefined


Built-in are predefined or existing exceptions.

NullPointerException.
ArithmeticException.

etc

Exceptions developed by developer are called userdefined exceptions.


We can create our own exceptions by extending a class from built-in exception.

The nature of userdefined exception depends on the kind of super class it is extending.

steps for creating userdefined exceptions
-----------------------------------------
step1:extend a class from a built-in exception like Exception\Throwable\Error\RuntimeException etc depends on requirement.

accessmodifier class ClassName extends Exception
{


}
step2:declare a parameterized constructor with String as a parameter.
accessmodifier class ClassName extends Exception
{
  accessmodifier ClassName(String msg)
  {
 
  }


}
step3:Declare super() in the contructor and deligate the String parameter to super class constructor.
accessmodifier class ClassName extends Exception
{
  accessmodifier ClassName(String msg)
  {
       super(msg);
 
  }
}

throw
-----
A throw keyword is used to throw an exception from a try block to catch block programatically or explicitly.

we can throw both built-in and userdefined exceptions using throw keyword but it is recommended to use throw keyword to throw userdefined exceptions because predefined exceptions are automatically thrown from try block catch block by jvm.

syntax
------
throw new ExceptionType(args);

ex:
throw new ArithmeticException("Division by zero");
throw new InvalidSalaryException("Incorrect Amount");


Program to demonstrate userdefined exception
--------------------------------------------
//create a Exception InsufficientFundsException

package com.manohar.java.exceptions;
public class InsufficientFundsException extends  Exception{
   public InsufficientFundsException(String msg){
  super(msg);
   }
}
//create a BalTest.java to test exception
---------------------------------------
package com.manohar.java.test;
import java.util.Scanner;
import com.manohar.java.exceptions.InsufficientFundsException;
public class BalTest {
public static void main(String[] args) {
// declaring variables
double bal = 10000.00;
double amount;

// creating scanner
Scanner s = new Scanner(System.in);
System.out.println("Enter amount");
amount = s.nextDouble();

if (amount > bal) {
try {
throw new InsufficientFundsException("Please enter proper amount");
}
catch (InsufficientFundsException e) {
System.out.println(e);
}
}
else{
System.out.println("Amount withdrwn "+amount);
System.out.println("Ramaining bal "+(bal-amount));
}
}
}

Displaying Exception Summary
----------------------------
Exception summary can be displayed 3 ways.
i)Printing reference of Exception.
ii)getMessage().
iii)printStackTrace().


i)Printing reference
This approach displays both exception and message
System.out.println(e):

ii)getMessage()
This approach displays only message
System.out.println(e.getMessage());

iii)printStackTrace()
This method  display complete summary of exception
e.printStackTrace();


Program
-------
class Test
{
  public static void main(String args[])
  {
     int a=10,b=0,c;
     try
     {
       c=a/b;
       System.out.println(c);
     }
    catch(ArithmeticException e)
    {
      System.out.println(e.getMessage());
      System.out.println(e);
      e.printStackTrace();
    }
}
}

output
------
/ by zero//getMessgae()
java.lang.ArithmeticException: / by zero//printing reference
java.lang.ArithmeticException: / by zero//stack Trace
        at Test.main(Test.java:8)


catch with multiple parameters
------------------------------
We can declare multiple paramters with a catch block from 1.7 version onwards.

syntax
------
try
{
//statements
}
catch(ExceptionType1|ExceptionType2|...  reference)
{

}

Program
-------
class Test
{
  public static void main(String args[])
  {
     int a=10,b=10,c;
     int x[]={1,2,3,4,5};
     try
     {
       c=a/b;
       System.out.println(c);
       System.out.println(x[6]);

     }
    catch(ArithmeticException|ArrayIndexOutOfBoundsException e)
    {
      e.printStackTrace();
    }
}
}

try with resources
------------------
Generally we use finally block to perform clean up operations but by using try with resources we dont need to use finally block because closing connections is automatically done by using try with resources.


syntax
------
try(rerefence type)
{

}
catch(ExceptionType e)
{
}

Program
-------
import java.util.*;
class Test
{
  public static void main(String args[])
  {
    try(Scanner s=new Scanner(System.in))
    {
       System.out.println("Enter a");
       int a=s.nextInt();
       System.out.println(a);
    }
    catch(InputMismatchException e)
    {
      e.printStackTrace();
    }
    System.out.println("The end");
}
}

try with resources reduces length of the code because it avoids usage of finally block.


Nested try/catch block
----------------------
A try/catch block within try or catch or finally blocks is known as nested try catch

syntax
------
try
{
   try{
   //
   }
   catch(ExceptionType e)
   {
   }
}
catch(ExceptionType e)
{
     try{
   //
   }
   catch(ExceptionType e)
   {
   }
}
finally
{
   try{
   //
   }
   catch(ExceptionType e)
   {
   }
}

throw                            throws
-----                            ------
throws exception              throws exception from a method
from a try block
programmatically

used to userdefined           used to throw checked exceptions
exceptions


syntax                           syntax
------                          --------
throw new ExceptionType("");   accessmodifier returntype methodname()                                throws  ExceptionType
                               {
                                 //
                               }

Java-packages

packages
--------
A package is collection
classes
interfaces
enum

It is a reusable component
It provides code modularization
It avoids naming conflict.
It provides code optimization.
Maintenance of project is easy using packages.


Types of packages
-----------------
i)Predefined package.
ii)Userdefined package.


Built-in/existing packages are predefined.

java.lang.*;
It is a General purpose package which consists of classes and interfaces like
System
String
Runnable
etc

It is also called default package because
it is automatically imported by a compiler if developer is not importing.

java.util.*;
It  consists of classes like
Stack,Queue,LinkedList etc.

java.io.*;
It is used to perform input/output operations(file operations)
FileInputStream.
FileOutputStream.

java.sql.*;
It is used to perform jdbc operations.
It consists of interfaces like
Connection
Statement
etc.

java.applet.*;
java.awt.*;
javax.swing.*;

The above packages are used to perform GUI programming.

Userdefined packages
--------------------
package defined or created by developer is known as userdefined package.


How to declare a package.
-------------------------
we declare a package by using a keyword "package".

syntax
------
package packagename;

ex:
package  pack1.*;

package declarartion must be the first statetment in a program.

packages must be declared in lowercase.


why packages
------------
Grouping related classes into  a single unit.

Reusability.

packages avoids naming conflict.

packages supports code modularization.

readability.


creating userdefined package;

syntax
------
package packagename;
accessmodifier class Class1
{
}
accessmodifier class Class2
{
}
.
.
accessmodifier interface Interface1
{
}
accessmodifier interface Interface2
{
}
.
.
accessmodifier enum EnumName1
{
}
.
.


Program to add a class to package
---------------------------------
package pack1;
public class A
{
  public void m1()
  {
    System.out.println("m1");
  }
}

How to save a package.

save as
ClassName.java
ex:
A.java

How to compile a package
------------------------
javac -d . Classname.java

-d is a flag which creates a directory(folder) with the name of a package declared in a program.

.(dot) represents current directory.

similary Add 2 more classes to a package
package pack1;
public class B
{
  public void m1()
  {
    System.out.println("m1");
  }
}
save as B.java


package pack1;
public class C
{
  public void m1()
  {
    System.out.println("m1");
  }
}
save as C.java

importing packages
------------------
We import a package by using a new keyword "import".

Types of import
---------------
implicit.
explicit.

implicit import
---------------
All the members of a package are automatically available for  a program,such an import is called implicit import.


syntax
------
import packagename.*;

ex:
import java.lang.*;
import pack1.*;

Program to demonstrate implicit import
--------------------------------------
import pack1.*;
class Test
{
  public static void main(String args[])
  {
      A a=new A();
      a.m1();

      B b=new B();
      b.n1();
 
      C c=new C();
      c.n1();

  }
}

Explicit import
---------------
Import a specific class/interface/enum to  a program is known as explicit import.

syntax
------
import packagename.ClassName;
or
import packagename.InterfaceName;
or
import packagename.EnumName;

ex:
import java.lang.Math;
import pack1.A;

Program to demonstrate explicit import
--------------------------------------
import pack1.A;
import pack1.B;

class Test
{
  public static void main(String args[])
  {
      A a=new A();
      a.m1();

      B b=new B();
      b.n1();
 
   
  }
}

Here only A,B classes are imported to Test class.


static import
-------------
A static import is used to invoke static methods of a class without using classname.


syntax
------
import static packagename.ClassName.*;

ex:
import static packagename.Math.*;

Program
-------
import static java.lang.Math.*;
public class Test  {
public static void main(String[] args) {

       System.out.println(sqrt(25.0));
       System.out.println(sqrt(45.0));
       System.out.println(sqrt(36.0));
       System.out.println(sqrt(64.0));
     }
}

In the above code we are calling sqrt() method of Math class without using classname,this is possible because we are using static import.

static import increases performance of an application but at the same time it is confusing to the developer.

Fully Qualified Name of a class
-------------------------------
we can directly use a class or member of a package in a program by using fully qualified name without importing a package.

syntax
------
packagename.membername

ex:
java.util.Scanner

Program
-------
public class Test  {
public static void main(String[] args) {
int a;
java.util.Scanner  scanner=new java.util.Scanner(System.in);
System.out.println("enter a");
a=scanner.nextInt();
System.out.println(a);
   
}
}

This is used for instant purpose.

creating packages in eclipse
----------------------------
open eclipse-->

file-->new--->java project-->

projectname--->packages

select-->use default jre.

goto package explorer-->Expand project-->src-->rightclick-->new-->package-->
                    name--->test

Adding a class to a package in eclipse
--------------------------------------
Goto Project-->packages-->src-->test-->right click on package-->new-->class-->
                   Name-->A-->ok

Program
-------
package test;

public class A {
public void m1()
{
System.out.println("m1");
}
}


Add 1 more classe to test package

package test;

public class B {
public void m1()
{
System.out.println("B");
}
}

importing classes  of one package in another package in eclipse
-------------------------------------------
create another package pack1.

Add a class Demo.

package pack1;

import test.A;
import test.B;
public class Demo {
public static void main(String[] args) {
A a=new A();
B b=new B();
a.m1();
b.m1();

}

}

accessmodifiers in packages
---------------------------
public members are accessible through out project.

default members are accessible within a package.

private members are accessible within a class itself.

protected members are accessible anywhere in same package and by sub class of other package.

Program
-------
package test;
public class A {
protected void m1()
{
System.out.println("A");
}
}


package pack1;
import test.A;
public class Demo extends  A{
public static void main(String[] args) {
        Demo d=new Demo();
        d.m1();
}
}

In the above program we are invoking the protected method m1() from test package in pack1 by extending class A to Demo as shown in the above code.

Nested packages
---------------
A package within another package is known as nested package.

syntax
------
package package1.package2.package3...;

ex:
package pack1.pack2;

Nested packages provides better modularization of related classes,interfaces,enum.

Java-interfaces

interface
---------
interface is similar to a class which consists

final fields
abstract methods
default methods
static methods

we declare interface using keyword "interface"

syntax
------
accessmodifier interface interfacename
{
  //final fields
  //abstract methods
  //default methods
  //static methods
}

ex:
 public interface Shape
 {
    public static final double pi=3.14;
    abstract public double area();
 }

By default variables of interface are public static and final.

By default methods of interfaces are public and abstract.

we implement an interface in a class.

we use the keyword "implements" to implemet interface in a class.

syntax
------
interface InterfaceName
{

}
class SubClass implements InterfaceName
{

}

A -----variable cannot be modified.
final variables  are used to declare-----
-------is the only modifier declared with local variables.
------method cannot be overridden.
------and ----- combination is illegal.
------class cannot be inherited.
we can restrict inheritance in ---ways and they are -------and -------.
interface consists of---,---,---,---.
------keyword is used to declare interface.
variables of interface are by default---,---,---.
abstract methods of interface are by default ---and ---.
we  -------interface in a------using------keyword.


we override abstract methods of interface in a sub class.

if we implement interface in a class we should override all the abstract methods of interface in a subclass otherwise the subclass also must be declared as abstract.

we cannot instantiate interfaces.

Program
-------
package com.manohar.java;
interface  I1{
void m1();
void m2();
void m3();
}
public class I1Impl implements  I1 {

@Override
public void m1() {
 System.out.println("m1");
}

@Override
public void m2() {
 System.out.println("m2");

}

@Override
public void m3() {
 System.out.println("m3");

}
public static void main(String[] args) {
  I1Impl  i1=new I1Impl();
  i1.m1();
  i1.m2();
  i1.m3();
 
}

}

Multiple inheritance using interfaces
-------------------------------------
Deriving a subclass from 2 or more super classes is known as multiple inheritance.

we can implement any number of interfaces in a subclass depends on requirement.

syntax to implement multiple interfaces in a subclass
--------
interface interface1
{

}
interface interface2
{

}
.
.
.

class SubClassName implements interface1,interface2,...
{
//
}

In java we can extend only one class from another class whereas we can implement multiple interfaces in a subclass.

Program
-------
package com.manohar.java;
interface I1
{
public abstract void m1();
public abstract void m2();
}
interface I2{
public abstract void n1();
public abstract void n2();
}
public class I1Impl implements  I1,I2{

@Override
public void m1() {
  System.out.println("m1");
}
@Override
public void m2() {
  System.out.println("m2");

}
@Override
public void n1() {
  System.out.println("n1");
}
@Override
public void n2() {
  System.out.println("n2");
}

public static void main(String[] args) {
I1Impl  impl=new I1Impl();
impl.m1();
impl.m2();
impl.n1();
impl.n2();


//
I1 i1=new I1Impl();
i1.m1();
i1.m2();

I2 i2=new I1Impl();
i2.n1();
i2.n2();


}

}

interfaces supports loose coupling.

coupling
tight coupling
loose coupling(interfaces)

coupling
--------
The degree of dependency of one class on another is called as coupling.

Tight coupling
Loose coupling


Tight coupling
--------------
The degree of dependecy of one class on another is high such kind of coupling is called tight coupling.

ex:
class A
{
  B b=new B();


}
class B
{
   C c=new C();


}
class C
{

}

In the above code if A must exist before that B must exist,if B must exist before that C must exist.Here there is a  dependecy of one class on another such kind of dependency is called Coupling.

Loose coupling
--------------
if there is less dependency of one class on another we call this as loose coupling.

we can accomplish loose coupling by using pojo-poji model.


POJI--Plain old java  interface[simple java interface].
POJO--Plain old java Object[simple java class].


In a simple note implementing an interface in a class is known pojo-poji model which is  higly useful in frameworks.

Program
-------
interface Vehicle
{
   public abstract void move();
 
}
class Bus implements Vehicle
{
   public void move()
   {
     System.out.println("Hey iam on Bus");
   }
}
class Car implements Vehicle
{
   public void move()
   {
     System.out.println("Huuu iam on Car");
   }
}
class Journey{
  private Vehicle v;
  public Journey(Vehicle v)
  {
     this.v=v;
  }
  public void travel()
  {
    v.move();
  }
}
class Test
{
  public static void main(String args[])
  {
     Bus b=new Bus();
     Car c=new Car();

    Journey j1=new Journey(c);
    j1.travel();
  }
}


In the above code we are implementing Vehicle interface in Bus and Car classes.

This approach makes objects loosely coupled,as we know from dynamic method dispatch a super class refer to a sub class object,an interface reference also can refer to its implementation class objects.

May be we can't instantiate interfaces,abstract classes but still the reference of interface or abstract class can refer to a subclass to object.

This approch is very popular in jdbc,spring,hibernate etc.

In the above code we are declaring Journey class,it consists of Vehicle as instance variable.

we are initializing Vehicle through constructor as shown in the above code.

Declaring object of one class in another class is called as HAS-A relation also this called as composition.

In the code Vehicle is called as dependency in Journey class.

Journey is called dependent.

In tight coupling if we make any changes to a dependency automatically it will affect dependent i.e if we make changes to Bus or Car then Journey will get affected.see below code.

ex:
class Journey
{
  Bus b=new Bus();
  ..
  ..
}
Here in the above  code if we replace Bus with Car i,e if we change dependency then Journey get affected.

So whenever we make changes to dependency it is going to impact dependent to avoid this loose coupling is introduced.

we can achieve loose coupling with above approach declared in Journey class,here we are using inteface reference to refer to subclass objects using constructor injection.

Here to the constructor we may pass Car object or Bus object we dont need to make any changes to Journey,so it reduces dependency of objects in a class.

Constructor injection
---------------------
Passing primitives or objects to a constructor is called Constructor injection.


case1:
if 2 interfaces has same methods then it is sufficient to provide a common implementation for both for these interfaces in a subclass for one time.

Program
-------
interface I1
{
  public abstract void m1();
}
interface I2
{
  public abstract void m1();
}
class I1I2 implements I1,I2
{
   public void m1()
   {
     System.out.println("m1");
   }
   public static void main(String args[])
   {
     I1I2 i1=new I1I2();
     i1.m1();
   }

}
 

case2:if 2 interfaces has same variables then we should invoke them in a sub class using InterfaceName,as we know variables of interface are final static and public,so we can access a variable of inteface using InterfaceName,otherwise it leads to ambiguity error.


Program
-------
interface I1
{
   int a=10;
}
interface I2
{
  int a=20;
}
class I1I2 implements I1,I2
{
   public void m1()
   {
     System.out.println("a is "+I1.a);
     System.out.println("a is "+I2.a);

   }
   public static void main(String args[])
   {
     I1I2 i1=new I1I2();
     i1.m1();
   }

}
 

Extending interfaces
--------------------
It is possible to extend one interface  from another interface.

syntax
------
accessmodifier interface Interface1
{
//

}
accessmodifier interface Interface2 extends Interface1
{
//

}

Program to demonstrate extending one interface from another and implementing in a subclass.
--------------------------------------------------
interface I1
{
   public abstract void m1();
   public abstract void m2();

}
interface I2 extends I1
{
   public abstract void m3();
}
class I1I2 implements I2
{
   public void m1()
   {
     System.out.println("m1");
 
   }
   public void m2()
   {
     System.out.println("m2");
 
   }
   public void m3()
   {
     System.out.println("m3");
 
   }
 
   public static void main(String args[])
   {
     I1I2 i1=new I1I2();
     i1.m1();
     i1.m2();
     i1.m3();

   }

}

In the above code we are extending I2 from I1 and implementing I2 in a subclass I1I2,here if we impement I2 in a subclass it is sufficient and we should override both the abstract of I1,I2.

case1:
we can extend multiple interfaces to another interface i,e multiple inheritance is possible between interfaces.

Program
-------
interface I1
{
   public abstract void m1();
   public abstract void m2();

}
interface I2
{
   public abstract void m3();
}
interface I3 extends I1,I2
{
   public abstract void m4();
}

class I1I2 implements I3
{
   public void m1()
   {
     System.out.println("m1");
 
   }
   public void m2()
   {
     System.out.println("m2");
 
   }
   public void m3()
   {
     System.out.println("m3");
 
   }
 
   public void m4()
   {
     System.out.println("m4");
 
   }
 
   public static void main(String args[])
   {
     I1I2 i1=new I1I2();
     i1.m1();
     i1.m2();
     i1.m3();
     i1.m4();

   }

}

Hybrid multiple inheritance
---------------------------
It is possible to extend a class and implement interfaces together in a subclass.

syntax
------
class Class1
{

}
interface I1
{

}
interface I2
{

}
..
class SubClass extends Class1 implements I1,I2,...
{

}

Program
-------
class Class1
{
   public void m1(){
     System.out.println("m1");
   }

}
interface I1
{
   public abstract void m2();
}

class ABC extends Class1 implements I1
{
   public void m2()
   {
     System.out.println("m2");
 
   }
   public static void main(String args[])
   {
     I1I2 i1=new I1I2();
     i1.m1();
     i1.m2();
 
   }

}
 


default methods in interfaces
-----------------------------
A method with default implementation in an inteface is called as default method.

we should declare default method in interface using "default" keyword.

syntax
------
public default returntype methodname()
{

}
ex:
public default void m1()
{

}

default methods makes maintenance of projects easy and simple.

suppose over a period of time the number of abstarct methods we add to interfaces increases to a level where addition of new abstract methods to an interface becomes difficult because the number of implementation classes also grows parallely once we introduce a new abstract method all the implementation classes  should override these methods even if is necessary or not,to avoid this situation default methods are introduced so that we don't need to implement these methods in a subclass,the subclass which needs these methods will override them and the other classes may use default methods as it is.

Program
-------

interface I1 {
void m1();

void m2();

default void m3() {
System.out.println("m3");
}
}

class A implements I1 {

@Override
public void m1() {
System.out.println("m1");
}

@Override
public void m2() {
System.out.println("m2");
}
}

public class DefaultDemo {
public static void main(String[] args) {

A a = new A();
a.m1();
a.m2();

a.m3();

}
}
static method
-------------
We can declare static methods in interfaces from 1.8 version onwards.

static methods are used to implement utility logic.

syntax
------
public  static returntype methodname()
{
//
}

Program
-------
interface I1 {
public static int max(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}

public default void m3() {
System.out.println("m3");
}
}

class A implements I1 {
public void m1() {
System.out.println("m1");
}

}

public class DefaultDemo {
public static void main(String[] args) {

A a = new A();
a.m1();
a.m3();
System.out.println(I1.max(10, 20));

}
}

Java-final keywords

final variable
--------------
A variable whose value cannot be altered/changed is known as final variable.

A variable declared using keyword final is known as final variable

syntax
------
final datatype varname=value;

ex:
final double pi=3.14;

if we want to define constants in a program then we must declare a variable as final.

The only modifier allowed with local variables is final.

we should initliaze a final variable at the time of declaring itself.

final method
------------
A method declared using a keyword final is known as final method

we cannot ovverride final methods in a subclass.


syntax
------
accessmodifier final returntype methodname()
{
//statements
}

ex:
public final void m1()
{

}

Program
--------
class A
{
  public final void m1()
  {
    System.out.println("A");
  }
}
class B extends A
{
  public void m1()
  {
    System.out.println("B");
  }

}

Above code leads to CE because we are overriding final method.

which of the following method definitions are valid?
public final void m1()
public final  abstract void m1()
public final static abstract void m1()
public abstract void m1()
void m1()
public static final void m1()

we cannot declare abstract and final together bcoz it is iilegal combination.abstract method must be overridden whereas final method shoud not be overridden.


final class
-----------
A class declared using keyword final is known final class.

A final class cannot be inherited.

syntax
------
accessmodifier final class ClassName
{
//
}

ex:
final class A
{
  public  void m1()
  {
    System.out.println("A");
  }
}

which of the following declarations are valid?
public final class A{}c
public abstract class A{}c
public final abstract class A{}
public static final class A{}
final class A{}c
abstract class A{}c
public abstract static final class A{}


Reason:A final class cannot be subclassed whereas an abstract class needs subclassing.

Java-this,super keywords,this(),super()

this
super
this()
super()



this
----
this is keyword used to refer to current class instance varaibles and methods.

this cannot used in static context.


syntax
------
How to access variable
----------------------
this.varname

ex:
this.name

How to access methods
---------------------
this.methodname();

ex:
this.show();


super keyword
-------------
A super keyword is used to refer to instance variables and instance methods of super class from a sub class.

super cannot be used in static context.


How to access variable
----------------------
super.varname

ex:
super.a

How access methods
------------------
super.methodname();

ex:super.display();





Program to demonstrate super keyword
------------------------------------
class A
{
int a=10;
public void display()
{
System.out.println(a);
}
}
class B extends A
{
int a=20;
public void display()
{
  System.out.println(a);
  System.out.println(super.a);
  super.display();
 
}
public static void main(String args[])
{
   B b=new B();
   b.display();

}
}


Note:
It is recommended to use super keyword if both the super class memebers and sub class members are same.


what is the output of the follwoing program?
Program
-------
class A
{
 int a=10;
}
class B extends A
{
 int a=20;
}
class C extends B
{
 int a=30;
 public void show()
 {
   System.out.println(a);
   System.out.println(super.a);
   System.out.println(((A)this).a);//line1
 }
 public static void main(String args[])
 {
    C c=new C();
    c.show();
 }
}
output
------
30
20
10


In the above code we are trying acces the instance variable of "A" class from "C" class,super keyword is applicable upto one level of inheritance.so to invoke the variable from A class to C class we had done casting as shown at line1.


this()
------
It is used to invoke one constructor from another constructor of same class.

Chaining of constructor within the same class is possible using this().


this() is of 2 types
default-->this();
parameterized-->this(value1,value2,...);
                   or
                this(var1,var2,...);


this() must be the first statement in a constructor.

//case1:Chaining parameterized from default
class Test
{
   Test()
   {
     System.out.println("1");
   }
   Test(int x,int y)
   {
     this();    
     System.out.println("2");
   }
}
class ThisTest
{
  public static void main(String args[])
  {
     Test t1=new Test(10,20);
 
  }
}

//case2:Chaining  parameterized from another //constructor
class Test
{
   Test()
   {
     this(30,40);
     System.out.println("1");
   }
   Test(int x,int y)
   {
         
     System.out.println("2");
   }
}
class ThisTest
{
  public static void main(String args[])
  {
     Test t1=new Test();
 
  }
}


what is the output of the following code?
class A
{
   A()
   {
      this(10);
      this(10,20);//line1
   }
   A(int x)
   {
   
   }
   A(int x,int y)
   {
   }
   public static void main(String args[])
   {

   }
}
//i)compiles
//ii)executes
//iii)cE[tick]
//iv)RE

In the above code this() method is declared as a second statement @line1.As per rule this() must be first statement in a constructor.


class A
{
   A()
   {
      this();
      System.out.println("A");
   }
   public static void main(String args[])
   {
       A a=new A();
     
   }
}
options
-------
i)CE
ii)RE
iii)Exceutes sucessfully and prints A
iv)None of the above.

Ans:
CE

Analysis
--------
The above program leads to CE saying "recursive constructor invocation" because we are calling same constructor repeatitively by declaring default this() inside default constrcutor.



Construtor calling in inheritance
---------------------------------
In java contructor is not inherited from super class to subclass because a construtor purpose is to initialize instance variables of a class in whihc it is declared.

In java,A sub class contructor will automatically make a call to its super class constructor but this is applicable only to default constructors.


While calling a super class construtor from a sub class constructor we use super() method.

super()
-------
A super() is used to make to call the constructor of a super class from a sub class constructor.

A super() must declared as a first statement in a sub class constructor.

A super() is of 2 types
default--->super()
       --->It is used to make a call to default constructor of a super class from a sub class constructor.

parameterized--->super(value1,value2,...);
                  or
             --->super(var1,var2,...);
--->It is used to make a call to parameterized constructor of a super class from a sub class constructor.

--->we can pass parameters from a sub class constructor to a super class constructor by using parameterized super() method.

Program to  demonstrate default super()
---------------------------------------
class A
{
   A()
   {
   
     System.out.println("A");
   }
 
}

class B extends A
{
   B()
   {
     super();
     System.out.println("B");
   }
}
class C extends B
{
   C()
   {
    super();
    System.out.println("C");
   }
   public static void main(String args[])
   {
       C c=new C();

   }

}

output
------
A
B
C
Important points
----------------
In the above code we are making a call to super class constructor B() from C() by using super(),similary from B() to A().


In case of default constuctors,if we don't declare a super() in a sub class constructor then the compiler will implicitly(automatically) add one super() in a sub class constructor.

program to demonstrate Parameterized super()
--------------------------------------------
class A
{
  A(int x,int y)
  {
    System.out.println("A "+x+y);
  }
}
class B extends A
{
  B(int x,int y,int z)
  {
    super(x,y);
    System.out.println("B "+x+y+z);
  }
}
class C extends B
{
  C(int x)
  {
    super(x,10,20);
    System.out.println("C "+x);
  }
  public static void main(String args[])
  {
    C c=new C(10);
   
  }
}



if we declare a constructor of a super class as private then it is not possible to inherit that super class.

Program
-------
class A
{
 
   private A()
   {
   }

}

class B extends A
{
   B()
   {
   }

}

The above code leads to CE saying  A() has private access.

Java-Arrays

Arrays
------
Array is a collection of similar type of values.

In one variable we can store many values using arrays.

static collection(fixed in size).

Arrays stores both primitives and objects.

Arrays are type safe.

Arrays are good at performance.


Types of arrays
---------------
one dimensional
Multi dimensional


one dimensional
---------------
Array with one subscript or one index is known as one dimensional array.

syntax
------
datatype varname[]=new datatype[size];

we can also declare array as below

datatype []varname=new datatype[size];
datatype[] varname=new datatype[size];

ex:
int a[]=new int[5];

Internal representation of arrays
---------------------------------
If the above statement is executed memory for array is allocated with 5 locations,the index of array always start with zero(0) and ends with size-1(4).

--
  |a[0]
--
  |a[1]
--
..


Programs
--------
import java.util.*;
class Test
{
  public static void main(String args[])
  {
     int a[]=new int[5],sum=0;
     int b[]=new int[5];
     Scanner s=new Scanner(System.in);
     System.out.println("Enter values into array");
     for(int i=0;i<5;i++)
     {
        a[i]=s.nextInt();

     }
     for(int i=0;i<5;i++)
     {
       b[i]=a[i];

     }
     for(int i=0;i<5;i++)
     {
        System.out.println(b[i]);
     }
   }
}

Initializing Array using Array Initializer
------------------------------------------
Array initializer is used to initialize  group of values with in parenthesis.
syntax
------
datatype varname[]={value1,value2,....};

Program
-------
import java.util.*;
class Test
{
  public static void main(String args[])
  {
      int a[]={1,2,3,4,5,6,7};
      for(int i=0;i<7;i++)
      {
         System.out.println(a[i]);
      }
   
   }
}

length variable
---------------
A length returns length of an array.

syntax
------
arrayvar.varname

ex:


Note:we cannot initialize size at the left the side of assigment operator in arrays;


which of the following array declarations are valid?
int a[]=new int[5];v
int a[]=new int[];iv
int a[5]=new int[5];iv
int a[5]=new int[];iv
int []a=new int[5];v
int[] a=new int[5];v

import java.util.*;
class Test
{
  public static void main(String args[])
  {
      int a[]={4,2,3,4,5,6,4};
      int count=0;

      System.out.println("Enter key");
      int key=new Scanner(System.in).nextInt();


      for(int i=0;i<a.length;i++)
      {
         if(a[i]==key)
         {
           count++;
         }
       }
       if(count>0)
       System.out.println("element "+key+" is found "+count+" times ");
       else
       System.out.println("element not found");
 }
}



2D Array
--------
Array with 2 subscripts is known as 2D Array.

2D Array is used to represent data in the form of rows and cols.

syntax
------
datatype varname[][]=new datatype[size1][size2];

size1-->rows
size2-->cols


ex:
int a[][]=new int[2][2];

internal representation
-----------------------



Program
-------
a.length.

3D Array
--------
Array with 3 subscript or index is known as 3D Array.

collection of 2d arrays.

syntax
------
datatype varname[][][]=new datatype[size1][size2][size3];

ex:
int a[][][]=new int[2][2][2];

size1-->no of 2d arrays
size2-->no of rows
size3-->no of cols

int a[]=new int[5];

If we try to insert/print values in an array we should not exceed the size of array,it leads to ArrayIndexOutOfBoundsException if we exceed the size.

Also we should not use negative index while working with arrays.

If we don't initialize an array it is automatically initialized with default values.

ex:
Program
-------
class Test
{
   public static void main(String args[])
   {
        int a[]=new int[5];

        for(int i=0;i<5;i++)
        {
           System.out.println(a[i]);
        }
   }
}
output
------
0
0
0
0
0

Arrays are obejects in java.we know that we create objects using new operator.
Arrays static collection i,e they are fixed in size