Tuesday, December 28, 2010

Class & Objects.1


About Class & Objects

Class
        A class is a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class.

Objects
        An object is an instance of a class created using a new operator.
The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation.

Declaring a Variable to Refer to an Object
class Point
{
            …………
            …………
}

Point originOne;
 If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):

Instantiating a Class  The new keyword is a Java operator that creates the object. The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like: Point originOne = new Point(23, 94);
 The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:    
int height = new Rectangle().height;
int areaOfRectangle = new Rectangle(100, 50).getArea();
Instance Variables (Non-Static Fields)
          Non-static fields are also known as instance variables because their values are unique to each instance of a class
Class Variables (Static Fields)
          A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated.
Java Output Stmt
          The printing facility is part of the Java standard library: The System class defines a public static field called out. The out object is an instance of the PrintStream class and provides the method println(String) for displaying data to the screen while creating a new line (standard out).
Simple Class program : 
//sample.java                        
//import java.lang.*;
//import java.io.*;
class Sample
{
    public static void main(String args[])
    {
        System.out.println("Hello World.");
        System.out.println(123);
        System.out.println(3.14);
        System.out.println(true);
        System.out.println('A');
        System.out.println("Have a pleasant day.");

        //PrintStream ps = new PrintStream(System.out);
        //ps.println("This is to test.");
    }
}
 Output :
Hello World.
123
3.14
true
A
Have a pleasant day.

 Example2 for class:
/* A program that uses the Vehicle class.
Call this file VehicleDemo.java
*/
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
// This class declares an object of type Vehicle.
class VehicleDemo {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
int range;
// assign values to fields in minivan
minivan.passengers = 7;  //Notice the use of the dot
minivan.fuelcap = 16;      //Notice the use of the dot
minivan.mpg = 21;       //Notice the use of the dot operator to access a member.
// compute the range assuming a full tank of gas
range = minivan.fuelcap * minivan.mpg;
System.out.println("Minivan can carry " + minivan.passengers +" with a range of " + range);
}
}

You should call the file that contains this program VehicleDemo.java because the main( ) method is in the class called VehicleDemo, not the class called Vehicle. When you compile this program, you will find that two .class files have been created, one for Vehicle and one for VehicleDemo. The Java compiler automatically puts each class into its own .class file. It is not necessary for both the Vehicle and the VehicleDemo class to be in the same source file.You could put each class in its own file, called Vehicle.java and VehicleDemo.java, respectively.
To run this program, you must execute VehicleDemo.class. The following output is displayed:
Minivan can carry 7 with a range of 336

 Before moving on, let’s review a fundamental principle: each object has its own copies of the instance variables defined by its class. Thus, the contents of the variables in one object can differ from the contents of the variables in another. There is no connection between the two objects except for the fact that they are both objects of the same type. For example, if you have two Vehicle objects, each has its own copy of passengers, fuelcap, and mpg, and the contents of these can differ between the two objects. The following program demonstrates this fact. (Notice that the class with main( ) is now called TwoVehicles.)
// This program creates two Vehicle objects.
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}
// This class declares an object of type Vehicle.
class TwoVehicles {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
 // assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
// compute the ranges assuming a full tank of gas
range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
System.out.println("Minivan can carry " + minivan.passengers +
" with a range of " + range1);
System.out.println("Sportscar can carry " + sportscar.passengers +
" with a range of " + range2);
}
}

The output produced by this program is shown here: 
Minivan can carry 7 with a range of 336
Sportscar can carry 2 with a range of 168
  As you can see, minivan’s data is completely separate from the data contained in sportscar. The following illustration depicts this situation.



In the preceding programs, the following line was used to declare an object of type Vehicle:
Vehicle minivan = new Vehicle();
This declaration performs two functions. First, it declares a variable called minivan of the class type Vehicle. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, the declaration creates a physical copy of the object and assigns to minivan a reference to that object. This is done by using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in a variable. Thus, in Java, all class objects must be dynamically allocated. The two steps combined in the preceding statement can be rewritten like this to show each step individually:
Vehicle minivan; // declare reference to object
minivan = new Vehicle(); // allocate a Vehicle object
The first line declares minivan as a reference to an object of type Vehicle. Thus, minivan is a variable that can refer to an object, but it is not an object, itself. At this point, minivan contains the value null, which means that it does not refer to an object. The next line creates a new Vehicle object and assigns a reference to it to minivan. Now, minivan is linked with an object.


Reference Variables and Assignment
In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int. When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. When you assign an object reference variable to another, the situation is a bit more complicated because you are changing the object that the reference variable refers to. The effect of this difference can cause some counterintuitive results. For example, consider the following fragment:

Vehicle car1 = new Vehicle();
Vehicle car2 = car1;

At first glance, it is easy to think that car1 and car2 refer to different objects, but this is not the case. Instead, car1 and car2 will both refer to the same object. The assignment of car1 to car2 simply makes car2 refer to the same object as does car1. Thus, the object can be acted upon by either car1 or car2. For example, after the assignment car1.mpg = 26; executes, both of these println( ) statements  
                                 System.out.println(car1.mpg);
                                 System.out.println(car2.mpg);
 
display the same value: 26. Although car1 and car2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to car2 simply changes the object to which car2
refers. For example:    

                               Vehicle car1 = new Vehicle();
                               Vehicle car2 = car1;
                               Vehicle car3 = new Vehicle(); 

                               car2 = car3; // now car2 and car3 refer to the same object.  
After this sequence executes, car2 refers to the same object as car3. The object referred to by car1 is unchanged.


Methods

As explained, instance variables and methods are the constituents of classes. So far, the Vehicle class contains data, but no methods. Although data-only classes are perfectly valid, most classes will have methods. Methods are subroutines that manipulate the data defined by the class and, in many cases, provide access to that data. In most cases, other parts of your program will interact with a class through its methods.
A method contains one or more statements. In well-written Java code, each method performs only one task. Each method has a name, and it is this name that is used to call the method. In general, you can give a method whatever name you please. However, remember that main( ) is reserved for the method that begins execution of your program. Also, don’t use Java’s keywords for method names. When denoting methods in text, this book has used and will continue to use a convention that has become common when writing about Java. A method will have parentheses after its name. For example, if a method’s name is getval, it will be written getval( ) when its name is used in a sentence. This notation will help you distinguish variable names from method names.
The general form of a method is shown here:
ret-type name( parameter-list ) {
// body of method
}
Here, ret-type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. The parameter-list 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, the parameter list will be empty.
Adding a Method to the Vehicle Class 
As just explained, the methods of a class typically manipulate and provide access to the data of the class. With this in mind, recall that main( ) in the preceding examples computed the range of a vehicle by multiplying its fuel consumption rate by its fuel capacity. While technically correct, this is not the best way to handle this computation. The calculation of a vehicle’s range is something that is best handled by the Vehicle class itself. The reason for this conclusion is easy to understand: the range of a vehicle is dependent upon the capacity of the fuel tank and the rate of fuel consumption, and both of these quantities are encapsulated by Vehicle. By adding a method to Vehicle that computes the range, you are enhancing its object-oriented structure.To add a method to Vehicle, specify it within Vehicle’s declaration. For example, the following version of Vehicle contains a method called range( ) that displays the range of the vehicle.
// Add range to Vehicle.
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Display the range.
void range() {
System.out.println("Range is " + fuelcap * mpg);
}
}
class AddMeth {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();

int range1, range2;


// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;


// assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
System.out.print("Minivan can carry " + minivan.passengers +". ");
minivan.range(); // display range of minivan
System.out.print("Sportscar can carry " + sportscar.passengers +". ");
sportscar.range(); // display range of sportscar.
}
}


This program generates the following output:

Minivan can carry 7. Range is 336
Sportscar can carry 2. Range is 168


Let’s look at the key elements of this program, beginning with the range( ) method itself.

The first line of range( ) is
void range() {
The range( ) method is contained within the Vehicle class. Notice that fuelcap and mpg are used directly, without the dot operator. This line declares a method called range that has no parameters. Its return type is void. Thus, range( ) does not return a value to the caller. The line ends with the opening curly brace of the
method body. The body of range( ) consists solely of this line:

System.out.println("Range is " + fuelcap * mpg);

This statement displays the range of the vehicle by multiplying fuelcap by mpg. Since each object of type Vehicle has its own copy of fuelcap and mpg, when range( ) is called, the range computation uses the calling object’s copies of those variables. The range( ) method ends when its closing curly brace is encountered. This causes program control to transfer back to the caller. Next, look closely at this line of code from inside main():
  minivan.range();
This statement invokes the range( ) method on minivan. That is, it calls range( ) relative to the minivan object, using the object’s name followed by the dot operator. When a method iscalled, program control is transferred to the method. When the method terminates, control is transferred back to the caller, and execution resumes with the line of code following the call.In this case, the call to minivan.range( ) displays the range of the vehicle defined by minivan.
In similar fashion, the call to sportscar.range( ) displays the range of the vehicle defined bysportscar. Each time range( ) is invoked, it displays the range for the specified object.There is something very important to notice inside the range( ) method: the instance variablesfuelcap and mpg are referred to directly, without preceding them with an object name or the dot operator. When a method uses an instance variable that is defined by its class, it does sodirectly, without explicit reference to an object and without use of the dotoperator. This iseasy to understand if you think about it. A method is always invoked relative to some object of its class. Once this invocation has occurred, the object is known. Thus, within a method, there is no need to specify the object a second time. This means that fuelcap and mpg inside range( ) implicitly refer to the copies of those variables found in the object that invokes range( ).

Returning from a Method

In general, there are two conditions that cause a method to return—first, as the range( ) method in the preceding example shows, when the method’s closing curly brace is encountered. The second is when a return statement is executed. There are two forms of return—one for use in void methods (those that do not return a value) and one for returning values. The first form is examined here.
         In a void method, you can cause the immediate termination of a method by using this form
of return:  return ;
When this statement executes, program control returns to the caller, skipping any remaining code in the method. For example, consider this method:

void myMeth() {
int i;
for(i=0; i<10; i++) {
if(i == 5) return; // stop at 5
System.out.println();
}
}
Here, the for loop will only run from 0 to 5, because once i equals 5, the method returns. It is permissible to have multiple return statements in a method, especially when there are two or more routes out of it. For example:

void myMeth() {
// ...
if(done) return;
// ...
if(error) return;
}
Here, the method returns if it is done or if an error occurs. Be careful, however, because having too many exit points in a method can destructure your code; so avoid using them casually. A well-designed method has well-defined exit points. To review: a void method can return in one of two ways—its closing curly brace is
reached, or a return statement is executed.

Returning a Value
Although methods with a return type of void are not rare, most methods will return a value. In fact, the ability to return a value is one of the most useful features of a method. You have already seen one example of a return value: when we used the sqrt( ) function to obtain a square root.
         Return values are used for a variety of purposes in programming. In some cases, such as with sqrt( ), the return value contains the outcome of some calculation. In other cases, the return value may simply indicate success or failure. In still others, it may contain a status code. Whatever the purpose, using method return values is an integral part of Java programming. Methods return a value to the calling routine using this form of return: return value; Here, value is the value returned.
You can use a return value to improve the implementation of range( ). Instead of displaying the range, a better approach is to have range( ) compute the range and return this value. Among the advantages to this approach is that you can use the value for other calculations. The following example modifies range( ) to return the range rather than displaying it.

// Use a return value.
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
// Return the range.
int range() {
return mpg * fuelcap;
}
}
class RetMeth {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// assign values to fields in sportscar
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
// get the ranges
range1 = minivan.range();
range2 = sportscar.range();
System.out.println("Minivan can carry " + minivan.passengers +
" with range of " + range1 + " Miles");
System.out.println("Sportscar can carry " + sportscar.passengers +
" with range of " + range2 + " miles");
}
}

The output is shown here:
Minivan can carry 7 with range of 336 Miles
Sportscar can carry 2 with range of 168 miles

In the program, notice that when range( ) is called, it is put on the right side of an assignment statement. On the left is a variable that will receive the value returned by range( ). Thus, after
range1 = minivan.range();
executes, the range of the minivan object is stored in range1. Notice that range( ) now has a return type of int. This means that it will return an integer value to the caller. The return type of a method is important because the type of data returned by a method must be compatible with the return type specified by the method. Thus, if you want a method to return data of type double, its return type must be type double. Although the preceding program is correct, it is not written as efficiently as it could be. Specifically, there is no need for the range1 or range2 variables. A call to range( ) can be used in the println( ) statement directly, as shown here:

System.out.println("Minivan can carry " + minivan.passengers +" with range of " + minivan.range() + " Miles");

In this case, when println( ) is executed, minivan.range( ) is called automatically and its value will be passed to println( ). Furthermore, you can use a call to range( ) whenever the range of a Vehicle object is needed. For example, this statement compares the ranges of two vehicles:
                           if(v1.range() > v2.range()) System.out.println("v1 has greater range");

//passing a reference to a function and returning a reference
import java.lang.*;
class Sample
{
    int num1;
    int num2;

    void set(int num1,int num2)
    {
        this.num1 = num1;
        this.num2 = num2;
    }

    void show()
    {
        System.out.println("num1 : " + num1 + " num2 : " + num2);
    }

    Sample sum(Sample ob2)
    {
        Sample ob3 = new Sample();
        ob3.num1 = num1 + ob2.num1;
        ob3.num2 = num2 + ob2.num2;
        //ob3.num1 = this.num1 + ob2.num1;
        //ob3.num2 = this.num2 + ob2.num2;

        return ob3;
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Sample s1 = new Sample();
        s1.set(10,20);
        s1.show();

        System.out.println("----------------------");

        Sample s2 = new Sample();
        s2.set(100,200);
        s2.show();

        System.out.println("----------------------");

        Sample s3 = s1.sum(s2);
        s3.show();
    }
}

  Output is:

num1 : 10 num2 : 20
----------------------
num1 : 100 num2 : 200
----------------------
num1 : 110 num2 : 220

Method Overloading :

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism.

If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Java's most exciting and useful features. 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 actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. 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. Here is a simple example that illustrates method overloading:

//method overloading
import java.lang.*;

class Sample
{
    void fun(int x,int y)
    {
        System.out.println("2 int args");
    }
  
    void fun(float x)
    {
        System.out.println("1 float args");
    }

    void fun(char x)
    {
        System.out.println("1 char args");
    }

    void fun(double x,double y,double z)
    {
        System.out.println("3 double args");
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Sample s = new Sample();
        s.fun(10,20);                //identity conversion
        s.fun(10.20f);                //identity conversion
        s.fun((float)10.20);        //type casting or down casting or narrowing primitive conversion
        s.fun('A');                    //identity conversion
        s.fun('A','B');                //widening primitive conversion
        s.fun(1.2,3.4,5.6);            //identity conversion
        s.fun(1,2,3);                //widening primitive conversion
        s.fun(70);                    //widening primitive conversion          
        s.fun((char)70);            //type casting
        s.fun('a','b','c');
        s.fun('a',1,2.3);
     //   s.fun(1.2);                    //error
    }
}
  Output is:
2 int args
1 float args
1 float args
1 char args
2 int args
3 double args
3 double args
1 float args
1 char args
3 double args
3 double args

Example 2:

import java.lang.*;
class Student
{
    int sno;
    String sname;

    void setDetails()
    {
        sno = -1111;
        sname = "Not Assigned";
    }

    void setDetails(int sno)
    {
        this.sno = sno;
        sname = "Not Assigned";
    }

    void setDetails(int sno,String sname)
    {
        this.sno = sno;
        this.sname = sname;
    }

    void showDetails()
    {
        System.out.println("sno : " + sno + " sname : " + sname);
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Student st1 = new Student();
        st1.setDetails();
        st1.showDetails();

        System.out.println("------------------------------");

        Student st2 = new Student();
        st2.setDetails(1231);
        st2.showDetails();

        System.out.println("------------------------------");

        Student st3 = new Student();
        st3.setDetails(1232,"Abcd");
        st3.showDetails();
    }
}

Output is:

sno : -1111 sname : Not Assigned
------------------------------
sno : 1231 sname : Not Assigned
------------------------------
sno : 1232 sname : Abcd

Constructor
          All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.
          A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
       You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the super class. In this situation, the compiler will complain if the super class doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit super class, then it has an implicit super class of Object, which does have a no-argument constructor
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.

When you define a class derived from another class, the first line of a constructor must be a call to the constructor of the base class, unless the base class has an accessible constructor that takes no parameters.
Note
          Parameters refer to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

//constructor Ex 1:
import java.lang.*;

class Student
{
    int sno;
    String sname;

    Student()    //non parameterized cons or no arg cons
    {
        sno = 1231;
        sname = "Abcd";
    }

    void showDetails()
    {
        System.out.println("sno : " + sno + " sname : " + sname);
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Student st1 = new Student();
        st1.showDetails();

        System.out.println("-------------------------");

        Student st2 = new Student();
        st2.showDetails();
    }

    Output is:
sno : 1231 sname : Abcd
-------------------------
sno : 1231 sname : Abcd
this keyword:
/*
this
----
    "this" is a keyword that always refers the address
    of the current object.

    in every non static method by default "this" will be
    available.
*/

import java.lang.*;

class Student
{
    int sno;
    String sname;

    void setDetails(int sno,String sname)
    {
        System.out.println("this : " + this);
        this.sno = sno;
        this.sname = sname;
    }

    void showDetails()
    {
        System.out.println("this : " + this);
        System.out.println("sno : " + sno);
        System.out.println("sname : " + sname);
    }
}

class MainClass
{
    public static void main(String args[])
    {
        Student st1 = new Student();
        System.out.println("st1 : " + st1);
        st1.setDetails(1231,"Abcd");
        st1.showDetails();

        System.out.println("--------------------");

        Student st2 = new Student();
        System.out.println("st2 : " + st2);
        st2.setDetails(1232,"Efgh");
        st2.showDetails();
    }
}
      Output is:

st1 : Student@19821f
this : Student@19821f
this : Student@19821f
sno : 1231
sname : Abcd
--------------------
st2 : Student@addbf1
this : Student@addbf1
this : Student@addbf1
sno : 1232
sname : Efgh


//constructor Ex2
//sample.java
import java.lang.*;

class Sample
{
    void fun()            //normal function
    {
        System.out.println("this : " + this);  //hashcode=class_name+@+address
        System.out.println("i'm a normal function.");
    }

    Sample()            //constructor
    {
        System.out.println("this : " + this);   //hashcode=class_name+@+address
        System.out.println("i'm a constructor.");
    }
}

class MainClass
{
    public static void main(String args[])
    {
        new Sample();

        System.out.println("-----------------------");

        Sample s;
        s = new Sample();        //cons called
        System.out.println("s : " + s);  //hashcode=class_name+@+address
        s.fun();                //fun called

        System.out.println("-----------------------");

        new Sample();

        System.out.println("-----------------------");

        new Sample().fun();
    }
}
Output is:
this : Sample@19821f
i'm a constructor.
-----------------------
this : Sample@addbf1
i'm a constructor.
s : Sample@addbf1
this : Sample@addbf1
i'm a normal function.
-----------------------
this : Sample@42e816
i'm a constructor.
-----------------------
this : Sample@9304b1
i'm a constructor.
this : Sample@9304b1
i'm a normal function.

When Are Constructors Called?
In the foregoing discussion of inheritance and class hierarchies, an important question may have occurred to you: When a subclass object is created, whose constructor is executed first, the one in the subclass or the one defined by the superclass? For example, given a subclass called B and a superclass called A, is A’s constructor called before B’s, or vice versa? 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 (parameterless) constructor of each superclass will be executed. The following program
illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Constructing A.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Constructing B.");
}
}
// Create another subclass by extending B.
class C extends B {
C( ) {
System.out.println("Constructing C.");
}
}
class OrderOfConstruction {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Constructing A.
Constructing B.
Constructing C.
As you can see, 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.

Monday, December 20, 2010

Java vs C++(OOP)

The differences between the C++ and Java programming

The differences between the C++ and Java programming languages can be traced to their heritage, as they have different design goals.
  • C++ was designed mainly for systems programming, extending the C programming language. To this procedural programming language designed for efficient execution, C++ has added support for statically-typed object-oriented programming, exception handling, scoped resource management, and generic programming, in particular. It also added a standard library which includes generic containers and algorithms.
  • Java was created initially to support network computing. It relies on a virtual machine to be secure and highly portable. It is bundled with an extensive library designed to provide a complete abstraction of the underlying platform. Java is a statically typed object-oriented language that uses syntax similar to C, but is not compatible with it. It was designed from scratch, with the goal of being easy to use and accessible to a wider audience.
  • C++ is a powerful language designed for system programming. The Java language was designed to be simple and easy to learn with a powerful cross-platform library. The Java standard library is considerably large for a standard library. However, Java does not always provide full access to the features and performance of the platform that the software runs on. The C++ standard libraries are simple and robust providing containers and associative arrays. [3].
The different goals in the development of C++ and Java resulted in different principles and design trade-offs between the languages. The differences are as follows:





C++
Java
Compatible with C source code, except for a few corner cases.
No backward compatibility with any previous language. The syntax is however strongly influenced by C/C++.
Allows direct calls to native system libraries.
Call through the Java Native Interface and recently Java Native Access
Exposes low-level system facilities.
Runs in a protected virtual machine.
Optional automated bounds checking.
Always performs bounds checking.
Supports native unsigned arithmetic.
No native support for unsigned arithmetic.
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available in 3rd-party libraries.[1]
Standardized limits and sizes of all primitive types on all platforms.
Pointers, References, and pass by value are supported
Primitive data types always passed by value. Objects references are passed by value. (comparable to using pointers for all class or struct parameters in C++).[2]
Explicit memory management, though third party frameworks exist to provide garbage collection. Supports destructors
Automatic garbage collection (can be triggered manually). Doesn't have the concept of Destructor and usage of finalize() is not recommended.
Supports class, struct, union and can allocate them on heap or stack
Only supports class and allocates them on heap
Allows explicitly overriding types.
Rigid type safety except for widening conversions. Autoboxing/Unboxing added in Java 1.5
The C++ Standard Library has a much more limited scope and functionality than the Java standard library but includes: Language support, Diagnostics, General Utilities, Strings, Locales, Containers, Algorithms, Iterators, Numerics, Input/Output and Standard C Library. Users must choose from a plethora of (mostly mutually incompatible) third-party libraries for threads, network I/O, GUI, and more functionality than the barebone implementations provided by the C++ Standard Library.
The standard library has grown with each release. By version 1.6 the library included support for locales, logging, containers and iterators, algorithms, GUI programming, graphics, multi-threading, networking, platform security, introspection, dynamic class loading, blocking and non-blocking I/O, and provided interfaces or support classes for XML, XSLT, MIDI, database connectivity, naming services (eg LDAP), cryptography, security services (eg Kerberos), print services, and web services.
Operator overloading for most operators
Meaning of operators is immutable.
Full multiple inheritance, including virtual inheritance.
Single inheritance only from classes, multiple from interfaces.
Compile time Templates
Run time Generics
Function pointers
No function pointer mechanism. Instead idioms like Interfaces, Adapters and Listeners are extensively used. (C# as the Java successor introduces the concept of Delegates
No standard inline documentation mechanism. 3rd party software exists like Doxygen
javadoc standard documentation
const keyword for defining immutable variables and member functions that does not change the object.
final provides a limited version of const, equivalent to type* const pointers for objects and plain const of primitive types only. No const member functions, nor any equivalent to const type* pointers.
Supports the goto statement
Doesn't support goto
Source code can be written to be platform independent (can be compiled for Windows, BSD, Linux, Mac OS X, Solaris etc. without needing modification) and written to take advantage of platform specific features. Is typically compiled into native machine code.
Is compiled into byte code for the JVM. Is dependent on the Java platform but the source code is typically written not to be dependent on operating system specific features.


Language features
 Syntax
  • Java Syntax has a context-free grammar which can be parsed by a simple LALRparser. Parsing C++ is somewhat more complicated; for example, Foo<1>(3); is a sequence of comparisons if Foo is a variable, but it creates an object if Foo is the name of a class template.
  • C++ allows namespace level constants, variables, and functions. All such Java declarations must be inside a class or interface.
  • In C++ declarations, a class name declares an object of that class as a value (a.k.a. value semantics). There is no way to do this in Java. Objects are not values in Java. In Java declarations, a class name declares a reference to an object of that class (a.k.a. reference semantics). The equivalent way to do this in C++ is to use "*" to declare a pointer.
  • In C++, the operator "." takes an object as the left operand and accesses a member of the object. Since objects cannot be values in Java, and all objects are accessed through references, this cannot be done in Java. In Java, the "." operator takes a reference to an object as the left operand and access a member of that object. The equivalent operator in C++ is "->".

C++
Java
class Foo          // Declares class Foo
{
public:
    int x;         // Member variable

    Foo(): x(0)    // Constructor for Foo,
    {              //  initializes x
    }

    int bar(int i) // Member function bar()
    {
        return 3*i + x;
    }
};
class Foo                 // Defines class Foo
{
    public int x = 0;     // Member variable,
                          //  with initializer

    public Foo()          // Constructor for Foo
    {
    }

    public int bar(int i) // Member method bar()
    {
        return 3*i + x;
    }
}
Foo a; // declares a to be a Foo object value,
       // initialized using the default constructor
       // If you wanted to use another constructor,
       // you would declare it as "Foo a(args);"
Foo a; // declares a to be a reference/pointer to a Foo object
Foo b = a; // copies the contents of a to a new Foo object b
// OR
// Foo b(a)
Foo b = a.clone(); // copies the values of all members
                   // of this instance if, and only if,
                   // Foo implements a public method called
                   // clone() which returns a new copy of the object
a.x = 5; // modifies a
a.x = 5; // modifies the object a points to
cout << b.x << endl; // outputs 0, because b is a different
                     // object than a
System.out.println(b.x); // outputs 0, because b points to a different
                         // object than a
Foo *c; // declares c to be a pointer to a Foo object (initially
        // undefined; could point anywhere)
Foo c; // declares c to be a reference to a Foo object (initially
       // null if c is a class member; you are required to
       // initialize c before use if it is a local variable)
c = new Foo(); // binds c to reference a new Foo object
c = new Foo(); // binds c to reference a new Foo object
Foo *d = c; // binds d to reference the same object as c
Foo d = c; // binds d to reference the same object as c
c->x = 5; // modifies the object referenced by c
c.x = 5; // modifies the object referenced by c
a.bar(5);  // invokes Foo::bar() for a
c->bar(5); // invokes Foo::bar() for *c
a.bar(5); // invokes Foo.bar() for a
c.bar(5); // invokes Foo.bar() for c
cout << d->x << endl; // outputs 5, because d references the
                      // same object as c
System.out.println(d.x); // outputs 5, because d references
                         // the same object as c

  • In C++ it is possible to declare a pointer to a const type, that is, you cannot modify the object pointed to by the pointer using that pointer. Functions and methods can also guarantee that they will not modify the object pointed to by a pointer by using the "const" keyword. This enforces const-correctness. This is not possible in Java. You can declare a reference "final" in Java (like declaring a pointer "const" in C++), but this just prevents you from re-binding that reference; you can still modify the object referenced by the reference.

C++
Java
const Foo *a; // you cannot modify the object
              //pointed to by a through a
private final Foo a;//Use getA() instead of a
public Foo getA(){
   return a.clone()
}
a = new Foo();
a=new Foo();//Only in constructor
a->x = 5; // ILLEGAL
getA().x=5; //Only modifies a clone of a's x, not a.x
Foo *const b = new Foo(); // you can declare a "const" pointer
final Foo b = new Foo(); // you can declare a "final" reference
b = new Foo(); //ILLEGAL, you can't re-bind it
b = new Foo(); // ILLEGAL, you can't re-bind it
b->x = 5; // LEGAL, you can still modify the object
b.x = 5; // LEGAL, you can still modify the object

  • C++ supports goto statements; Java enforces structured control flow, and relies on labelled break and labelled continue statements to provide some goto-like functionality. Some commenters point out that these labelled flow control statements break the single point-of-exit property of structured programming.
  • C++ provides low-level features which Java lacks. In C++, pointers can be used to manipulate specific memory locations, a task necessary for writing low-level operating system components. Similarly, many C++ compilers support inline assembler. In Java, such code has to reside in external libraries, and can only be accessed through the Java Native Interface with a significant overhead for each call.
 Semantics
  • C++ allows default values for arguments of a function/method, Java does not. However, method overloading can be used to obtain similar results in Java.
  • The minimal compilation unit in C++ is a file. Hence a member function can be compiled separately by creating it in a separate file and adding it to the binary. This helps to reduce the number of lines in a single file. Also two different developers can work on the same class on different methods by defining them on separate files. This can sometimes reduce the configuration management effort, by avoiding the additional merging that would be necessary with Java since it requires all the methods of a class in a single file.
  • C++ allows a range of implicit conversions between native types, and also allows the programmer to define implicit conversions involving user-defined types. In Java, only widening conversions between native types are implicit; other conversions require explicit cast syntax.
    • A consequence of this is that although loop conditions (if, while and the exit condition in for) in Java and C++ both expect a boolean expression, code such as if(a = 5) will cause a compile error in Java because there is no implicit narrowing conversion from int to boolean. This is handy if the code was a typo for if(a == 5). Yet current C++ compilers usually generate a warning when such an assignment is performed within a conditional expression.
  • For passing parameters to functions, C++ supports both pass-by-reference and pass-by-value. In Java, parameters are always passed by value [5]. However, in Java all non-primitive values are references to objects (in C++ terms, they are (smart)-pointers). Objects are not values in Java and only their references can be manipulated; C++ developers who are used to having objects as values may confuse this with pass-by-reference.
  • Java built-in types are of a specified size and range defined by the virtual machine; In C++, a minimal range of values is defined for built-in types, but the exact representation (number of bits) can be mapped to whatever native types are supported on a given platform.
    • For instance, Java characters are 16-bit Unicode characters, and strings are composed of a sequence of such characters. C++ offers both narrow and wide characters, but the actual size of each is platform dependent, as is the character set used. Strings can be formed from either type.
  • The rounding and precision of floating point values and operations in C++ is platform dependent. Java provides an optional strict floating-point model that guarantees consistent results across platforms, though possibly at the cost of slower run-time performance.
  • In C++, pointers can be manipulated directly as memory address values. Java does not have pointers — it only has object references and array references, neither of which allow direct access to memory addresses. In C++ one can construct pointers to pointers, while Java references only access objects.
  • In C++ pointers can point to functions or methods (function pointers or functors). The equivalent mechanism in Java uses object or interface references.
  • Through the use of stack-allocated objects, C++ supports scoped resource management, a technique used to automatically manage memory and other system resources that supports deterministic object destruction. Yet, scoped resource management in C++ cannot be guaranteed; it is only a design pattern, and hence relies on programmers' adherence. Java supports automatic memory management using garbage collection, but other system resources (windows, communication ports, threads) often have to be explicitly released if the garbage collector can not determine they are no longer used.
  • C++ features programmer-defined operator overloading which is not supported in Java. The only overloaded operators in Java are the "+" and "+=" operators, which concatenate strings as well as performing addition.
  • Java features standard API support for reflection and dynamic loading of arbitrary new code.
  • C++ supports static and dynamic linking of binary to manage the space required for binary and performance.
  • Java has generics, whose main purpose is to provide type-safe containers. C++ has templates, which provide more extensive support for generic programming.
  • Both Java and C++ distinguish between native types (these are also known as "fundamental" or "built-in" types) and user-defined types (these are also known as "compound" types). In Java, native types have value semantics only, and compound types have reference semantics only. In C++ all types have value semantics, but a reference can be created to any type, which will allow the object to be manipulated via reference semantics.
  • C++ supports multiple inheritance of arbitrary classes. In Java a class can derive from only one class, but a class can implement multiple interfaces (in other words, it supports multiple inheritance of types, but only single inheritance of implementation).
  • Java explicitly distinguishes between interfaces and classes. In C++ multiple inheritance and pure virtual functions make it possible to define classes that function almost like Java interfaces do, with a few small differences.
  • Java has both language and standard library support for multi-threading. The synchronized keyword in Java provides simple and secure mutex locks to support multi-threaded applications, though synchronized sections have to be left in LIFO order. Java also provides robust and complex libraries for more advanced multi-threading synchronization. In C++ there is currently no defined memory model for multi-threading; however, third party libraries provide support roughly equivalent to that of Java; obvious difference being the non-uniformity of these C++ libraries.
  • C++ methods can be declared as virtual functions, which means the method to be called is determined by the run-time type of the object. By default, methods in C++ are not virtual. In Java, methods are virtual default, but can be made non-virtual by using the final keyword.
  • C++ enumerations are primitive types and support conversion to and comparison with other integer types. Java enumerations are actually instances of a class (they extend java.lang.Enum<E>) and may therefore define constructors, fields, and methods as any other class.
 Resource management
  • Java offers automatic garbage collection. Memory management in C++ is usually done through constructors, destructors, and smart pointers - notably those in Common Language Runtime - CLR. The C++ standard permits garbage collection, but does not require it; garbage collection is rarely used in practice. The enforced use of automatic garbage collection means that writing real-time software can be difficult in Java.
  • C++ can allocate arbitrary blocks of memory. Java only allocates memory through object instantiation. (Note that in Java, the programmer can simulate allocation of arbitrary memory blocks by creating an array of bytes. Still, Java arrays are objects.)
  • Java and C++ use different idioms for resource management. Java relies mainly on garbage collection, which can only reclaim memory and may be a last shot at other resources, while C++ relies mainly on the RAII (Resource Acquisition Is Initialization) idiom. This is reflected in several differences between the two languages:
    • In C++ it is common to allocate objects of compound types as local stack-bound variables which are destroyed when they go out of scope. In Java compound types are always allocated on the heap and collected by the garbage collector (except in virtual machines that use escape analysis to convert heap allocations to stack allocations).
    • C++ has destructors, while Java has finalizers. Both are invoked prior to an object's deallocation, but they differ significantly. A C++ object's destructor must be implicitly (in the case of stack-bound variables) or explicitly invoked to deallocate the object. The destructor executes synchronously just prior to the point in the program at which the object is deallocated. Synchronous, coordinated uninitialization and deallocation in C++ thus satisfy the RAII idiom. In Java, object deallocation is implicitly handled by the garbage collector. A Java object's finalizer is invoked asynchronously some time after it has been accessed for the last time and before it is actually deallocated, which may never happen. Very few objects require finalizers; a finalizer is only required by objects that must guarantee some clean up of the object state prior to deallocation — typically releasing resources external to the JVM. In Java safe synchronous deallocation of resources has to be performed explicitly using the try/finally construct.
    • In C++ it is possible to have a dangling pointer – a stale reference to an object that has already been deallocated; attempting to use a dangling pointer typically results in program failure. In Java, the garbage collector won't destroy a referenced object.
    • In C++ it is possible to have uninitialized primitive objects, Java enforces default initialization.
    • In C++ it is possible to have an object that is allocated, but has no reachable reference to it. Such an unreachable object cannot be destroyed (deallocated), and results in a memory leak. In contrast, in Java an object will not be deallocated by the garbage collector until it becomes unreachable (by the user program). (Note: weak references are supported, which work with the Java garbage collector to allow for different strengths of reachability.) Garbage collection in Java prevents many memory leaks, but leaks are still possible under some circumstances.[6]
    • Java is more prone to leaking non-memory resources, while idiomatic C++ makes that much harder.
Libraries
  • provides cross-platform access to many features typically available in platform-specific libraries. Direct access from Java to native operating system and hardware functions requires the use of the Java Native Interface.
Runtime
  • Due to its unconstrained expressiveness, low level C++ language features (e.g. unchecked array access, raw pointers, type punning) cannot be reliably checked at compile-time or without overhead at run-time. Related programming errors can lead to low-level buffer overflows and segmentation faults. The Standard Template Library provides higher-level abstractions (like vector, list and map) to help avoid such errors. In Java, low level errors either cannot occur or are detected by the JVM and reported to the application in the form of an exception.
  • The Java language requires specific behavior in the case of an out-of-bounds array access, which generally requires bounds checking of array accesses. This eliminates a possible source of instability but usually at the cost of slowing down execution. In some cases, compiler analysis can prove a bounds check unnecessary and eliminate it. C++ has no required behavior for out-of-bounds access of native arrays, thus requiring no bounds checking for native arrays. C++ standard library collections like std::vector, however, offer optional bounds checking. In summary, Java arrays are "always safe; severely constrained; always have overhead" while C++ native arrays "have optional overhead; are completely unconstrained; are potentially unsafe."
  • C ++ is normally compiled directly to machine code which is then executed directly by the operating system. Java is normally compiled to byte-code which the Java virtual machine (JVM) then either interprets or JIT compiles to machine code and then executes.
  Templates vs. Generics                         
Both C++ and Java provide facilities for generic programming, templates and generics, respectively. Although they were created to solve similar kinds of problems, and have similar syntax, they are actually quite different.

C++ Templates
Java Generics
Classes and functions can be templated.
Classes and methods can be genericized.
Parameters can be any type or integral value.
Parameters can only be reference types (not primitive types).
Separate copies of the class or function are likely to be generated for each type parameter when compiled.
One version of the class or function is compiled, works for all type parameters.
Objects of a class with different type parameters are different types at run time.
Type parameters are erased when compiled; objects of a class with different type parameters are the same type at run time.
Implementation source code of the templated class or function must be included in order to use it (declaration insufficient).
Signature of the class or function from a compiled class file is sufficient to use it.
Templates can be specialized -- a separate implementation could be provided for a particular template parameter.
Generics cannot be specialized.
Template parameters can have default arguments (only for template classes, not functions).
Generic type parameters cannot have default arguments.
Does not support wildcards. Instead, return types are often available as nested typedefs.
Supports wildcard as type parameter if it is only used once.
Does not directly support bounding of type parameters, but metaprogramming provides this
Supports bounding of type parameters with "extends" and "super" for upper and lower bounds, respectively; allows enforcement of relationships between type parameters.
Allows instantiation of class of type parameter type.
Does not allow instantiation of class of type parameter type.
Type parameter of templated class can be used for static methods and variables.
Type parameter of templated class cannot be used for static methods and variables.
Static variables are not shared between classes of different type parameters.
Static variables are shared between instances of a classes of different type parameters.
Templated classes and functions do not enforce type relations for type parameters in their declaration. Use of a wrong type parameter results in the template code "not working", usually generating an error message at a place in the template code where an operation is not allowed for that type and not in the user's code. Proper use of templated classes and functions is dependent on proper documentation. Again, metaprogramming can provide all that Java does and more, but is intimidating.
Generic classes and functions can enforce type relationships for type parameters in their declaration. Use of a wrong type parameter results in a type error at the code that uses it. Operations on parametrized types in generic code are only allowed in ways that can be guaranteed to be safe by the declaration. This results in greater type safety but lesser flexibility.
Generics are not Turing-complete.

Miscellaneous
  • Java and C++ use different techniques for splitting up code in multiple source files. Java uses a package system that dictates the file name and path for all program definitions. In Java, the compiler imports the executable class files. C++ uses a header file source code inclusion system for sharing declarations between source files. (See Comparison of imports and includes.)
  • Compiled Java code files are generally smaller than code files in C++ as Java bytecode is usually more compact than native machine code[citation needed] and Java programs are never statically linked.
  • C++ compilation features an additional textual preprocessing phase, while Java does not. Thus some users add a preprocessing phase to their build process for better support of conditional compilation.
  • In both languages, arrays have a fixed size. In Java, arrays are first-class objects, while in C++ they are merely a continuous run of their base objects, often referred to using a pointer to their first element and an optional length. In Java, arrays are bounds-checked and know their length, while in C++ you can treat any subsequence as an array in its own right. Both C++ and Java provide container classes (std::vector and java.util.ArrayList respectively) which are resizable and store their size.
  • Java's division and modulus operators are well defined to truncate to zero. C++ does not specify whether or not these operators truncate to zero or "truncate to -infinity". -3/2 will always be -1 in Java, but a C++ compiler may return either -1 or -2, depending on the platform. C99 defines division in the same fashion as Java. Both languages guarantee (where a and b are integer types) that (a/b)*b + (a%b) == a for all a and b (b != 0). The C++ version will sometimes be faster, as it is allowed to pick whichever truncation mode is native to the processor.
  • The sizes of integer types is defined in Java (int is 32-bit, long is 64-bit), while in C++ the size of integers and pointers is compiler and ABI dependent within given constraints. Thus, carefully-written C++ code can take advantage of the 64-bit processor's capabilities while still functioning properly on 32-bit processors. However, care must be taken to write the C++ program in a portable manner. In contrast, Java's fixed integer sizes mean that programmer error in this regard shouldn't be possible. This may incur a performance penalty since Java code cannot run using an arbitrary processor's word size.
Performance
In addition to running a compiled Java program, computers running Java applications must also run the Java Virtual Machine JVM, while compiled C++ programs can be run without external applications. Early versions of Java were significantly outperformed by statically compiled languages such as C++. This is because the program statements of these two closely related languages may compile to a few machine instructions with C++, while compiling into several byte codes involving several machine instructions each when interpreted by a JVM. For example:

Java/C++ statement
C++ generated code (x86)
Java generated byte code
vector[i]++;
mov edx,[ebp+4h]
mov eax,[ebp+1Ch]
inc dword ptr [edx+eax*4]
aload_1
iload_2
dup2
iaload
iconst_1
iadd
iastore

While this may still be the case for embedded systems because of the requirement for a small footprint, it is frequently argued that advances in just in time (JIT) compiler technology for long-running server and desktop Java processes will close the performance gap.
Several studies of mostly numerical benchmarks argue that Java could potentially be faster than C++ in some circumstances, for a variety of reasons:
  • Pointers make optimization difficult since they may point to arbitrary data, though many C++ compilers provide the C99 keyword restrict which corrects this problem.
  • Compared to C++ implementations which make unrestrained use of standard implementations of malloc/new for memory allocation, implementations of Java garbage collection may have better cache coherence as its allocations are generally made sequentially.
  • Run-time compilation can potentially use additional information available at run-time to optimise code more effectively, such as knowing what processor the code will be executed on.
Static compilers can be given hints, using command-line switches or pragmas, regarding the processor and other optimization options, but these choices may be wrong for where and when the code is actually run. Just-in-time compilation, used in recent Java virtual machines, allows optimization using current run-time measurements. This adds an additional runtime overhead as code is optimised, but is theoretically capable of increasing performance in processes that run for a very long time.
One comprehensive study of microbenchmarks shows quite a large variation in results but indicates that Java often outperforms C++ in operations such as heap allocation and file I/O while C++ often outperforms Java in arithmetic and trigonometric operations. For numerical processing, Java has shown significant gains with each new version but still lags C++ and Fortran. The requirement for reproducibility of floating-point results across all platforms can be enforced with the strictfp keyword in Java. However, other authors note that when benchmarks are tweaked to be algorithmically comparable, overall C++ runs about twice as fast as Java.
Because Java always passes references to objects instead of objects themselves, passing arguments to functions is always an efficient operation, similar to passing a pointer or passing an object by reference in C++. In contrast, C++ allows passing objects by value to functions, which can cause significant overhead in the case that much memory must be copied or inefficient copy constructors must be called.
Setting aside the compilation discussion, the same algorithm in C++ and Java can have a huge difference in performance due the number of object copies performed. On most cases, though, there are other solutions (like using StringStream rather than String for mutable strings), but that often makes the code more bloated, obscured and increases the creation of temporary objects, increasing memory footprint and impacting in speed.


 why pointer concept not use in java?

The Java language does _not_ provide pointers.  Instead, all objects are handled by references, not to be confused with pointers or C++ references.  The difference is that Java references do not refer directly to the memory location, but rather contain the pointer to the actual memory location, which the programmer cannot get direct access to.  This extra level of indirection is required for GC to work.  When GC kicks in and frees objects, that are no longer in use, it then does heap compaction to defragment the heap.  To do this, some objects must be moved around in memory.  This is possible because there is only one place where this pointer is located, in the reference, and thus the memory can be relocated, old location freed, and pointer changed.  In C++ this is not possible because pointers are copied all over the code.
         It is also true that pointers are dangerous and lead to memory leaks, memory corruption, invalid memory access, e.g. from uninitialized and improperly initialized variables, indexing out of bounds, and many bugs due to pointer arithmetic.  References, and other features related to these, avoid all these problems.