Thursday, 30 August 2018

PACKAGES


PACKAGES
 Java API Packages
Java API provides a large number of classes grouped into different packages according to functionality. Most frequently used packages are:-
  • Java.lang: 
These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types.
  • Java.util:        
A collection of classes to provide utility functions such as vectors, hash tables, random numbers, date and time functions etc.
  • Java.io: 
A Collection of classes required for Input/Output manipulations.
  • Java.net: 
A collection of classes for communicating with other computers via network.
  • Java.awt:
The Abstract Window Tool Kit package contains classes that implements platform independent graphical user interface.
  • Java.applet:
This includes a set of classes that allows us to create Java applets.

Using system Packages
There are two ways of accessing the classes stored in a package. The first approach is to use the fully qualified class name of the class that we want to use. This is done by using the package name containing the class and then appending the class name to it using the dot operator. For example, if we want to refer to the class Color in the awt package, then we may do so as follows:
java.awt.Colour
Notice that awt is a package within the package java and the hierarchy is represented by separating the levels with dots. This approach is perhaps the best and easiest one if we need to access the class only once or when we need not have to access any other classes of the package.
But, in many situations, we might want to use a class in a number of places in the program or we may like to use many of the classes contained in a package. We may achieve this easily as follows;
import packagename.classname; or
import packagename.*;
These are known as import statements and must appear at the top of the file, before any class declarations.
The first statement allows the specified class in the specified package to be imported. For example, the statement
         import java.awt.Color;
imports the class Colour and therefore the class name can now be directly used in the program.
The second statement imports-every class contained in the specified package. For example, the statement import java.awt.*; bring all classes of java.awt package

Naming Conventions
  • Packages begin with lowercase letters
  • Every package name must be unique
  
Creating Packages

Packages declare the name of the package using the package keyword followed by a package name. This must be the first statement in Java source file.

package first;
public class firstclass
{
            body
}

here the package name is first. This should be saved as firstclass.java and located in a directory named first. When the source file is compiled, java will create a .class file and store it in the same directory.

 Steps to create package

  1. Declare the package at the beginning of a file using the form,
Package packagename;
  1. Define the class that is to be put in the package and declare it public.
  2. Create a subdirectory under the directory where the main source files are stored.
  3. Store the file as the classname.java in the subdirectory created.
  4. Compile the file. This creates .class file in the subdirectory.
Subdirectory name must match the package name exactly. Java also supports the concept of package hierarchy.
A java package file can have more than one class definition. In such cases, only one of the classes may be declared as public and that class name with .java extension is the source file name. When a source file with more than one class definition is compiled, Java creates independent .class files for those classes.

 Accessing a Package

Packages are accessed through a fully qualified class name or using a shortcut approach through the import statement. We use the import statement when there are many references to a particular package or the package name is too long and unwieldy.
The same approaches can be used to access the user-defined packages as well. The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching a class is as follows:
import packagel [.package2][.package3] .classname;
Here packagel is the name of the top level package, package2 is the name of the package that is inside the packagel, and so on. We can have any number of packages in a package hierarchy. Finally, the explicit class name is specified.
The following is an example of importing a particular class:
import firstPackage.secondPackage.MyClass;
After defining this statement, all the members of the class MyClass can be directly accessed using the class name or its objects directly without using the package name.
We can also use another approach as follows:
import packagename. *;
Here, packagename may denote a single package or a hierarchy of packages as mentioned earlier. The star (") indicates that the compiler should search this entire package hierarchy when it encounters a class name. This implies that we can access all classes contained in the above package directly.

Using a Package

This source file should be named calculations.java and stored in the subdirectory arithmetic. Now compile this java file. The resultant calculations.class will be stored in the arithmetic subdirectory.

//Program to calculate arithmetic operations
package arithmetic;
public class calculations
{
            public int add(int a,int b)
            {
                        return a+b;
            }
            public int sub(int a,int b)
            {
                        return a-b;
            }
            public int mul(int a,int b)
            {
                        return a*b;
            }
            public int div(int a,int b)
            {
                        return a/b;
            }
}

Now consider the listing shown below
//importing package
import arithmetic.calculations;
class performoperations
{
            public static void main(String []args)
            {
                        calculations c=new calculations();
                        int a=Integer.parseInt(args[0]);
                        int b=Integer.parseInt(args[1]);
                        int z=c.mul(a,b);
                        int v=c.sub(a,b);
                        System.out.println("Addition is:"+c.add(a,b));
                        System.out.println("Division is:"+c.div(a,b));
                        System.out.println("Multiplication is:"+z);
                        System.out.println("Subtraction is:"+v);          
            }
}
Output:
D:\ \programs>javac performoperations.java
D:\ \programs>java performoperations 6 2
Addition is:8
Division is:3
Multiplication is:12
Subtraction is:4

This listing shows a simple program that imports the class calculations from the package arithmetic. The source file should be saved as performoperations.java and then compiled.

During the compilation of performoperations.java the compiler checks for the file calculations.class in the arithmetic directory for information it needs, but it does not actually include the code from calculations.class in the file performoperations.java. When the performoperations.java program is run, Java looks for the file calculations.class and loads it using something called class loader. Now the interpreter knows that it also needs the code in the file calculations.class and loads it as well.

Adding a Class to a Package
It is simple to add a class to an existing package. Consider the following package:
package pl;
public ClassA
{
// body of A
}
The package p1 contains one public class by name A. Suppose we want to add another class to this package. This can be done as follows:
1.    Define the class and make it public.
2.    Place the package statement
package p1;
before the class definition as follows:
package pl;
public class B
{         
// body of B
            }
3.    Store this as B.java file under the directory p1.
4.    Compile B.java file. This will create a B.class file and place it in the directory p1.
Remember that, since a Java source file can have only one class declared as public, we cannot put two or more public classes together in a .java file. This is because of the restriction that file name should be same as the name of the public class with .java extension.
If we want to create a package with multiple public classes in it, we may follow the following steps:
  • Decide the name of the package.
  • Create a subdirectory with this name under the directory where main source files are stored.
  • Create classes that are to be placed in the package in separate source files and declare the package statement
package packagename;
at the top of each source file.
  • Switch to the subdirectory created earlier and compile each source file. When completed, the package would contain. class files of the entire source files.
Hiding Classes
When we import a package using asterisk(*), all public classes are imported. However, we may prefer to not import certain classes. Such classes should not be declared as public.
Ex:
package p1;
class y  //not public so it is hidden class
{
            body
}

Here the class y which is not declared public is hidden from outside of package p1.

Wednesday, 29 August 2018

Interface :: Multiple Inheritance


Interface  :: Multiple Inheritance

Multiple inheritance: Derivation of a class from two or more classes is called multiple inheritances.


 
Since Java does not support multiple inheritances, which leads to duplication in the methods for the derived classes which lead to complication at run-time. To overcome this drawback java provides a concept of Interfaces.

Defining Interfaces

Interface is a collection of ‘n’ number of final members and abstract methods that can be implemented by any number of subclasses. Interface provides dynamic request dispatching of methods when implemented by ‘n’ number of sub-classes. No objects will be created for Interface because it implements the particular class so the object will be created for that class.

Syntax for declaration:
            Interface          <interfacename>
            {
                        members=value;
                        returntype <methodname>(argslist);
            }
Syntax for implementation:
Class <name> implements <interfacename>
            {
                        overridden methods from interface ( )
                        {
                                    body;
                        }
            }

keypoints :

  • All the methods declared inside the interface does not require any body and they are by default abstract types
  • All the members declared inside the interface are by default final which must be initialized and cannot be modified in the subclasses
  • Once a class implements an interface it has to over-ride all the methods of the interface atleast with null body.
  • Interfaces cannot have instances
  • One class can implement any number of interfaces.
  • Interface can be pointed to the objects of those classes which implements the interface leads to dynamic method dispatching.

Extending Interfaces

Like classes, interfaces can also be extended i.e., an interface can be sub interfaced from other interfaces. The new subinterface will inherit all the members of the superinterface in the manner similar to subclasses. This is achieved using the keyword extends as shown below:
Syntax:
Interface name2 extends name1
{
            body
}
One interface can inherit from another interface and if a class implements the later interface the class must override all the methods of both the interfaces.

Implementing Interfaces
Interfaces are used as “superclass” whose properties are inherited by classes.
Syntax:
Class classname implements interfacename
{
            body
}

Accessing Interface Variables
Interfaces can be used to declare a set of constants that can be used in different classes. The constant values will be available to any class that implements the interface. The values can be used in any method, where we can use a final value.

Example Program:
interface demo             //definition of interface
{
            int sno=101;                 //by default final which cannot be modified
            String sname="GVP";
}

interface demo2 extends demo            //extending interfaces
{
            void display();             //by default abstract
}
           
class example implements demo2        //implementation of interface
{
            public void display()
            {
                        System.out.println("Sno="+sno+"\n"+"Sname="+sname);
                        //accessing interface variables
            }
}

class inter
{
            public static void main(String []args)
            {
                        example e=new example();
                        e.display();
            }
}
Output:
D:\ \programs>javac inter.java
D:\ \programs>java inter
Sno=101
Sname=GVP


//Bank Transactions using Interfaces
interface bank
{
            int accno=101;
            String accname="GVP";
            int amt=10000;
}
interface acctype extends bank
{
            void calc_interest(int rof);
            void put_details();
}
abstract class members implements acctype
{
            float interest=0.0f;
            float bal=0.0f;
            public void put_details()
            {
                        System.out.println("Account Number="+accno);
                        System.out.println("Account Name="+accname);
                        System.out.println("Amount ="+amt);
                        System.out.println("Interest="+interest);
                        System.out.println("Balance="+bal);
            }
}
class current_accnt  extends members implements acctype
{         
            public void calc_interest(int rof)
            {
                        interest=(rof*amt)/100;
                        bal=amt-interest;
            }
}
class savings_accnt extends members implements acctype
{
            public void calc_interest(int rof)
            {
                        interest=(rof*amt)/100;
                        bal=amt-interest;
            }
}
class interest
{
            public static void main(String []args)
            {
                        current_accnt ca=new current_accnt();
                        savings_accnt sa=new savings_accnt();
                        if(args[0].equals("current"))
                        {
                                    ca.calc_interest(10);
                                    ca.put_details();
                        }
                        else if(args[0].equals("savings"))
                        {
                                    sa.calc_interest(5);
                                    sa.put_details();
                        }         
                        else
                                    System.exit(0);
            }
}
Output:
D:\ \programs>javac interest.java
D:\ \programs>java interest current
Account Number=101
Account Name=GVP
Amount =10000
Interest=1000.0
Balance=9000

Tuesday, 28 August 2018

Vectors & Wrapper Classes


Vectors
Vectors class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number. Vector class contained in the java.util.package. The objects do not have to be homogenous. Vectors are created like arrays as follows:

            Vector vect=new vector();       //declaring without size
            Vector vect=new vect(3);                     //declaring with size.

 Vectors possess a number of advantages over arrays:-

  1. It is convenient to use vectors to store objects
  2. A vector can be used to store a list of objects that may vary in size.
  3. We can add and delete objects from the list as and when required.
Vectors can hold only Objects and not primitive types (eg, 5).

Common Vector Methods

There are many useful methods in the Vector class and its parent classes. Here are some of the most useful. v is a Vector, i is an int index, o is an Object.
Method
Description
v.add(o)
adds Object o to Vector v
v.add(i, o)
Inserts Object o at index i, shifting elements up as necessary.
v.clear()
removes all elements from Vector v
v.contains(o)
Returns true if Vector v contains Object o
v.firstElement(i)
Returns the first element.
v.get(i)
Returns the object at int index i.
v.lastElement(i)
Returns the last element.
v.listIterator()
Returns a ListIterator that can be used to go over the Vector. This is a useful alternative to the for loop.
v.remove(i)
Removes the element at position i, and shifts all following elements down.
v.set(i,o)
Sets the element at index i to o.
v.size()
Returns the number of elements in Vector v.
v.toArray(Object[])
The array parameter can be any Object subclass (eg, String). This returns the vector values in that array (or a larger array if necessary). This is useful when you need the generality of a Vector for input, but need the speed of arrays when processing the data.
v.addElement(item)
Adds the item specified to the list at the end
v.elementAt(10)
Gives the name of the 10th object
v.size()
Gives the number of objects present
v.removeElement(item)
Removes the specified item from the list
v.removeElementAt(n)
Removes the item stored in the nth position of the list
v.removeAllElements( )
Removes all the elements in the list
v.copyInto(array)
Copies all items from list to array
v.insertElementAt(item,n)
Inserts the item at nth position

Example Program:
import java.io.*;
import java.util.*;
class VectorDemo1
{
public static void main(String args[]) throws IOException
{
Vector v = new Vector( );
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1.Creation");
System.out.println("2.Insertion");
System.out.println("3.Deletion");
System.out.println("4.Display");
System.out.println("5.exit");
System.out.println("Enter Ur Choice:");
int n=Integer.parseInt(br.readLine());
switch(n)
{
            case 1:            
                        System.out.println("Enter the Element:");
                        v.addElement(new Integer(br.readLine()));
                        break;
            case 2: System.out.println("Enter the position to be inserted:");
                        int x=Integer.parseInt(br.readLine());
                        v.insertElementAt(new Integer(br.readLine()),x);
                        break;
            case 3:System.out.println("Enter the position to be deleted:");
                        int y=Integer.parseInt(br.readLine());
                        v.removeElementAt(y);
                        break;
            case 4: System.out.println("Elements are:");
                        for(int i=0;i<v.size();i++)
                        System.out.println(v.get(i)+" ");                      
                        break;
            case 5:System.exit(0);
}
}
}
}

Wrapper Classes
Vectors cannot handle primitive data types like int,float,long,char and double. Primitive data types may be converted into object types by using the wrapper classes contained in Java.lang package.


Following table lists the primitive types and the corresponding wrapper classes:
Primitive
Wrapper
boolean
  java.lang.Boolean
byte
  java.lang.Byte
char
  java.lang.Character
double
  java.lang.Double
float
  java.lang.Float
int
  java.lang.Integer
long
  java.lang.Long
short
  java.lang.Short