What is Class

95
What is class? What is class? Class is a collection of data members and member functions. Now what are data members? Data members are nothing but simply variables that we declare inside the class so it called data member of that particular class. Now what are member functions? Member functions are the function or you can say methods which we declare inside the class so it called member function of that particular class. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably. Syntax of class: class classname { type instance-variable1; type instance-variable2; //.... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) {

description

cls

Transcript of What is Class

  

What is class?

What is class?

Class is a collection of data members and member functions.

Now what are data members?

Data members are nothing but simply variables that we declare inside the class so it called data member of that particular class.

Now what are member functions?

Member functions are the function or you can say methods which we declare inside the class so it called member function of that particular class.

The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type.

Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably.

Syntax of class:

class classname{ type instance-variable1; type instance-variable2; //.... type instance-variableN;

type methodname1(parameter-list) {

// body of method }

type methodname2(parameter-list) {

// body of method } // ... type methodnameN(parameter-list) { // body of method } }

When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data.

The data, or variables, defined within a class are called instance variables. The code is contained within methods.

NOTE : C++ programmers will notice that the class declaration and the implementation of the methods are stored in the same place and not defined separately.

EX.

?1234567891011121314151617181920

public class MyPoint{        int x = 0;        int y = 0;         void displayPoint()        {                System.out.println("Printing the coordinates");                System.out.println(x + " " + y);        }         public static void main(String args[])        {                MyPoint obj;  // declaration                 obj = new MyPoint(); // allocation of memory to an object            obj.x=10;    //access data member using object.            obj.y=20;                obj.displayPoint(); // calling a member method        }}

Output : Printing the coordinates10  20

Here x and y are data members of class MyPoint and displayPoint() is a member function of the same class.

In above program we can take as many objects as we want.

From the above program one thing we should keep in mind that when we want to access data member or methods of class we have to write objectname.member name

Syntax:

accessing data member of the class: objectname.datamember name;

accessing methods of the class: objectname.method name();

So for accessing data of the class: we have to use (.) dot operator.

NOTE: we can use or access data of any particular class without using (.) dot operator from inside that particular class only.

How to declare object of class in java?

The program we gave in previous topic from that we can easily learn that how object is going to declare and define for any class.

Syntax of object:

classname objectname;         \\ declaration of object.

objectname = new classname();      \\ allocate memory to object (define object).

or we can directly define object like this

classname objectname = new classname();

Now let us look one class which has two different object.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class Box

{

        double width;

        double height;

        double depth;

}

class BoxDemo2

{

        public static void main(String args[])

       {

             Box mybox1 = new Box();

             Box mybox2 = new Box();

             double vol;

             // assign values to mybox1's instance variables

             mybox1.width = 10;

             mybox1.height = 20;

             mybox1.depth = 15;

18

19

20

21

22

23

24

25

26

27

28

29

             /* assign different values to mybox2's instance variables */

             mybox2.width = 3;

             mybox2.height = 6;

             mybox2.depth = 9;

             // compute volume of first box

             vol = mybox1.width * mybox1.height * mybox1.depth;

             System.out.println("Volume is " + vol);

             // compute volume of second box

            vol = mybox2.width * mybox2.height * mybox2.depth;

            System.out.println("Volume is " + vol);

       }

}

Output :

 

Volume is 3000.0

Volume is 162.0

From the above program we can understand that each object has its own copies of the instance variables.

This means that if you have two Box objects, each has its own copy of depth, width, and height. It is important to understand that changes to the instance variables of one object have no effect on the instance variables of another.

Assigning Object Reference Variables :

 

Suppose 

 

Box b1 = new Box();

Box b2 = b1; 

Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1.

 

Here we did not use new keyword for b2 so b1 and b2 will both refer to the same object.

 

The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1.

 

Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object.

NOTE: When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.

  

Introduction to method

As we all know that, classes usually consist of two things instance variables and methods.

Here we are going to explain some fundamentals about methods.

So we can begin to add methods to our classes.

Methods are defined as follows

§  Return type

§  Name of the method

§  A list of parameters

§  Body of the method.

Syntax:

return type method name (list of parameters){                Body of the method}

return type specifies the type of data returned by the method. This can be any valid data type including class types that you create.

If the method does not return a value, its return type must be void, Means you can say that void means no return.

Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:

return value;

Here, value is the value returned.

The method name is any legal identifier.

The list of parameter is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.

If the method has no parameters, then the parameter list will be empty.

Let us look at one example of class which have methods and data members both.

?12345678910111213141516171819202122232425262728

import java.util.Scanner;class Box {       double width;       double height;       double depth;       void volume()        // display volume of a box        {             System.out.print("Volume is : ");             System.out.println(width * height * depth);       }}class BoxDemo {       public static void main(String args[])       {              Box box1 = new Box();   // defining object box1 of class Box              Scanner s = new Scanner(System.in);              System.out.print(“Enter Box Width : ”);              box1.width = s.nextDouble();              System.out.print(“Enter Box Height : ”);              box1.height = s.nextDouble();              System.out.print(“Enter Box Depth : ”);              box1.depth = s.nextDouble();              // display volume of box1              box1.volume();  // calling the method volume       }}

Output: Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here width, height and depth are data members of class Box and void volume() is method of class Box.

Here method has no parameter and no return value.

Now let us look at same program but in different way.

?1234567891011121314151617181920212223242526272829

import java.util.Scanner;class Box {       double width;       double height;       double depth;       double volume()        {               return width * height * depth;       }}class BoxDemo {       public static void main(String args[])       {              double vol;              Box box1 = new Box();   // defining object box1 of class Box              Scanner s = new Scanner(System.in);              System.out.print(“Enter Box Width : ”);              box1.width = s.nextDouble();              System.out.print(“Enter Box Height : ”);              box1.height = s.nextDouble();              System.out.print(“Enter Box Depth : ”);              box1.depth = s.nextDouble();              // display volume of box1              vol = box1.volume();  // calling the method volume              System.out.println("Volume is : " +vol);       }}

Output:

Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

Here in above program volume() method has return type double so we took one vol variable. It is a local variable of class BoxDemo and it catch the returned value by volume method of class Box.

One thing must keep in mind that the data type of vol and return type of volume() method always be same.

?1234567891011121314151617181920212223242526272829

import java.util.Scanner;class Box {       double width;       double height;       double depth;       double volume(double w, double h, double d)        {               return width * height * depth;       }}class BoxDemo {       public static void main(String args[])       {              double vo,wth,ht,dth;              Box box1 = new Box();   // defining object box1 of class Box              Scanner s = new Scanner(System.in);              System.out.print(“Enter Box Width : ”);              wth = s.nextDouble();              System.out.print(“Enter Box Height : ”);              ht = s.nextDouble();              System.out.print(“Enter Box Depth : ”);              dth = s.nextDouble();              // display volume of box1              vol = box1.volume(wth,ht,dth);  // calling the method volume              System.out.println("Volume is : " +vol);       }}

Output: Enter Box Width : 15

Enter Box Height : 20

Enter Box Depth : 10

Volume is : 3000.00

 

Here in above program volume() method has three parameters as well as double return type.

Here we took three extra local variables in class BoxDemo and pass them in function calling.

One thing must keep in mind that in defining and calling of method, the sequence of data type of parameter must be same in both.

 

Constructor

Java supports a special type of methods, called constructor that enables an object to initialize itself when it is created.

Constructors have the same name as the class it-self.

Constructors do not specify a return type, not even void. This is because they return the instance of the class itself.

A constructor is automatically called when an object is created.

Syntax:

Constructor_name([arguments])

{

           // body

}

Constructors are generally of two types.

1.      Non-Parameterized

2.      Parameterized  

1.      Non-Parameterized:

?1234567891011121314

// Non - parameterised constructor class Point1{        int x;        int y;        Point1()   //constructor of class        {                x = 10;                y = 20;        }        void display()        {                System.out.println("\n\n\t-----Printing the coordinates-----");                System.out.println("\t\t\t" + x + "  " + y);

15161718192021222324

        }}class pointDemo{        public static void main(String args[])        {                Point1 p1 = new Point1();  // constructor will be call automatically from here                p1.display();        }}

Output: -----Printing the coordinates-----                   10   20 2.      Parameterized:?12345678910111213141516171819202122232425262728293031

// parameterised constructorimport java.util.Scanner; class Point2{        int x;        int y;        Point2(int a, int b)        {                x = a;                y = b;        }        void display()        {                System.out.println("\n\n\t-----Printing the coordinates-----");                System.out.println("\t\t\t" + x + "  " + y);        }}class pointDemo{        public static void main(String args[])        {                int i,k;                Scanner s = new Scanner(System.in);                System.out.print("Enter int value for i : ");                i = s.nextInt();                System.out.print("Enter int value for k : ");                k = s.nextInt();                Point2 p1 = new Point2(i,k);                p1.display();        }}

Output: Enter int value for i : 10Enter int value for k : 20-----Printing the coordinates-----

                   10   20

Keywords

We have already seen one keywords table in our first chapter.

But here we are going to learn few regularly used keywords.

1. new

2. this

3. static

4. super

5. final

The super and final keywords will demonstrate in further chapter.

new:

The new keyword dynamically allocates memory for an object. Syntax: claas_name object _name  = new class_name(); EX. Box b1 = new Box();Box b2 = new Box(); We have already seen so many programs in which we used new keyword for creating objects.

this:

This keyword is the name of a reference that refers to a calling object itself.

one common use of the this keyword is to reference a class` hidden data fields.

You can have local variables, including formal parameters to methods which overlap with the names of the class` instance variables.

The local variable hides the instance variable so we use this keyword.

Another common use of this keyword is to enable a constructor to invoke another constructor of the same class.

java requires that the this(arg-list) statement appear first in the constructor before any other statements.

EX :

?12345678910111213141516171819202122232425262728293031

public class This_demo {    public static void main(String[] args)     {        abc a1 = new abc();     //call non parameterize constructor             }     } class abc{    int x,y;    abc()    {        this(10,20);    //this will call another constructor     }    abc(int x,int y)    {        this.x=x+5;     //it will set class` member x        this.y=y+5;     //it will set class` member y        System.out.println("local method`s x = " +x);        System.out.println("local method`s y = " +y);        Print_data();    }    public void Print_data()    {        System.out.println("x = " +x);        System.out.println("y = " +y);    }}

 Output : local method`s x = 10local method`s y = 20x = 15y = 25

static :

A class member must be accessed with the use of an object of its class but sometimes we want to define a class member that will be used independently without creating any object of that class.

It is possible in java to create a member that can be used by itself, without reference to a specific instance.

To create such a member, precede its declaration with the keyword static.

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.

one can declare both methods and variables to be static.

The most common example of a static member is main().

main() is declared as static because it must be called  before any object exist.

Instance variables declared as static are actually, global variables.

When objects of its class are declared, no copy of a static variable is made.

Instead, all instances of the class share the same static variable.

Method declared as static have several restrictions:

1.    Can call only other static methods.

2.    Only access static data.

3.    Can not refer to this or super in any way.

One can also declare a static block which gets executed exactly once, when the class is first loaded. 

EX : 

?123456789101112131415161718192021

public class Static_Demo {    public static void main(String[] args)     {        display(40); //call static method    }    static int i = 5;    static int j;    int k = 10;    static void display(int a)    {        System.out.println("a = "+a);   // here a = 40        System.out.println("i = "+i);   // here i = 5        System.out.println("j = "+j);   // here j = 50( because of static block j = i * 10 = 5 * 10 =50 )        //System.out.println("k = "+k); //can,t make a static reference to the non-static field k    }    static    {        System.out.println("Static block initialized..........");        j = i * 10;    }

22 }

 Output : Static block initialized..........a = 40i = 5j = 50

 

 

Access Control

One can control what parts of a program can access the member of a class. By controlling access, one can prevent misuse.

For Example, allowing access to data only through a well-defined set of methods, one can prevent misuse of that data. Thus,

when correctly implemented, a class creates “black box”.

How a member can be accessed is determined by the access specifier that modifies its declaration.

Java provides a set to access specifiers. Some aspects of access control are related to inheritance or packages.

Java’s access specifiers are:

public:

o   When a member of a class is specified by the public specifier, then that member can be accessed by any other code.

o   The public modifier makes a method or variable completely available to all classes.

o   Also when the class is defined as public, it can be accessed by any other class.

private:

o   To hide a method or variable from other classes, private modifier is used.

o    A private variable can be used by methods in it’s own class but not by objects of any other class.

o   Neither private variables nor private methods are inherited by subclass.

o   The only place these variables and methods can be seen is from within their own class.

protected:

o   protected applies only when inheritance is involved.

o   If you want to allow an element to be seen outside your current package, but only to classes that are inherited from your class directly, then declare that element as protected.

default:

o   We have seen that when no access control modifier is specified, it is called as default access.

o   Classes written like this are not accessible in other package.

o   Any variable declared without a modifier can be read or changed by any other class in the same package.

o   Any method declared the same way can be called by any other class in the same package.

o   When a member does not have an explicit access specification,

o    it is visible to subclasses as well as to other classes in the same package.

The following table summarizes the levels of access control.

Access Public Protected Default Private

From the same class

Yes Yes Yes Yes

From any class in the same package

Yes Yes Yes No

From any class outside the package

Yes No No No

From a sub -  class in the same package

Yes Yes Yes No

From a sub -  class outside the same package

Yes Yes Yes No

 

Method overloading in java:

Method overloading:

A class can contain any number of methods. Methods can be with parameter and without parameter.

The parameter in a method are called type signature.

It is possible in java to define two or more methods within the same class that share the same name, but with different parameter declarations (type signatures).

When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.

Overloading methods demonstrate the concept of polymorphism.

When an overloaded method is invoked, java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to call.

Thus, overloaded methods must differ in the type and/or number of their parameters.

Overloaded methods may have different return types.

When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.

EX :

?

1

2

3

4

5

6

7

8

9

10

public class MethodOver 

{       

    int n1;

        int n2;

        MethodOver()

        {

        n1 = 10;

                n2 = 20;

        }

        void square()        

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

    {

            System.out.println("The Square is " + n1 * n2);

        }

        void square(int p1)

        {        

            n1 = p1;

                System.out.println("The Square is " + n1 * n2);    

    }

        void square(int p1, int p2)       

    {

        n1 = p1;

                n2 = p2;

                System.out.println("The Square is " + n1 * n2);     

    }

        public static void main(String args[])        

    {         

            MethodOver obj1 = new MethodOver();

                obj1.square(); //call non parameterise method       

            obj1.square(4);   //call method which has 1 argument  

                obj1.square(7,8);  //call method which has 2 argument     

    }

}

 

Output :

 

The Square is 200

The Square is 80

The Square is 56

You can see that here we have 3 square methods with different argument.

Its called method overloading.

Constructor overloading in java:

Along with method overloading, we can also overload constructors. Constructors having the same name with different parameter list is called constructor overloading.

EX :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

class Point

{

        int x;

        int y;

        Point(int a, int b)

        {

                x = a;

                y = b;

        }

 

}

 

class Circle

{

        int originX;

        int originY;

        int radius;

 

        //Default Constructor

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

 

        Circle()

        {

                originX = 5;

                originY = 5;

                radius = 3;

 

        }

 

        // Constructor initializing the coordinates of origin and the radius.

 

        Circle(int x1, int y1, int r)

        {

                originX = x1;

                originY = y1;

                radius = r;

 

        }

 

 

        Circle(Point p, int r)

        {

                originX = p.x;

                originY = p.y;

                radius = r;

        }

 

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

        void display()

        {

                System.out.println("--Center at " + originX + " and " + originY);

                System.out.println("Radius = " + radius);

        }

 

        public static void main(String args[])

        {

         

        Circle c1 = new Circle();

        Circle c2 = new Circle(10,20,5);

        Circle c3 = new Circle(new Point(15,25),10);

 

        c1.display();

        c2.display();

        c3.display();

        }

}

 

Output :

 

--Center at 5 and 5

Radius = 3

--Center at 10 and 20

Radius = 5

--Center at 15 and 25

Radius = 10

 

Above program is quite complicated here i am giving you perfect flow of program.

 

First of all note one thing that new ClassName() this is a short  syntax of creating object of any class.

 

And we all know that when we create object the constructor of that class will be called automatically.

 

So in our program first of all due to syntax Circle c1 = new Circle(); non parameterize constructor will be called for object c1 so we get output like Center at 5 and 5 Radius = 3 in c1.display().

 

Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3 arguments will be called for object c2 so we get output like Center at 10 and 20 Radius = 5 in c2.display().

 

Now when we define object c3 our syntax is like Circle c3 = new Circle(new Point(15,25),10); so first of all it will create object for Point class so constructor of point class will be called and it will set parameter x and y.

 

Then constructor of circle class which has Point class object as an argument along with one int argument will be called and set all parameter as per program and we get output like Center at 15 and 25 Radius = 10 in c3.display().

 

We can also write

 

Point p1 = new Point(15,25);

Circle c3 = new Circle(p1,10);

 

This is how we can pass object as an argument in constructor.

 

We have already seen Call by reference in which we pass object as a method argument.

Now in next topic we will discuss about how you can return an object.

1. Passing Objects as a Parameter to Method.

We have seen that methods can take parameters as input and process them.

It is also common to pass objects as a parameter to methods.

?123456789101112131415161718192021222324252627282930

class PassObj{        int n1;        int n2;        // constructor        PassObj()        {                n1 = 0;                n2 = 0;        }         PassObj(int p1, int p2)        {                n1 = p1;                n2 = p2;        }         void multiply(PassObj p1)        {                int temp;                temp = p1.n1 * p1.n2;                System.out.println("Multiplication is " + temp);        }        public static void main(String args[])        {                PassObj obj1 = new PassObj(5,6);                PassObj obj2 = new PassObj();                obj2.multiply(obj1);        }}

 Output : Multiplication is 30 2. Method overloading with object as a parameter.?1234567

class MetObjOv{        int n1;        int n2;         // constructor        MetObjOv()

891011121314151617181920212223242526272829303132333435363738394041

        {                n1 = 0;                n2 = 0;        }        MetObjOv(int x, int y)        {                n1 = x;                n2 = y;        }        void multiply(MetObjOv p1)        {                n1 = p1.n1;                n2 = p1.n2;                System.out.println("There is nothing to multiply ");                System.out.println("n1 = "+n1+"\tn2 = " +n2);        }        void multiply(MetObjOv p1, MetObjOv p2)        {                n1 = p1.n1 * p2.n1;                n2 = p1.n2 * p2.n2;                                 System.out.println("Multiplication of two objects ");                System.out.println("n1 = " + n1 + "\tn2 = " + n2 );        }         public static void main(String args[])        {                MetObjOv obj1 = new MetObjOv(5,6);                MetObjOv obj2 = new MetObjOv(6,5);                MetObjOv obj3 = new MetObjOv();                obj3.multiply(obj1);                obj3.multiply(obj1, obj2);        }}

 Output : There is nothing to multiply n1 = 5 n2 = 6Multiplication of two objects n1 = 30 n2 = 30 3. Return an Object. A method can return any type of data, including class type (object) that you create.?12345678

class RetObj{        int n1;        int n2;         // constructor        RetObj()        {

91011121314151617181920212223242526272829303132333435363738

                n1 = 0;                n2 = 0;        }        RetObj(int x, int y)        {                n1 = x;                n2 = y;        }        RetObj multiply(RetObj p1, RetObj p2)        {                n1 = p1.n1 * p2.n1;                n2 = p1.n2 * p2.n2;                return (this);         }         void display()        {                System.out.println("An Example of returning an Object ");                System.out.println("n1 = "+n1+"\tn2 = " +n2);        }                         public static void main(String args[])        {                RetObj obj1 = new RetObj(5,6);                RetObj obj2 = new RetObj(6,5);                RetObj obj3 = new RetObj();                obj3 = obj3.multiply(obj1, obj2);                obj3.display();        }}

 Output : An Example of returning an Object n1 = 30 n2 = 30 RetObj multiply(RetObj p1, RetObj p2) This is the syntax in our program which has return type object. obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method multiply and return object, it will store in obj3.

 

Call by value

Now we all know that how to define and call the methods.

There are two types of calling method and those are

1. call by value

2. call by reference

Here we illustrate call by  value and in next topic we will look at call by reference.

In call by value when we call any method we pass value as method parameter so changing in local variables of the method doesn't`t affect the original variables of class.

This method copies the value of an argument into the formal parameter of the subroutine.

Therefore, changes made to the parameter of the subroutine have no effect on the argument.

In java, when we pass a primitive type to a method, it is passed by value.

Thus, what occurs to the parameter that receives the argument has no effect outside the method.

EX :

?1234567891011121314151617181920212223242526272829

public class CallBy_Value {    public static void main(String[] args)    {        Value v = new Value(10,20);        System.out.println("a and b before call............");        System.out.println("a = "+v.a);        System.out.println("b = "+v.b);        v.call(v.a,v.b);        // CALL BY VALUE        System.out.println("a and b after call............");        System.out.println("a = "+v.a);        System.out.println("b = "+v.b);    }} class Value{    int a,b;    Value(int i,int j)    {        a = i ;        b = j;    }    void call(int a, int b)    {        a = a * 2;        b = b * 2;    }}

 Output : 

a and b before call............a = 10b = 20a and b after call............a = 10b = 20 You can see that after calling method we change value of a and b but it will not afect the original value of class` members because of call by value. We pass value v.a and v.b as parameter and it will change local method`s a and b variables.  

Call by reference

Call by reference :

Here we pass reference as parameter in function calling.

We all know that reference means object so we pass object as parameter.

A reference to an argument (not value of argument) is passed to the parameter.

Inside the subroutine, this reference is used to access the actual argument specified in the call.

This means that changes made to the parameters will affect the argument used to call the subroutine.

When we pass an object to a method, the situation changes, because objects are passed by call-by-reference.

When we create a variable of a class type, we are only creating a reference to an object. Thus,

When you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.

This effectively means that objects are passed to method do affect the object used as an argument. 

EX :

?123456789

public class CallBy_Reference {    public static void main(String[] args)    {    Reference r = new Reference(10,20);    System.out.println("a and b before call............");    System.out.println("a = "+r.a);    System.out.println("b = "+r.b);    r.call(r);      // CALL BY REFERENCE

1011121314151617181920212223242526272829

    System.out.println("a and b after call.............");    System.out.println("a = "+r.a);    System.out.println("b = "+r.b);    }} class Reference {    int a,b;    Reference(int i,int j)    {        a = i ;        b = j;    }    void call(Reference r)    {        r.a = a * 2;        r.b = b * 2;    }}

 Output : a and b before call............a = 10b = 20a and b after call.............a = 20b = 40 You can see that after calling method value of original a and b is changed because of call by reference. Here we pass "r" reference (Object) as parameter in method calling. So changes inside method will affect original variable of class.

Recursion :

Recursion is the process of defining something in terms of itself.

When function call it self is called recursion.

A method that calls itself is said to be recursive.

EX :

?123456

import java.util.Scanner; class Factorial {    // this is a recursive function    int fact(int n)

789101112131415161718192021222324252627

    {        int result;        if(n==1)             return 1;        result = fact(n-1) * n;   //From here function call it self (fact(n-1))        return result;    }} public class Recursion{    public static void main(String args[])     {        int x;        Scanner s = new Scanner(System.in);        System.out.print("Enter int no = ");        x = s.nextInt();        Factorial f = new Factorial();        System.out.println("Factorial of" + x + " is " + f.fact(x));    }}

 Output : Enter int no = 7Factorial of7 is 5040 Here the method fact is recursive because it calls itself. The whole precess something like thisresult = fact(7-1) * 7 and so on until it returns 1. So one thing is sure that we have to take care that in every recursive process there must be a terminate condition to come out from recursion.

nested class :

It is possible to define a class within another class; such classes are known as nested classes.

The scope of a nested class is bounded by the scope of its enclosing class.

That means, if class B is defined within class A, then B is known to A, but not outside A.

If A is nesting class B, then A has access to all the members of B, including private members. But the B does not have access to the members of nested class.

There are two types of nested classes:

1.      Static

2.      Non – Static

Static nested class

A static nested class is one which has the static modifier, as it is static it must access the member of its enclosing class through an object.

That means it cannot refer to member of its enclosing class directly.

Non – Static nested class

Non – Static nested class is known as inner class.

It has access to all of its variables and methods of its outer class and can refer to them directly.

An inner class is fully within the scope of its enclosing class.

EX :

?1234567891011121314151617181920212223242526272829303132

class Inner1{        class Contents        {                private int i = 16;                public int value()                {                        return i;                }        }         class Destination        {                private String label;                Destination(String whereTo)                {                        label = whereTo;                }        }               public void ship(String dest)        {                Contents c = new Contents();  // create object of inner class Contents                Destination d = new Destination(dest);  // create object of inner class Destination                 System.out.println("Shipped " + c.value() + " item(s) to " + dest);        }         public static void main(String args[])        {                Inner1 p = new Inner1();                p.ship("Congo");  //call ship method of outer class "inner1"        }

33 }

 Output : Shipped 16 item(s) to Congo Let us see one more example but here the program will not compile?123456789101112131415161718192021222324252627282930313233

class Outer {    int outer_x = 100;    void test()     {        Inner inner = new Inner();        inner.display();    }     // this is an inner class     class Inner     {        int y = 10; // y is local to Inner        void display()         {            System.out.println("display: outer_x = " + outer_x);        }    }    void showy()     {        System.out.println(y); // error, y not known here!    }} class InnerClassDemo {    public static void main(String args[])     {        Outer outer = new Outer();        outer.test();    }}

 Here, y is declared as an instance variable of Inner. Thus it is not known outside ofthat class and it cannot be used by showy( ).

 

Command Line Argument :

Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).  

A command-line argument is the information that directly follows the program’s name on the command line when it is executed.  To access the command-line arguments inside a Java program is quite easy—they are stored as strings in the String array passed to main( ).?12345678

class CommandLine{    public static void main(String args[])     {        for(int i=0; i < args.length; i++)            System.out.println("args[" + i + "]: " +args[i]);    }}

 Try executing this program, as shown here: java CommandLine this is a test 100 -1 When you do, you will see the following output: args[0]: thisargs[1]: isargs[2]: aargs[3]: testargs[4]: 100args[5]: -1 But first of all you should have the basic knowledge about command line and how any java program run through command prompt. CLICK HERE to know more.

 

Inheritance in java:

What is a Inheritance ?

The derivation of one class from another class is called Inheritance.

Type of inheritance :

A class that is inherited is called a superclass.

The class that does the inheriting is called as subclass.

In above figure all class A is superclass.

A subclass inherits all instance variables and methods from its superclass and also has its own variables and methods.

One can inherit the class using keyword extends.

Syntax :

Class subclass-name extends superclass-name

{

            // body of class.

}

In java, a class has only one super class.

Java does not support Multiple Inheritance.

One can create a hierarchy of inheritance in which a subclass becomes a superclass of another subclass.

However, no class can be a superclass of itself. 

EX :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class A   //superclass

{

    int num1;    //member of superclass

    int num2;    //member of superclass

    void setVal(int no1, int no2)   //method of superclass

    {

        num1 = no1;

        num2 = no2;

    }

}

 

class B extends A   //subclass B

{

    int multi;   //member of subclass

    void mul()   //method of subclass

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

    {

        multi = num1*num2;   //accessing member of superclass from subclass

    }

}

 

class inhe2

{

    public static void main(String args[])

    {

        B subob = new B();

        subob.setVal(5,6);  //calling superclass method throgh subclass object

        subob.mul();

        System.out.println("Multiplication is  " + subob.multi);

    }

}

 

Output :

 

Multiplication is  30

 

Note : Private members of superclass is not accessible in subclass,

           superclass is also called parentclass or baseclass,

           subclass is also called childclass or derivedclass.

 

super - final - keywords in java:

Let us see now two most important keywords of java

1. super :

super keyword is used to call a superclass constructor and to call or access super class members(instance variables or methods).

syntax of super :

=> super(arg-list)

When a subclass calls super() it is calling the constructor of its immediate superclass.

super() must always be the first statement executed inside a subclass constructor.

=> super.member

Here member can be either method or an instance variables.

This second form of super is most applicable to situation in which member names of a subclass hide member of superclass due to same name.

EX :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class A1

{

    public int i;

    A1()

    {

        i=5;

    }

}

 

class B1 extends A1

{

    int i;

    B1(int a,int b)

    {

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

        super();    //calling super class constructor

        //now we will change value of superclass variable i

        super.i=a;  //accessing superclass member from subclass

        i=b;

    }

    void show()

    {

        System.out.println("i in superclass = " + super.i );

        System.out.println("i in subclass = " + i );

    }

}

 

public class Usesuper

{

        public static void main(String[] args)

        {

            B1 b = new B1(10,12);

            b.show();

             

        }

}

 

Output :

 

i in superclass = 10

i in subclass = 12

 

The instance variable i in B1 hides the i in A, super allows access to the i defined in the superclass.

 

super can also be used to call methods that are hidden by a subclass.

2. final :

final keyword can be use with variables, methods and class.

=> final variables.

When we want to declare constant variable in java we use final keyword.

Syntax : final variable name = value;

=> final method

Syntax final methodname(arg)

When we put final keyword before method than it becomes final method.

To prevent overriding of method final keyword is used, means final method cant be override.

=> final class

A class that can not be sub classed is called a final class.

This is archived in java using the keyword final as  follow.

Syntax : final class class_name {   ...   }

Any attempt to inherit this class will cause an error and compiler will not allow it.

EX:

?

1

2

3

4

5

6

final class aa

{

    final int a=10;

    public final void ainc()

    {

        a++;   // The final field aa.a cannot be assigned

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

    }

     

}

 

class bb extends aa    // The type bb cannot subclass the final class aa  

{

    public void ainc()    //Cannot override the final method from aa

    {

        System.out.println("a = " + a);

    }

}

 

public class Final_Demo

{

    public static void main(String[] args)

    {

        bb b1 = new bb();

        b1.ainc();

    }

}

 

Here no output will be there because all the comments in above  program are errors. Remove final keyword from class than you will get error like final method can not be override.

 

Method overriding :

Defining a method in the subclass that has the same name, same arguments and same return type as a method in the superclass and it hides the super class method is called method overriding.

Now when the method is called, the method defined in the subclass is invoked and executed instead of the one in the superclass.

?123456789101112131415161718192021222324252627282930313233343536

class Xsuper{    int y;    Xsuper(int y)    {        this.y=y;    }    void display()    {        System.out.println("super y = " +y);    }}class Xsub extends Xsuper{    int z;    Xsub(int z , int y)     {        super(y);        this.z=z;    }    void display()    {        System.out.println("super y = " +y);        System.out.println("sub z = " +z);    }     } public class TestOverride {    public static void main(String[] args)     {        Xsub s1 = new Xsub(100,200);        s1.display();    }}

 Output : super y = 200sub z = 100 Here the method display() defined in the subclass is invoked.

Overloading VS Overriding :

Methodoverloading is comiple time polymorphism.

Method overriding is run time polymorphism.

Overloading a method is a way to provide more than one method in one class which have same name but different argument to distinguish them.

Defining a method in the subclass that has the same name, same arguments and same return type as a method in the superclass is called method overriding.

Multilevel Inheritance in java:

Multilevel Hierarchy :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

class student

{

    int rollno;

    String name;

 

    student(int r, String n)

    {

        rollno = r;

        name = n;

    }

    void dispdatas()

    {

        System.out.println("Rollno = " + rollno);

        System.out.println("Name = " + name);

    }

}

 

class marks extends student

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

{

    int total;

    marks(int r, String n, int t)

    {

        super(r,n);   //call super class (student) constructor

        total = t;

    }

    void dispdatam()

    {

        dispdatas();    // call dispdatap of student class

        System.out.println("Total = " + total);

    }

}

 

class percentage extends marks

{

    int per;

     

    percentage(int r, String n, int t, int p)

    {

        super(r,n,t);  //call super class(marks) constructor

        per = p;

    }

    void dispdatap()

    {

        dispdatam();    // call dispdatap of marks class

        System.out.println("Percentage = " + per);

46

47

48

49

50

51

52

53

54

55

    }

}

class Multi_Inhe

{

    public static void main(String args[])

    {

        percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage

        stu.dispdatap();  // call dispdatap of percentage class

    }

}

 

Output :

 

Rollno = 1912

Name = SAM

Total = 350

Percentage = 50

 

It is common that a class is derived from another derived class.

 

The class student serves as a base class for the derived class marks, which in turn serves as a base class for the derived class percentage.

 

The class marks is known as intermediated base class since it provides a link for the inheritance between student and percentage.

 

The chain is known as inheritance path. 

 

When this type of situation occurs, each subclass inherits all of the features found in all of its super classes. In this case, percentage inherits all aspects of marks and student. 

To understand the flow of program read all comments of program.

When a class hierarchy is created, in what order are the constructors for the classes that

make up the hierarchy called?

 

EX :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

class X

{

    X()

    {

        System.out.println("Inside X's constructor.");

    }

}

 

class Y extends X   // Create a subclass by extending class A.

{

    Y()

    {

        System.out.println("Inside Y's constructor.");

    }

}

 

class Z extends Y   // Create another subclass by extending B.

{

    Z()

20

21

22

23

24

25

26

27

28

29

30

31

    {

        System.out.println("Inside Z's constructor.");

    }

}

 

public class CallingCons

{

    public static void main(String args[])

    {

        Z z = new Z();

    }

}

 

Output:

 

Inside X's constructor.

Inside Y's constructor.

Inside Z's constructor.

 

The answer is that in a class hierarchy, constructors are called in order of derivation, from superclass to subclass.

 

Further, since super( ) must be the first statement executed in a subclass’ constructor,  this order is the same whether or not super( ) is used.

 

If super( ) is not used, then the default or parameterless constructor of each superclass will be executed.

 

As you can see from the output the constructors are called in order of derivation.

 

If you think about it, it makes sense that constructors are executed in order of derivation.

 

Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must be executed first.

 

Dynamic Method Dispatch:

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time.

Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

method to execution based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

EX :

?12345678910111213141516171819202122

class A {    void callme()     {        System.out.println("Inside A's callme method");    }} class B extends A {        // override callme()    void callme()     {        System.out.println("Inside B's callme method");    }} class C extends A {        // override callme()    void callme()     {

232425262728293031323334353637383940414243

        System.out.println("Inside C's callme method");    }} public class Dynamic_disp {    public static void main(String args[])     {        A a = new A(); // object of type A        B b = new B(); // object of type B        C c = new C(); // object of type C        A r; // obtain a reference of type A        r = a; // r refers to an A object        r.callme(); // calls A's version of callme        r = b; // r refers to a B object        r.callme(); // calls B's version of callme                 r = c; // r refers to a C object        r.callme(); // calls C's version of callme    }}

 Output : Inside A's callme methodInside B's callme methodInside C's callme method Here reference of type A, called r, is declared. The program then assigns a reference to each type of object to r and uses that reference to invoke callme( ). As the output shows, the version of callme( ) executed is determined by the type of object being referred to at the time of the call.

 

Abstract Classes :

When the keyword abstract appears in a class definition, it means that zero or more of it’s methods are abstract.

An abstract method has no body.

Some of the subclass has to override it and provide the implementation.

Objects cannot be created out of abstract class.

Abstract classes basically provide a guideline for the properties and methods of an object.

In order to use abstract classes, they have to be subclassed.

There are situations in which you want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method.

That is, sometimes you want to create a superclass that only defines generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method.

Syntax :

            abstract type name(parameter-list);

As you can see, no method body is present.

Any class that contains one or more abstract methods must also be declared abstract.

To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration.

There can be no objects of an abstract class.

That is, an abstract class cannot be directly instantiated with the new operator.

Any subclass of an abstract class must either implement all of the abstract methods of the superclass, or be itself declared abstract.

EX :

?123456789101112131415161718192021

abstract class A1{    abstract void displayb1();    void displaya1()    {        System.out.println("This is a concrete method");    }     } class B1 extends A1{    void displayb1()    {        System.out.println("B1's implementation");    }} public class Abstract_Demo {    public static void main(String args[])

222324252627

    {        B1 b = new B1();        b.displayb1();        b.displaya1();      }}

 Output : B1's implementationThis is a concrete method EX 2 :  

 

?1234567891011121314151617181920212223242526272829303132333435

abstract class shape{    double dim1;    double dim2;    shape(double a, double b)    {        dim1 = a;        dim2 = b;    }    abstract double area();} class rectangle extends shape{    rectangle(double a, double b)    {        super(a,b);    }    double area()    {        System.out.println("Area of rectangle.");        return dim1*dim2;    }} class triangle extends shape{    triangle(double a, double b)    {        super(a,b);    }    double area()    {        System.out.println("Area of triangle.");        return dim1*dim2/2;

3637383940414243444546474849

    }} public class Abstract_D2 {    public static void main(String args[])    {        rectangle r = new rectangle(10,20);        triangle t = new triangle(10,6);                 System.out.println(r.area());        System.out.println(t.area());       }}

 Output: Area of rectangle.200.0Area of triangle.30.0

 

The Object class :

There is one special class, Object, defined by Java. All other classes are subclasses of Object.

That is, Object is a superclass of all other classes.

This means that a reference variable of type Object can refer to an object of any other class.

Every class in java is descended from the java.lang.Object  class.

If no inheritance is specified when a class is defined, the super class of the class is Object by default.

EX :

public class circle { ... }

is equivalent to

public class circle extends Object { ... }

Methods of Object class

METHOD PURPOSE

Object clone() Creates a new object that is the same as the object being cloned.

boolean equals(Object obj_name) Determines whether one object is equal to another

Void finalize() Called before an unused object is recycled

Class getClass( ) Obtains the class of an object at run time.

int hashCode( ) Returns the hash code associated with the invoking object.

void notify( ) Resumes execution of a thread waiting on the invoking object.

void notifyAll( ) Resumes execution of all threads waiting on the invoking object.

String toString( ) Returns a string that describes the object.void wait( )

void wait(long milliseconds)

void wait(long milliseconds, int nanoseconds)

Waits on another thread of execution.

The methods getclass(), notify(), notifyall() and wait() are declared as final.

You may override the others.

tostring()

?public String tostring()

it returns a String that describe an object.

?It consisting class name, an at (@) sign and object memory address in hexadecimal.

EX :

Circle c1 = new Circle();

System.out.println(c1.tostring());

It will give O/P like Circle@15037e5

We can also write System.out.println(c1);

Polymorphism :

An object of a sub class can be used whenever its super class object is required.

This is commonly known as polymorphism.

In simple terms polymorphism means that a variable of super type can refer to a sub type object.

Java Interface:

Interfaces are similar to abstract classes, but differ in their functionality.

In interfaces, none of the methods are implemented means interfaces defines methods without body.

Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.

But, it can contain final variables, which must be initialized with values.

Once it is defined, any number of classes can implement an interface.

One class can implement any number of interfaces.

If we are implementing an interface in a class we must implement all the methods defined in the interface as well as a class can also implement its own methods.

Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in C++. 

Defining interfaces in java with syntax:

Syntax :

[Access-specifier] interface interface-name

{

Access-specifier return-type method-name(parameter-list);

final type var1=value;

}

Where, Access-specifier is either public or it is not given.

When no access specifier is used, it results into default access specifier and if interface has default access specifier then it is only available to other members of the same package.

When it is declared as public, the interface can be used by any other code of other package.

       Interface-Name: name of an interface, it can be any valid identifier.

The methods which are declared having no bodies they end with a semicolon after the parameter list. Actually they are abstract methods;

Any class that includes an interface must implement all of the methods. Variables can be declared inside interface declarations.

They are implicitly final and static, means they can not be changed by implementing it in a class.

They must also be initialized with a constant value.

EX :

interface Item

{

       static final int code = 100;

       static final String name = "Fan";

       void display ( );

}

 

interface Area

{

       static final float pi = 3.14F;

       float compute ( float x, float y );

       void show ( );

}

 

Once an interface has been defined, one or more classes can implement that interface.

To implement an interface, include the implements clause in a class definition, and then create the methods declared by the interface.

The general form of a class that includes the implements clause looks like this:

Access-specifier class classname [extends superclass] [implements interface, [, interface..]]

{

            // class body

      }

If a class implements from more than one interface, names are separated by comma.

If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface.

The methods that implement an interface must be declared as public.

The type-signature of implementing method must match exactly the type signature specified in the interface.

?1234567

interface religion{    String city = new String("Amritsar");    void greet();    void pray();} 

8910111213141516171819202122232425262728

class gs implements religion{    public void greet()    {        System.out.println("We greet - ABCD");    }    public void pray()    {        System.out.println("We pray at " + city + " XYZ ");    }} class iface1{    public static void main(String args[])    {        gs sikh = new gs();        sikh.greet();        sikh.pray();    }}

 Output : We greet - ABCDWe pray at Amritsar XYZ EX 2 :?12345678910111213141516171819202122232425

interface i1{    void dispi1();} interface i2{    void dispi2();} class c1 implements i1{    public void dispi1()    {        System.out.println("This is display of i1");    }} class c2 implements i2{    public void dispi2()    {        System.out.println("This is display of i2");    }}

26272829303132333435363738394041424344454647484950515253

 class c3 implements i1, i2{    public void dispi1()    {        System.out.println("This is display of i1");    }    public void dispi2()    {        System.out.println("This is display of i2");    }} class iface2{    public static void main(String args[])    {        c1 c1obj = new c1();        c2 c2obj = new c2();        c3 c3obj = new c3();                             c1obj.dispi1();        c2obj.dispi2();        c3obj.dispi1();        c3obj.dispi2();             }}

 Output : This is display of i1This is display of i2This is display of i1This is display of i2 EX 3 : // Implementing interface having common function name?12345678910111213141516

interface i1{    void disp();} interface i2{    void disp();} class c implements i1, i2{    public void disp()    {        System.out.println("This is display .. ");    }

1718192021222324252627

} class iface7{    public static void main(String args[])    {        c cobj = new c();                     cobj.disp();    }}

 Output : This is display .. 

Note : When implementing an interface method, it must be declared as public. It is possible for classes that implement interfaces to define additional members of their own.

Partial Implementation of Interface :

If we want to implement an interface in a class we have to implement all the methods defined in the interface.

But if a class implements an interface but does not fully implement the method defined by that interface, then that class must be declared as abstract.

EX :

?1234567891011121314151617181920212223

interface i1{    void disp1();    void disp2();} abstract class c1 implements i1{    public void disp1()    {        System.out.println("This is display of 1");    }} class c2 extends c1{    public void disp2()    {        System.out.println("This is display of 2");    }} class iface

2425262728293031

{    public static void main(String args[])    {        c2 c2obj = new c2();        c2obj.disp1();        c2obj.disp2();    }}

 Output : This is display of 1This is display of 2

 

Accessing interface variable :

One can declare variable as object references that uses an interface rather than a class type.

When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being referred to.

?1234567891011121314151617181920212223242526

interface AreaCal{    final double pi = 3.14;    double areacalculation(double r);} class Circle implements AreaCal{    public double areacalculation(double r)    {        double ar;        ar = pi*r*r;        return ar;    }} class iface3{    public static void main(String args[])    {        double area;        AreaCal ac = new Circle();        area = ac.areacalculation(10.25);        System.out.println("Area of Circle is : " + area);    }}

 

Output : Area of Circle is : 329.89625 

Here variable ac is declared to be of the interface type AreaCal,

it was assigned an instance of circle. Although ac can be used to access the areacalculation() method,

it cannot access any other members of the client class. An interface reference variable only has knowledge of the method declared by its interface declaration.

Extending interfaces :

One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes.

When a class implements an interface that inherits another interface,

It must provide implementation of all methods defined within the interface inheritance.

Note : Any class that implements an interface must implement all methods defined by that interface, including any that inherited from other interfaces.

EX :

?12345678910111213141516171819202122232425

interface if1{    void dispi1();}interface if2 extends if1{    void dispi2();}class cls1 implements if2{    public void dispi1()    {        System.out.println("This is display of i1");    }    public void dispi2()    {        System.out.println("This is display of i2");    }}public class Ext_iface {    public static void main(String args[])    {        cls1 c1obj = new cls1();             

2627282930

        c1obj.dispi1();        c1obj.dispi2();    } }

 Output : This is display of i1This is display of i2

Note : We have to define disp1() and disp2() in cls1.

Multiple inheritance using interface..

?12345678910111213141516171819202122232425262728293031323334353637

class stu{    int rollno;    String name = new String();    int marks;    stu(int r, String n, int m)    {        rollno = r;        name = n;        marks = m;    }} interface i{    void display();} class studerived extends stu implements i{    studerived(int r, String n, int m)    {        super(r,n,m);    }    public void display()    {        System.out.println("Displaying student details .. ");        System.out.println("Rollno = " + rollno);        System.out.println("Name = " + name);        System.out.println("Marks = " + marks);    }} public class Multi_inhe_demo {    public static void main(String args[])    {

3839404142

        studerived obj = new studerived(1912, "Ram", 75);        obj.display();    } }

 Output : Displaying student details .. Rollno = 1912Name = RamMarks = 75

We can make various forms of interface implementation as below

String Handling in java:

In Java, a string is defined as a sequence of characters.

But, unlike many other languages that implement strings as character arrays, java implements strings as objects of type String.

Java handles String by two classes StringBuffer and String. The String and StringBuffer classes are defined in java.lang.

Thus, they are available to all programs automatically.

1. String Concatenation (+)

EX :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import java.util.*;

class str3

{

    public static void main(String args[])

    {

        String s1 = new String ("Java");

        String s2 = "2all";

        String s3 = s1+s2;

        System.out.println("S1 = " + s1);

        System.out.println("S2 = " + s2);

        System.out.println("Concatenation Operator = " + s1+s2);

        System.out.println("S3 = " + s3);

     

        byte num [] = {65,66,67,68};

        String s4 = new String(num);

        System.out.println("S4 = " + s4);

    }

}

 

Output :

 

S1 = Java

S2 = 2all

Concatenation Operator = Java2all

S3 = Java2all

S4 = ABCD

 

2. Character Extraction :

 

The String class provides ways in which characters can be extracted from a String object.

 

 

3. String Comparison :

The String class provides several methods that compare strings or substrings within strings.

equals( ) – used to compare two strings

General form:

       Boolean equals(Object str)

Here, str is a String object.

It returns true if the strings contain the same character otherwise it returns false.

The comparison is case-sensitive.

equalsIgnoreCase( ) – Same as equals but this ignores case.

General form:

      Boolean equalsIgnoreCase(String str)

Here, str is the String object.

It returns true if the strings contain the same character otherwise it returns false.

This is case in – sensitive.

      regionMatches( )

This method compares a specific region inside a string with another specific region in another string.

There is an overloaded form that allows you to ignore case in such comparisons.

General form:

      Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars)

      Boolean regionMatches(Boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)

startsWith( ) and endsWith()

The startsWith( )  method determines whether a given String begins with a specified string.

endsWith( ) determines whether the String ends with a specified string.

General Form

      Boolean startsWith(String str)

      Boolean endsWith(String str)

equals( ) Versus = =

Equals( ) method and the = = operator perform two different operations. The equals ( ) method compares the characters inside a String object. The = = operator compares two object references to see whether they refer to the same instance.

compareTo( )

It is not enough to know that two strings just for equal or not. For sorting applications, we need to know which is less than, equal to, or greater than the other string.

The String method compareTo( ) serves this purpose.

General Form:

      int compareTo(String str)

4 Modifying a string :

If we want to modify a String, we must either copy it into a StringBufer or we can use following String methods:

5 valueOf() :

The valueOf() method converts data from internal format into a human-readable form. It has several forms:

String valueOf(double num)

String valueOf(long num) 

String valueOf(Object ob)

String valueOf(char chars[ ] )

String valueOf(char chars[], int startIndex, int numChars)

String Methods in java:

Example :

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import java.util.*;

class str1

{

    public static void main(String args[])

    {

        String s1 = "Bhagirath";

        System.out.println("S1 = " + s1);

        int length = s1.length();

        System.out.println("S1 lenth = " + length);

        System.out.println("S1 lowercase = " + s1.toLowerCase());

        System.out.println("S1 uppercase = " + s1.toUpperCase());

        System.out.println("S1 replace a with z = " + s1.replace('a','z'));

        System.out.println("S1 indexOf('e')= " + s1.indexOf('e'));

        System.out.println("S1 lastindexof('e') = " + s1.lastIndexOf('e'));

        String s2 = "ViewSonic";

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

        System.out.println("S2 = " + s2);

        System.out.println("S1 and S2 trim = " + s1.trim() + s2.trim());

        System.out.println("S1 and S2 equals = " + s1.equals(s2));

        System.out.println("S1 and S2 equals ignoring case = " + s1.equalsIgnoreCase(s2));

        System.out.println("S1 and S2 compareTo = " + s1.compareTo(s2));

        System.out.println("S1 and S2 concate = " + s1.concat(s2));

        System.out.println("S1 substring(n) = " + s1.substring(5));

        System.out.println("S1 substring(n,m) = " + s1.substring(5,8));

        System.out.println("S1 toString() = " + s1.toString());

        int i = 100;

        System.out.println("S1.valueOf(variable) = " + (s1.valueOf(i)).length()); // converts the parameter to string

        System.out.println("Start with " + s1.startsWith("P"));

        System.out.println("Start with " + s1.endsWith("y"));

         

    }

}

 

Output :

 

S1 = Bhagirath

S1 lenth = 9

S1 lowercase = bhagirath

S1 uppercase = BHAGIRATH

S1 replace a with z = Bhzgirzth

S1 indexOf('e')= -1

S1 lastindexof('e') = -1

S2 = ViewSonic

S1 and S2 trim = BhagirathViewSonic

S1 and S2 equals = false

S1 and S2 equals ignoring case = false

S1 and S2 compareTo = -20

S1 and S2 concate = BhagirathViewSonic

S1 substring(n) = rath

S1 substring(n,m) = rat

S1 toString() = Bhagirath

S1.valueOf(variable) = 3

Start with false

Start with false

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import java.util.*;

class str4

{

    public static void main(String args[])

    {

        String s = "This is a dAmo of the getChars method.";

        int start = 10;

        int end = 14;

        char buf[] = new char[10];

        //System.out.println("Character at 10 = " + s.charAt(10));

        s.getChars(start, end, buf,0); 

        System.out.println(buf);

        s.getChars(start, end, buf,5); 

        System.out.println(buf);

         

16

17

18

19

20

21

22

23

24

25

26

27

        byte bt [] = new byte[10];

        s.getBytes(start, end, bt,0);  

        System.out.println(bt[0]);

        System.out.println(bt[1]);

        System.out.println(bt[2]);

        System.out.println(bt[3]);

         

        char buf1[] = s.toCharArray(); 

        System.out.println(buf1);

         

    }

}

 

Output :

 

 jav      

 jav  jav 

32

74

97

118

Welcome to Java2all

 

?

1

2

import java.util.*;

class str5

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

{

    public static void main(String args[])

    {

        String s1 = "Rome was not built in a not day";

        System.out.println("S1 = " + s1);

        /*System.out.println("S1 = " + s1.indexOf('o'));

        System.out.println("S1 = " + s1.indexOf("not"));

        System.out.println("S1 = " + s1.indexOf('o',5));

        System.out.println("S1 = " + s1.indexOf("not", 15));

         

        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o'));

        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not"));

        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o',15));

        System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not", 15));

        */

        String s2 = "Rome was not built in a Not day";

        System.out.println("S2 = " + s2);

        //System.out.println("S1 = " + s1.indexOf("not"));

        //System.out.println("S1 = " + s1.lastIndexOf("not"));

        System.out.println("Region Matches = ");

        boolean b1 = s1.regionMatches(false,9,s2,24,3);

        System.out.println("b1 = " + b1);

         

     

    }

}

 

Output :

 

S1 = Rome was not built in a not day

S2 = Rome was not built in a Not day

Region Matches = 

b1 = false

 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

import java.util.*;

class str6

{

    public static void main(String args[])

    {

        String s1 = "Hello";

        String s2 = new String(s1);

        System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));

        System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

         

         

    }

}

 

Output :

 

Hello equals Hello -> true

Hello == Hello -> false

 

StringBuffer class :

StringBuffer is a peer class of String. String creates strings of fixed length, while StringBuffer creates strings of flexible length that can be modified in terms of both length and content.

So Strings that need modification are handled by StringBuffer class.

We can insert characters and substrings in the middle of a string, or append another string to the end.

            StringBufer defines these Constructor:

            StringBuffer()

            StringBuffer(int size)

            StringBuffer(String str)

Method Call Task PerformedSb.length() Gives the current length of a StringBuffer.Sb.capacity() Gives the total allocated capacity (default 16)

setLength(int len) Set the length of the buffer within a String Buffer object.

charAt(int where) Gives the value of character

setCharAt(int where, char ch) Set the value of a character within a StringBuffer.

S1.append(s2) Appends the string s2 to s1 at the end

S1.insert(n,s2) Inserts the string s2 at the position n of the string s1

S1.reverse() Reverse the string of s1S1.deleteCharAt(nth) Delete the nth character of string s1S1.delete(StartIndex, endIndex) Delete characters from start to end.

EX :

?123456789101112

import java.util.*; class strbuf1{        public static void main(String args[])        {            StringBuffer s1 = new StringBuffer();            StringBuffer s2 = new StringBuffer("Bhagirath");            StringBuffer s3 = new StringBuffer(s2);            StringBuffer s4 = new StringBuffer(100);            System.out.println("s1 = " + s1);            System.out.println("s2 = " + s2);

131415161718192021222324252627

            System.out.println("s3 = " + s3);                         System.out.println("s1.length = " + s1.length());            System.out.println("s2.length = " + s2.length());            System.out.println("s3.length = " + s3.length());            System.out.println("s4.length = " + s4.length());                         System.out.println("s1.capacity = " + s1.capacity());            System.out.println("s2.capacity = " + s2.capacity());            System.out.println("s3.capacity = " + s3.capacity());            System.out.println("s4.capacity = " + s4.capacity());                                  }}

 Output : s1 = s2 = Bhagiraths3 = Bhagiraths1.length = 0s2.length = 9s3.length = 9s4.length = 0s1.capacity = 16s2.capacity = 25s3.capacity = 25s4.capacity = 100

EX :

?1234567891011121314151617181920

import java.util.*;class strbuf2{        public static void main(String args[])        {            StringBuffer s1 = new StringBuffer("Java2all");            StringBuffer s2 = new StringBuffer("Hello");            System.out.println("s1 = " + s1);            //System.out.println("s1.charAt(5) = " + s1.charAt(5));            //s1.setCharAt(5,'z');            //System.out.println("s1 = " + s1);             //System.out.println("Inserting String = " + s1.insert(5,s2));            //System.out.println("s1 = " + s1);             //System.out.println("Appending String = " + s1.append(s2));            //System.out.println("s1 = " + s1);             //System.out.println("Reversing String = " + s1.reverse());             //System.out.println("Deleting 5th character = " + s1.deleteCharAt(5));             System.out.println("Deleting 5 to 8 character = " + s1.delete(5,8));         }}

 Output : s1 = Java2allDeleting 5 to 8 character = Java2

EX :

?123456789101112131415161718192021

import java.util.*; public class strbuf3{    public static void main(String[] args)    {          StringBuffer s = new StringBuffer("Hello world!");         System.out.println("s = " + s);        System.out.println("s.length() = " + s.length());        System.out.println("s.length() = " + s.capacity());        // Change the length of buffer to 5 characters:        s.setLength(5);         System.out.println(s);        System.out.println("s.length() = " + s.length());        System.out.println("s.length() = " + s.capacity());             }}

 Output : s = Hello world!s.length() = 12s.length() = 28Hellos.length() = 5s.length() = 28

 

Introduction to JDBC:

JDBC - Java Database Connectivity.

JDBC provides API or Protocol to interact with different databases.

With the help of JDBC driver we can connect with different types of databases.

Driver is must needed for connection establishment with any database.

A driver works as an interface between the client and a database server.

JDBC have so many classes and interfaces that allow a java application to send request made by user to any specific DBMS(Data Base Management System).

JDBC supports a wide level of portability.

JDBC provides interfaces that are compatible with java application

components and specification of JDBC:

Components of JDBC:

JDBC has four main components as under and with the help of these components java application can connect with database.

The JDBC API - it provides various methods and interfaces for easy communication with database.

The JDBC DriverManager - it loads database specific drivers in an application to establish connection with database.

The JDBC test suite - it will be used to test an operation being performed by JDBC drivers.

The JDBC-ODBC bridge - it connects database drivers to the database.

JDBC Specification:

Different version of JDBC has different specification as under.

JDBC 1.0 - it provides basic functionality of JDBC

JDBC 2.0 - it provides JDBC API(JDBC 2.0 Core API and JDBC 2.0 Optional Package API).

JDBC 3.0 - it provides classes and interfaces in two packages(java.sql and javax.sql).

JDBC 4.0 - it provides so many extra features like

Auto loading of the driver interface.

Connection management

ROWID data type support.

Enhanced support for large object like BLOB(Binary Large Object) and CLOB(Character Large Object). 

JDBC Architecture:

As we all know now that driver is required to communicate with database.

JDBC API provides classes and interfaces to handle request made by user and response made by database.

Some of the important JDBC API are as under.

DriverManager

Driver

Connection

Statement

PreparedStatement

CallableStatement

ResultSet

DatabaseMetaData

ResultSetMetaData

Here The DriverManager plays an important role in JDBC architecture.

It uses some database specific drivers to communicate our J2EE application to database.

As per the diagram first of all we have to program our application with JDBC API.

With the help of DriverManager class than we connect to a specific database with the help of spcific database driver.

Java drivers require some library to communicate with the database.

We have four different types of java drivers.

We will learn all that four drivers with architecture in next chapter.

Some drivers are pure java drivers and some are partial.

So with this kind of JDBC architecture we can communicate with specific database.

We will learen programatically all this thing in further chapter. 

JDBC Driver Types:

There are four categories of drivers by which developer can apply a connection between Client (The JAVA application or an applet) to a DBMS.

(1)   Type 1 Driver : JDBC-ODBC Bridge.

(2)   Type 2 Driver : Native-API Driver (Partly Java driver).

(3)   Type 3 Driver : Network-Protocol Driver (Pure Java driver for database Middleware).

(4)   Type 4 Driver : Native-Protocol Driver (Pure Java driver directly connected to database).

(1) Type 1 Driver: JDBC-ODBC Bridge  :-

The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.

Sun provides a JDBC-ODBC Bridge driver by “sun.jdbc.odbc.JdbcOdbcDriver”.

The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example, ODBC must be installed on the computer and the database must support ODBC driver.

Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on Microsoft platform.

The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a particular database.

Architecture Diagram:

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 1 Driver   →   ODBC Driver   → Database library APIs → Database

Advantage:

(1)   Connect to almost any database on any system, for which ODBC driver is installed.

(2)   It’s an easy for installation as well as easy(simplest) to use as compare the all other driver.

Disadvantage:

(1)   The ODBC Driver needs to be installed on the client machine.

(2)   It’s a not a purely platform independent because its use ODBC which is depends on native libraries of the operating system on client machine.

(3) Not suitable for applets because the ODBC driver needs to be installed on the client machine.

(2) Type 2 Driver: Native-API Driver (Partly Java driver) :-

The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database  so this driver is also known as a Native-API driver.

Architecture Diagram :

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 2 Driver   →  Vendor Client Database library APIs → Database

Advantage:

(1)   There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).

Disadvantage:

(1)   On the client machine require the extra installation because this driver uses the vendor client libraries.

(2)   The Client side software needed so cannot use such type of driver in the web-based application.

(3)   Not all databases have the client side library.

(4)   This driver supports all JAVA applications except applets.

(3) Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware) :-

The JDBC type 3 driver uses the middle tier(application server) between the calling program and the database and this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be used for multiple databases also so it’s also known as a Network-Protocol driver as well as a JAVA driver for database middleware.

Architecture Diagram:

 

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 3 Driver   →  Middleware (Server)→ any Database

Advantage:

(1) There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client.

(2) Type 3 driver can be used in any web application as well as on internet also because there is no any software require at client side.

(3) A single driver can handle any database at client side so there is no need a separate driver for each database.

(4) The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc.

Disadvantage:

(1) An Extra layer added, may be time consuming.

(2) At the middleware develop the database specific coding, may be increase complexity.

(4) Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to database) :-

The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written in JAVA because of that this is also known as the “direct to database Pure JAVA driver”.

Architecture Diagram:

 

 

Process:

Java Application   → JDBC APIs     → JDBC Driver Manager →   Type 4 Driver (Pure JAVA Driver)   → Database Server

Advantage:

(1)   It’s a 100% pure JAVA Driver so it’s a platform independence.

(2)   No translation or middleware layers are used so consider as a faster than other drivers.

(3)   The all process of the application-to-database connection can manage by JVM so the debugging is also managed easily.

Disadvantage:

(1)There is a separate driver needed for each database at the client side.

(2) Drivers are Database dependent, as different database vendors use different network protocols.

JDBC APIs:

If any java application or an applet wants to connect with a database then there are various classes and interfaces available in java.sql package.

Depending on the requirements these classes and interfaces can be used.

Some of them are list out the below which are used to perform the various tasks with database as well as for connection.

Class or Interface DescriptionJava.sql.Connection Create a connection with specific database

Java.sql.DriverManager The task of DriverManager is to manage the database driver

Java.sql.Statement It executes SQL statements for particular connection and retrieve the results

Java.sql.PreparedStatement It allows the programmer to create prepared SQL statements

Java.sql.CallableStatement It executes stored procedures

Java.sql.ResultSet This interface provides methods to get result row by row generated by SELECT statements

Now we are going to elobrate each class or interface in detail with their methods and will give program for each one in next topic.

The Connection interface:

The Connection interface used to connect java application with particular database.

After crating the connection with database we can execute SQL statements for that particular connection using object of Connection and retrieve the results.

The interface has few methods that makes changes to the database temporary or permanently.

The some methods are as given below.

Method Description

void close()This method frees an object of type Connection from database and other JDBC resources.

void commit()This method makes all the changes made since the last commit or rollback permanent. It throws SQLExeception.

Statement createStatement() This method creates an object of type Statement for sending SQL statements to the

database. It throws SQLExeception.

boolean isClosed() Return true if the connection is close else return false.

CallableStatement prepareCall(String s)

This method creates an object of type CallableStatement  for calling the stored procedures from database. It throws SQLExeception.

PreparedStatement prepareStatement(String s)

This method creates an  object  of type PrepareStatement for sending dynamic (with or without IN parameter) SQL statements to the database. It throws SQLExeception.

void rollback() This method undoes all changes made to the database.

The example program for Connection interface and its methods are given in next chapter for different databases.

Statement Interface:

The Statement interface is used for to execute a static query.

It’s a very simple and easy so it also calls a “Simple Statement”.

The statement interface has several methods for execute the SQL statements and also get the appropriate result as per the query sent to the database.

Some of the most common methods are as given below

Method Description

void close()This method frees an object of type Statement from database and other JDBC resources.

boolean execute(String s)This method executes the SQL statement specified by s. The getResultSet() method is used to retrieve the result.

ResultSet getResultet()This method retrieves the ResultSet that is generated by the execute() method.

ResultSet executeQuery(String s)This method is used to execute the SQL statement specified by s and returns the object of type ResultSet.

int getMaxRows()This method returns the maximum number of rows those are generated by the executeQuery() method.

Int executeUpdate(String s)This method executes the SQL statement specified by s. The SQL statement may be a SQL insert, update and delete statement.

The example program for Statement interface and its methods are given in next chapter for different databases.

The Prepared Statement Interface:

The Prepared Statement interface is used to execute a dynamic query (parameterized SQL statement) with IN parameter.

IN Parameter:-

In some situation where we need to pass different values to an query then such values can be specified as a “?” in the query and the actual values can be passed using the setXXX() method at the time of execution.

Syntax :        

            setXXX(integer data ,XXX value);

Where XXX means a data type as per the value we want to pass in the query.

For example,

String query = "Select * from Data where ID = ? and Name = ? ";

PreparedStatement ps = con.prepareStatement(query);

              ps.setInt(1, 1);   

              ps.setString(2, "Ashutosh Abhangi");

The Prepared statement interface has several methods to execute the parameterized SQL statements and retrieve appropriate result as per the query sent to the database.

Some of the most common methods are as given below

Method Description

void close()This method frees an object of type  Prepared Statement from database and other JDBC resources.

boolean execute()

This method executes the dynamic query in the object of type Prepared Statement.The getResult() method is used to retrieve the result.

ResultSet executeQuery()

This method is used to execute the dynamic query in the object of type Prepared Statement and returns the object of type ResultSet.

Int executeUpdate() This method executes the SQL statement in

the object of type Prepared Statement. The SQL statement may be a SQL insert, update and delete statement.

ResultSetMetaData getMetaData()

The ResultSetMetaData means a deta about the data of ResultSet.This method retrieves an object of type ResultSetMetaData that contains information about the columns of the ResultSet object that will be return when a query is execute.

int getMaxRows()This method returns the maximum number of rows those are generated by the executeQuery() method.

-

The example program for Prepared Statement interface and its methods are given in next chapter for different databases.