Unit 6 & 7 java programming

3rd Semester

Class and object

A class is a user defined data type which binds data and function into a single unit and objects are the instance of a class.
A class is declared by use of the class keyword. The general form of a class definition is shown here:

class classname
{
type instance-variable1;
type instance-variable2;
type instance-variablen;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of methodTHE JAVA LANGUAGE
}
type methodnamen(parameter-list)
{
// body of method
}
}

The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

WAP to calculate volume of a box with its width, height and depth given.





 

class Box
{
double width;
double height;
double depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box(); //create an object mybox1 and allocates memory
Box mybox2 = new Box(); //create an object mybox2 and allocates memory
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}

Output:
Volume is 3000.0
Volume is 162.0
The new operator dynamically allocates memory for an object. It has this general form:
class-var = new classname( );
Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created.
Thus the statement:
Box mybox1 = new Box(); create an object mybox1 and allocate memory to it.
The above statement can be written in two steps:
Box mybox1; // declare reference to object
mybox1 = new Box(); // allocate memory to a Box object





Constructor

 A constructor is a special member function having name same as class name.
 The constructor is automatically called immediately after the object is created, before the new
operator completes.
 Constructors look a little strange because they have no return type, not even void.
 Its purpose is to initialize the object of a class.





 It is of three types:

  • Default Constructor: Constructor which takes no argument(s) is called Default Constructor.
  • Parameterized constructor: Constructor which takes argument(s) is called parameterized Constructor.
  • Copy Constructor: Constructor which takes object as its argument is called copy
    constructor.

 When a single program contains more than one constructor, then the constructor is said to be overloaded.





WAP to illustrate constructor overloading in java.

class Box
{
double width;
double height;
double depth;
Box(double w, double h, double d) // Parameterized Constructor
{
width = w;
height = h;
depth = d;
}
Box() // Default Constructor
{
width = -1;
height = -1;
depth = -1;
}
Box(double len) // Parameterized Constructor
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class Overload
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}




Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

The this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this can be used inside any method to refer to the current object. It always points to the object through which a method is called. We can use this anywhere a reference to an object of the current class’ type is permitted.
To better understand what this refers to, consider the following version of Box ( ):
// A redundant use of this.

Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}

This version of Box ( ) operates exactly like the earlier version. The use of this is redundant, but perfectly correct. Inside Box ( ), this will always refer to the invoking object.





The static Keyword

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. We 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 objects exist.

WAP to demonstrate use of static variables and methods.

class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}
Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12




As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12. Then main( )is called, which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.
Note: It is illegal to refer to any instance variables inside of a static method.





 

The final Keyword

A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. (In this usage, final is similar to const in C/C++/C#.)
For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is
essentially a constant.
The keyword final can also be applied to methods (will be discussed in inheritance), but its meaning is
substantially different than when it is applied to variables.

Garbage Collection

Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation.

  •  In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation automatically.The technique that accomplishes this is called garbage collection.
  •  It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
  •  There is no explicit need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or more objects exist that are no longer used

The finalize () method

  •  Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization.
  •  By using finalization, we can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.
  •  To add a finalizer to a class, we simply define the finalize ( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize ( ) method you will specify those actions that must be performed before an object is destroyed.
    The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed,the Java run time calls the finalize ( ) method on the object.




The finalize ( ) method has this general form:

protected void finalize( )
{
// finalization code here
}

Short Type Questions
1. Why java does not provide any destructor?
2. Why java characters takes 2 byte unlike c/c++, which takes 1 byte of memory.
3. Define Constructor.
4. Define class. How memory is allocated dynamically to an object of a class?
5. What is the meaning of the statement: final int var=10;
6. Define a static method.





Long Type Questions
1. Write a program that gives the output: “Welcome to the World of Java”.
2. Write two explicit constructors for a class to calculate the area of rectangle. When a single value is
passed to the constructor, it should assume that the width and height is the same as the passed
variable. It should calculate the area accordingly. When two values are passed to the constructor, it
should calculate the area.
3. Write a program that does the following:

  •  Declare s and initializes variables m and n to 100 and 200 respectively.
  •  Under the condition, if m equals 0, it displays the appropriate result.
  •  If m is greater than n, it displays the appropriate result.
  •  Check whether the value of n is even or odd.

4. Write a program that displays the total no of multiples of 7 between 1 and 100.
5. Write short notes on following:

  •  Static
  •  Final
  •  Garbage Collection
  •  Constructor

6. What is constructor overloading? Discuss with an example.
7.Write a java program to display all the prime factors of 9999.
8. Write a java program to find sum of all even factors of 5000.
9. Write a java program to find 1+2+3+………..50.
10. Write java program to display following Pattern:
*
***
*****
*******