Vous êtes sur la page 1sur 24

1

1)Describe the java garbage collection mechanism?

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. The
technique that accomplishes this is called garbage collection. It works like this when no reference
to an object exist , that object is assumed to be no longer needed, and the memory occupied by
the object can be reclaimed.

Finalize () method:
The garbage collector of an object called this method when the garbage collection
determines that those are no more references to the object. It is also placed some actions inside the
finalized method. The following points are related to finalize () method.
1. Every class has object class as a super class.
2. Every class in java can have a finalize () method that returns resources to the system.
3. A class should have only one finalize () method that takes no argument . method finalize
is originally defined in class object.

The finalize () method has the following syntax:


protected void finalize()
{
//finalization code
}

Example:

class Garbage extends Object


{
int x,y;
void setdata(int a,int b)
{
X=a;
Y=b;

}
void printdata()
{
System.out.println(“x=”+x+ “ y=”+y);

}
protected void finalize()
{
System.out.println(“finalizer”);
}
}
2

Class Mg
{
public static void main(String args[])
{
Garbage obj=new Garbage();
Garbage obj1=new Garbage();
obj.setdata(10,20);
obj1.printdata();
obj1=null;
System.gc();//method to call garbage collector
//obj1.setdata(2,3);//error
Obj.printdata();
}
}
Output:
X=10 y=20
Finalizer
X=10 y=20
2) Write a java program using command-Line argument and explain?
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 string in a String array passed to the args parameter of main(). The
first command-Line argument is stored at args[0],the second at args[1],and so on.
Ex:
//Display all command-line arguments.
class CommandLine{
public static void main(String args[])
{

For(int i=0;i<args.lenth ;i++)


System.out.println(“args[“+i+”]:”+args[i]);

}
}

Executing this program


Java CommandLine this is a test 100 -1
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

3) With an example explain java recursion mechanism ?


3

Java supports recursion. Recursion the process of defining something in terms of itself. It relates
the java programming ,recursion is the attribute that allows a method to call itself. A method call
itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The factorial of a
number N is the product of all the whole numbers between 1 and N. for example , 3 factorial is
1*2*3 ,or 6 .
Example:
// A simple example of recursion .
class Factorial
{
//this is the recursive method

int fact(int n)
{
int result;
if (n==1)
return 1;
result=fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[])
{
Factorial f=new Factorial();
System.out.println(“factorial of 3 is”+f.fact(3));
System.out.println(“factorial of 4 is”+f.fact(4));
System.out.println(“factorial of 5 is”+f.fact(5));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24

Factorial of 5 is
4) What is constructor ?Describe its special properties?
A constructor is a special method of class. which is invoked automatically , whenever an object of
a class is created. It has the same name as its class and resides similar to a method. A constructor
has the following characteristics.
 It doesn’t have any return type not even void.
 It can be overloaded.
 It is automatically used to initialize the member of the object.
Different types of Constructors:
4

1)Default Constructor: A constructor that accepts no parameters is called the default constructor.
If no constructors are defined for a class. The java system automatically generates the default
constructor.
Example:
class Time1
{
int hour,min,sec;
public Time1()
{
hour=10;
min=45;
sec=23;

}
Void printdata()
{
System.out.println(hours+”hours:” ”+min+”minutes:”+sec+”seconds”);
}
}

class const1
{
public static void main(String args[])
{
Time1 t=new Time1();
t.printdata();
}
}

Output: 10 hours:45minutes:23seconds.

2) Parameterized Constructor: A constructor that takes arguments as parameter is called


parameterized constructor. If any constructor are defined by a class with the parameters, java will
not create a default constructor for the class.

Example:

class Time1
{

int hour,min,sec;
public Time1(int h,int m,int s)
{
hour=h;
5

min=m;
sec=s;

}
Void printdata()
{
System.out.println(hours+”hours:” ”+min+”minutes:”+sec+”seconds”);
}
}

class const2
{
public static void main(String args[])
{
Time1 t=new Time1(10,9,4);
t.printdata();
}
}

5) Explain with a java program about reference variable?

Class box Boxobject


{
Width
double width; b1
double height;
Height
double depth;
}
b2 Depth
class demo
{
public static void main(String args[])
{
box b1=new box();
box b2=b1;
b2.width=100;
b2.height=50;
b2.depth=200;
double v=b1.width * b1.height*b1.depth;
System.out.println(“volume of box is”+v);

}
}
6

Here if b1 has been set to null,but b2 still points to the original object.

Note: when we assign our object reference variable to another object reference variable we are not
creating a copy of the object , we are only making a copy of the reference.

6) Explain about this keyword?

Java define “this” keyword , that can be used inside any method to refer the current object. “this “
always a reference to the object on which method was invoked .”this” reference is implicitly used
to refer to both the instance variables and method of current object.

Example:

class box
{
double width;
double height;
double depth;

box(double width, double height, double depth)


{
this.width=width;
this.height=height;
this.depth=depth;
}
double volume()
{
return (width*height*depth)

}
}
class boxdemo
{
public static void mian(String args[])
{
box b= new box( 10,20,15);
System.out.println(“volume is :”+ b.volume());

}
}

String handling methods():


1)int length(): it returns the number of characters in a given string .
7

2)char charAt(int where):it returns the character at the specified location. “where” must be a
nonnegative specified location within the string. The first element of string is considered to be at
position “zero”.
3)boolean equals(): It compares the two strings and returns true if the strings contain the same
characters in the same order ,and false otherwise . The comparison is case-sensitive.
Syntax: boolean equals(Object string);
4)boolean equalsIgnoreCase(): it compares the two strings and returns true if the strings contain
the same characters in the same order, and false otherwise by ignoring the case characters.
Syntax:boolean equalsIgnoreCase(String str);
5)int compareTo(String str): it returns ‘0’ if the two strings are equal. ‘Negative number’ if the
invoking string is less than str and ‘positive number’ if the invoking string is greater than is passed
as an argument. The comparision is case-sensitive

6)int indexOf(String str): it search for the first occurrence of a character. If the character is
found the index of that characters in the string is returned. Otherwise , it returns ‘-1’.
7)int indexOf(String ch,int startIndex): it searches the occurrence of character from the
startIndex argument.
8)int lastIndexOf(String ch): it searches the last occurrence of the character. The search is
performed from the end of the string towards the beginning of the string. If the character is found
the index of that character in the string is return. Otherwise ,it returns ‘-1’.
9)String substring(int startIndex): it returns a copy of the sub string that begins that startIndex
and return to the end of the invoking string.
10)String substring(int startIndex, int endIndex): It returns all the characters from the
beginning index upto but not including the ending index.
11)boolean startsWith(String str):
boolean endsWith(String str): The startWith() method determines whether a given string
begins with a specified string or not. Conversely , ends With() method determines whether Sting
ends with a specified string or not.
12)String toLowerCase(): it converts all uppercase characters into lowercase character of a string.
String toUpperCase(): it converts all lowercase characters into uppercase character of a string.

Example on String Handling Functions:


class ChangeCaseDemo
{
public static void main(String args[])
{
String s=”This is Sit”;
System.out.println(“Original:”+s);
String upper=s.toUpperCase();
String lower=s.toLowerCase();
System.out.println(“UpperCase:”+upper);
System.out.println(“lowerCase:”+lower);
System.out.println(“the length of the String is %d:”+s.length());

}}
8

UNIT-111
INHERITANCE
The Benefits of Inheritance:
• Software Reusability
• Increased Reliability
• Code sharing
• Consistency of Interface
• Software Components
• Rapid Prototyping
• Polymorphism and frameworks.
• Information hiding

Software Reusability: When behavior is inherited from another class, the code that provides
that behavior does not have to be rewritten. This may seem obvious, but the implications are
important. Many programs send much of their time rewriting code they have written many times
before-for example , to search for a pattern in string or to insert a new element into a table. With
object –oriented technique , these functions can be written once and reused.

Increased Reliability: code that is executed infrequently . when the same components are used in
two or more applications , the code will be exercised more than code that is developed for a single
application. Thus , bugs in such code tend to be discovered more quickly , and latter applications
gain the benefit of using components that are more error free . Similarly the costs of maintenance
of shared components can be split among many projects.
Code sharing: Code sharing can occur on several levels with object-oriented techniques. On
one level , many users or projects can use the same classes. (Brad Cox [1986] calls these software
–Ics, in analogy to the integrated circuits used in hardware design.) Another form of sharing occurs
when two or more classes developed by a single programmer as part of a project inherit from a
single parent class. For example , a set and an Array may both be considered a form of
Collection . When this happens , two or more types of objects will share the code that they
inherit . This code needs to be written only once and will contribute only once to the size of the
resulting program.
Consistency of Interface: when two or more classes inherit from the same super class , we are
assured that the behavior they inherit will be the same in all cases. Thus it is easier to guarantee
that interfaces to similar objects are in fact similar and that the user if not presented with a
confusing collection of objects that are almost the same but behave , and are interacted with very
differently.
Software Components: Inheritance enables programmers to construct reusable software
components . the goal is to permit the development of new and novel applications that
nevertheless require little or no actual coding. The java library offers a rich collection of software
components for use in the development of application.

Rapid Prototyping: When a software system is constructed largely out of reusable components ,
developers can concentrate their time on understanding the new and unusual portion of the
system . Thus, software system can be generated more quickly and easily , leading to style of
9

programming known as rapid prototyping or exploratory programming. A prototyping system is


developed , user experiment with it , a second system is produced that is based on experience with
the first, further experimentation takes place , and so on for several iterations. Such programming
is particularly useful in situation where the goals and requirements of the system are only vaguey
understood when the project begins.

Polymorphism and frameworks: Software produced conventionally is generally written from the
bottom up, although it may be designed from the top down . that is , the lower-level routines are
written and on top of these , slightly higher abstractions are produced , and on top of these even
more abstract elements are generated .
Normally , code portability decreases as one moves up the levels of abstraction . that is the lower-
level routines may be used in several different projects , and perhaps even the next level of
abstraction may be reused.
Polymorphism in programming languages permits the programmer to generates high-level reusable
components that can be tailored to fit different applications by changes in their low-level
Parts.
Information hiding: A programmer who reuses a software component needs only to understand
the nature of the component and its interface . It is not necessary for the programmer to have
detailed information concerning matters such as the techniques used to implement the component.
Thus the interconnectedness between software system is reduced.

THE COSTS OF INHERITANCE

• Execution speed
• Program Size
• Message-Passing overhead
• Program Complexity

Execution speed: It is seldom possible for general purpose software tools to be as fast as
carefully handcrafted systems. Thus, inherited methods, which must deal with arbitrary subclasses,
are often slower than specialized code. The difference in speed or complexity is often small. The
reduction in execution speed may be balanced by an increase in the speed of software
development.
Program Size: The use of any software library frequently imposes a size penalty not imposed by
systems constructed for a specific project. Although this expense may be substantial, as memory
costs decrease , the size of programs becomes less important . Containing development costs and
producing high quality and error –free code rapidly are
Now more important than limiting the size of programs.
Message-Passing overhead: Much has been made of the fact that passing messages is by nature a
more costly operation than simply invoking procedures. As which overall execution speed,
however, over concern about the cost of messaging passing frequently penny wise and pound
foolish.
Program Complexity: Although object-oriented programming is often touted as a solution to
software complexity, in fact ,overuse of inheritance can often simply replace one from of
complexity with another. Understanding the control flow of a program that uses inheritance may
require several multiple scans up and down the inheritance graph.
10

Method Overriding : A method in a subclass has the same , type of the variable s and order of
the variables as a method in its super class, then the method in the subclass is said to be override
the method in the super class. The process is called Method Overriding . In such process the
method defined by the super class will be hidden.
When the method is called , the method defined in the super class has invoked and executed
instead of the method in the super class. The super reference followed by the dot(.) operator my be
used to access the original super class version of that method from the subclass.

Note: 1. Method Overriding occurs only when the name and type signature of the two methods are
identical.
2 . if method name is identical and the type signature is different , then the process is said to be
method Overriding.

Example:
class A
{
int i,j;
public A(int a, int b)
{
i=a;
j=b;
}
void show()
{
System.out.println(“i=”+i+”\n”+”j=”+j);
}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
Super(a,b);
K=c;
}
void show()
{
System.out.println(“k=”+k);

}
}
class override
{
public static void main(String args[])
{
B obj=new B(1,2,3);
11

Obj.show();

}
}
Output: k=3

Example2:
class A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;

}
void show()
{
System.out.println(“i=”+i+”\n”+”j=”+j);

}
}
class B extends A
{
int k;
B(int a,int b,int c)
{
Super(a,b);
k=c;

void show()
{
super.show();
System.out.println(“k=”+k);
}}
class override
{
Public static void main(String args[])
{
B obj=new B(1,2,3);
Obj.show();
}
}
Output: i=1
12

J=2
K=3

Abstract Class: classes from which objects cannot be instantiated with new operator are called
Abstract Classes. Each abstract class contains one or more abstract methods . In a class if there
exist any method with no method body is known as a abstract method. An abstract method is
declared as
Syntax: abstract type method-name(parameter-list)

“abstract: is a keyword used for declaring abstract methods. To declared a class as abstract , use
the abstract keyword in front of the class keyword at the beginning of the class declaration . No
Objects are created to an abstract class. For the abstract methods , the implementation code will be
defined in its subclass.
Example:
abstract class figure
{
double dim1,dim2;
Figure(double x, double y)
{
dim1=x;
dim2=y;

}
abstract double area();
}
class rectangle extends figure
{
rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println (“Rectangle area ”);
return dim1*dim2;

}
}
class triangle extends figure
{
triangle(double x, double y)
{

super(x,y);
13

}
double area()
{
System.out.println(“triangle area”);
return dim1*dim2/2;

}
}
class
{
public static void main(String args[])
{
//figure obj=new figure(10,10);// error
rectangle obj1=new rectangle(9,5);
System.out.println(“Area=”+obj1.area());
triangle obj2=new triangle(10,8);
figure a;
a=obj2;
System.out.println(“Area=”+a. area());
}
}

Note:

1. We cannot declare any abstract constructor.


2. Concrete (general) methods are also being inside any abstract class.
i)Abstract classes are used for general purpose.
ii)An abstract class must be subclass and override it methods .
iii) super class has only method name and signature end with semicolon.
iv) abstract classes cannot be used to instantiate objects. But they can used to create
object reference due to java supports Run-time polymorphism.

Explain about super keyword?


Super keyword is used for two purposes
1. If the super class and the subclass have the data members with same
name them to access super class data members from sub
Class super keyword is used.
Syntax: super. Datamember
14

//Using super to over come name hiding


class A
{
int i;
//creating a subclass by extending Class A
}
class B extends A
{
int i;// this i hides the i in A
B(int a,int b)
{
Super.i==a;
i=b;//i in b
}
void show()
{System.out.println(“ i in super class: ”+super.i);
System.out.println(“ i in subclass:”+i);
}
}
class Usesuper
{
15

Public static void main(“String args[]”)


{
B subob=new B(1,2);
Subob.show();
}
}
Output:
i In superclas:1
i in subclass:2

2. Super keyword is used to invoke super class constructor from


subclass.

Example:
class box
{
double width;
double height;
double depth;
box(double w, double h, double d )
{
16

width=w;
height=h;
depth=d;

double volume()
{
return(width*height*depth);
}
}
class boxweight extends box
{
double weight;
}
Boxweight(double w,double h,double we)
{
Super(w,h,d);
Weight=we;
}
}
17

class demo
{
public static void main(String args[])
{
Boxweight ob=new boxweight(10,20,30,100);
System.out.println(“volume of box is:”+ob.volume());
System.out.println(“weight of box is :”+ob.Boxweight())
}
}

Explain about Inheritane for


specialization,specification,construction?
Specialization:
The child class is a special case of the parent class in other words, the
child class is the subtype of the parent class.
Components
Labels Textcomponents Buttons Check box
Text field Text area
Example program:
class figure
{
double dim1;
double dim2;
v
}void setData(double d1,double d2)
{
dim1=d1;
dim2=d2;
18

}
class rectangle extends figure
{
void area()
{
double a=dim1*dim2;
System.out.println(“Area of rectangle is :”+a);

}
}
class demo
{
public static void main(String args[])
{
rectangle r=new rectangle();
r.setdata(10,20);
r.area();
}
}

Specification: The parent class defines behaviour that is implemented in


the child class but not the parent class.
There are two different mechanisms provided by the java to support the
idea of inheritance of specification.
1)Abstract class
2)Interface

Ex: Abstract class figure


{
abstract void area();
abstract void perimeter();
}
class rectangle extends figure
{
19

double length;
double breadth;
void set data(double l, double b)
{
lenth=l;
breadth=b;
}
void area()

{
double a=length*breadth;
System.out.println(“area of rectangle is:”+a)
}
void perimeter()
{
double p=2*(l+b);
System.out.println(“perimeter of rectangle is:”+p);
}
}
class demo
{
Public static void main(String args[])
{
rectangle r=new rectangle();
r.setdata(20,50);
r.area();
r.peremeter();

}
}
Construction: The child class makes use of the behaviour provided by
the parent class but is not a subtype of the parent class.
Ex: class stack extends vector
{
public object push(object item)
20

{
addElement(item);
return item;
}
Public boolean empty()
{
return isempty();
}
public synchronized object pop()
{
Object obj=peek();
removeElementAt(size()-1);
return obj;

}
Public synchronized object peek()
{
}
return elementAt(size)-1);
}
}

Explain about Inheritance for extension,limitation,combination?

Inheritance for extension: The child class adds new functionality to the
parent class but does not change any inherited behaviour.
Ex: import java.io.*;
class student
{
int rno;
String name;
void getdata()
21

{
Scanner in=new Scanner(System.in);
System.out.println(“Enter the name and rollno”);
name=in.nextLine();
rno=in.nextInt();

}
void showdata()
{
System.out.println(“Rno is:”+rno);
System.out.println(“Name is:”+name);
}
}
Class marks extends student
{
Int m1,m2,m3;
Void getmarks()
{
Scanner in= new Scanner(System.in);
System.out.println(“Enter marks in 3 subjects”);
M1=in.nextInt();
M2=in.nextInt();
M3=in.nextInt();
}

Void showmarks()
{
System.out.println(“m1=”+m1);
System.out.println(“m2=”+m2);
System.out.println(“m3=”+m3);
}
}

Class demo
{
22

Public static void main(String args[])


{
Marks ob= new marks();
Ob.getdata();
Ob.getmarks();
Ob.showdata();
Ob.showmarks();
}
}

Inheritance for limitation:- The child class restricts the use of some of the
behaviour inheritance from the parent class.

Class figure
{
Double dim1;
Double dim2;
Figure(double d1,double d2)
{
Dim1=d1;
Dim2=d2;
}
Void area()
{
System.out.println(“Area of figure is undefined”);
}
}

Class rectangle extends figure


{
Rectangle(double d1,double d2)
{
Super(d1,d2);
}
23

Void area()
{
System.out.println(“Area of rectangle is “+(dim1*dim2));
}
}
Class demo
{
Public static void main(String args[])
{
Rectangle r=new rectangle(10,20);
r.area();
}
}
Inheritance for combination:- The child class inherits features from more
than one parent class. Although multiple inheritance is not supported
directly by java, it can be simulated in part by classes that use both
inheritance and implementation of an interface, or implement two or more
interfaces

Class figure
{
Double dim1;
Double dim2;
Void getdata(double d1, double d2)
{
Dim1=d1;
Dim2=d2;
}
}
Interface methods
{
Void area();
Void p_meter();
}
24

Class rectangle extends figure implements methods


{
Public void area()
{
System.out.println(“Area of rectangle is:”+(dim1*dim2));
}
Public void p_meter()
{
Double p;
P=2*(dim1+dim2);
System.out.println(“Perimeter of rectangle is:”+p);
}
}

Class demo
{
Public static void main(String args[])
{
Rectangle r= new rectangle();
r.setdata(20,30);
r.area();
r.p_meter();
}
}

Vous aimerez peut-être aussi