Sei sulla pagina 1di 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 finali ed method. The following points are related to finali e !" method. 1. #$ery class has object class as a super class. %. #$ery class in ja$a can ha$e a finali e !" method that returns resources to the system. &. ' class should ha$e only one finali e !" method that takes no argument . method finali e is originally defined in class object. The finali e !" method has the following syntax( protected $oid finali e!" ) **finali ation code + Example: class ,arbage extends -bject ) int x,y. $oid setdata!int a,int b" ) /0a. 10b. + $oid printdata!" ) System.out.println!2x034x4 2 y034y". + protected $oid finali e!" ) System.out.println!2finali er3". + +

%
5lass 6g ) public static $oid main!String args78" ) ,arbage obj0new ,arbage!". ,arbage obj10new ,arbage!". obj.setdata!19,%9". obj1.printdata!". obj10null. System.gc!".**method to call garbage collector **obj1.setdata!%,&".**error -bj.printdata!". + + -utput( /019 y0%9 :inali er /019 y0%9 2) Write a java program sing command!"ine arg ment and explain? ' 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 ja$a program is quite easy they are stored as string in a String array passed to the args parameter of main!". The first command;=ine argument is stored at args798,the second at args718,and so on. Ex: **>isplay all command;line arguments. class 5ommand=ine) public static $oid main!String args78" ) :or!int i09.i?args.lenth .i44" System.out.println!2args724i438(34args7i8". + + #xecuting this program @a$a 5ommand=ine this is a test 199 ;1 args798( this args718( is args7%8( a args7&8( test args7A8( 199 args7B8( ;1 #) With an example explain java rec rsion mechanism ?

&
@a$a supports recursion. Cecursion the process of defining something in terms of itself. It relates the ja$a programming ,recursion is the attribute that allows a method to call itself. ' method call itself is said to be recursi$e. The classic example of recursion is the computation of the factorial of a number. The factorial of a number D is the product of all the whole numbers between 1 and D. for example , & factorial is 1E%E& ,or F . Example: ** ' simple example of recursion . class :actorial ) **this is the recursi$e method int fact!int n" ) int result. if !n001" return 1. result0fact!n;1" E n. return result. + + class Cecursion ) public static $oid main!String args78" ) :actorial f0new :actorial!". System.out.println!2factorial of & is34f.fact!&"". System.out.println!2factorial of A is34f.fact!A"". System.out.println!2factorial of B is34f.fact!B"". + + $ tp t: :actorial of & is F :actorial of A is %A :actorial of B is %) What is constr ctor ?Describe its special properties? ' constructor is a special method of class. which is in$oked automatically , whene$er an object of a class is created. It has the same name as its class and resides similar to a method. ' constructor has the following characteristics. It doesn<t ha$e any return type not e$en $oid. It can be o$erloaded. It is automatically used to initiali e the member of the object. >ifferent types of 5onstructors(

A
1)De&a lt 'onstr ctor( ' constructor that accepts no parameters is called the default constructor. If no constructors are defined for a class. The ja$a system automatically generates the default constructor. #xample( class Time1 ) int hour,min,sec. public Time1!" ) hour019. min0AB. sec0%&. + Goid printdata!" ) System.out.println!hours43hours(3 34min43minutes(34sec43seconds3". + + class const1 ) public static $oid main!String args78" ) Time1 t0new Time1!". t.printdata!". + + -utput( 19 hours(ABminutes(%&seconds.

2) (arameterized 'onstr ctor: ' constructor that takes arguments as parameter is called parameteri ed constructor. If any constructor are defined by a class with the parameters, ja$a will not create a default constructor for the class. Example: class Time1 ) int hour,min,sec. public Time1!int h,int m,int s" ) hour0h.

B
min0m. sec0s. + Goid printdata!" ) System.out.println!hours43hours(3 34min43minutes(34sec43seconds3". + + class const% ) public static $oid main!String args78" ) Time1 t0new Time1!19,H,A". t.printdata!". + + + )) Explain *ith a java program abo t re&erence variable? 5lass box ) double width. double height. double depth. + class demo ) public static $oid main!String args78" ) box b10new box!". box b%0b1. b%.width0199. b%.height0B9. b%.depth0%99. double $0b1.width E b1.heightEb1.depth. System.out.println!2$olume of box is34$". + +
Koxobject

b1

Iidth Jeight

b%

>epth

F
Jere if b1 has been set to null,but b% still points to the original object. +ote: when we assign our object reference $ariable to another object reference $ariable we are not creating a copy of the object , we are only making a copy of the reference.

,) Explain abo t this -e.*ord? @a$a define 2this3 keyword , that can be used inside any method to refer the current object. 2this 2 always a reference to the object on which method was in$oked .3this3 reference is implicitly used to refer to both the instance $ariables and method of current object. Example: class box ) double width. double height. double depth. box!double width, double height, double depth" ) this.width0width. this.height0height. this.depth0depth. + double $olume!" ) return !widthEheightEdepth" + + class boxdemo ) public static $oid mian!String args78" ) box b0 new box! 19,%9,1B". System.out.println!2$olume is (34 b.$olume!"". + + /tring handling methods(): 1)int length(): it returns the number of characters in a gi$en string .

L
2)char char0t(int *here):it returns the character at the specified location. 2where3 must be a nonnegati$e specified location within the string. The first element of string is considered to be at position 2 ero3. #)boolean e1 als(): 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;sensiti$e. Syntax( boolean equals!-bject string". %)boolean e1 als2gnore'ase(): 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 equalsIgnore5ase!String str". ))int compare3o(/tring str): it returns M9< if the two strings are equal. MDegati$e number< if the in$oking string is less than str and Mpositi$e number< if the in$oking string is greater than is passed as an argument. The comparision is case;sensiti$e ,)int index$&(/tring 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. -therwise , it returns M;1<. 4)int index$&(/tring ch5int start2ndex): it searches the occurrence of character from the startIndex argument. 6)int last2ndex$&(/tring 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. -therwise ,it returns M;1<. 7)/tring s bstring(int start2ndex): it returns a copy of the sub string that begins that startIndex and return to the end of the in$oking string. 18)/tring s bstring(int start2ndex5 int end2ndex): It returns all the characters from the beginning index upto but not including the ending index. 11)boolean startsWith(/tring str): boolean endsIith!String str"( The startIith!" method determines whether a gi$en string begins with a specified string or not. 5on$ersely , ends Iith!" method determines whether Sting ends with a specified string or not. 12)/tring to"o*er'ase(): it con$erts all uppercase characters into lowercase character of a string. /tring to9pper'ase(): it con$erts all lowercase characters into uppercase character of a string. Example on /tring :andling F nctions: class 5hange5ase>emo ) public static $oid main!String args78" ) String s03This is Sit3. System.out.println!2-riginal(34s". String upper0s.toNpper5ase!". String lower0s.to=ower5ase!". System.out.println!2Npper5ase(34upper". System.out.println!2lower5ase(34lower". System.out.println!2the length of the String is Od(34s.length!"". ++

P
NDIT;111 IDJ#CIT'D5# 3he ;ene&its o& 2nheritance: Software Ceusability Increased Celiability 5ode sharing 5onsistency of Interface Software 5omponents Capid Qrototyping Qolymorphism and frameworks. Information hiding

/o&t*are <e sabilit.: Ihen beha$ior is inherited from another class, the code that pro$ides that beha$ior does not ha$e to be rewritten. This may seem ob$ious, but the implications are important. 6any programs send much of their time rewriting code they ha$e written many times before;for example , to search for a pattern in string or to insert a new element into a table. Iith object Roriented technique , these functions can be written once and reused. 2ncreased <eliabilit.( 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 de$eloped for a single application. Thus , bugs in such code tend to be disco$ered 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. 'ode sharing: 5ode sharing can occur on se$eral le$els with object;oriented techniques. -n one le$el , many users or projects can use the same classes. !Krad 5ox 71HPF8 calls these software RIcs, in analogy to the integrated circuits used in hardware design." 'nother form of sharing occurs when two or more classes de$eloped by a single programmer as part of a project inherit from a single parent class. :or example , a set and an 'rray may both be considered a form of 5ollection . Ihen 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 si e of the resulting program. 'onsistenc. o& 2nter&ace: when two or more classes inherit from the same super class , we are assured that the beha$ior 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 beha$e , and are interacted with $ery differently. /o&t*are 'omponents: Inheritance enables programmers to construct reusable software components . the goal is to permit the de$elopment of new and no$el applications that ne$ertheless require little or no actual coding. The ja$a library offers a rich collection of software components for use in the de$elopment of application. <apid (rotot.ping: Ihen a software system is constructed largely out of reusable components , de$elopers 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

H
programming known as rapid prototyping or exploratory programming. ' prototyping system is de$eloped , 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 se$eral iterations. Such programming is particularly useful in situation where the goals and requirements of the system are only $aguey understood when the project begins. (ol.morphism and &rame*or-s: Software produced con$entionally is generally written from the bottom up, although it may be designed from the top down . that is , the lower;le$el routines are written and on top of these , slightly higher abstractions are produced , and on top of these e$en more abstract elements are generated . Dormally , code portability decreases as one mo$es up the le$els of abstraction . that is the lower; le$el routines may be used in se$eral different projects , and perhaps e$en the next le$el of abstraction may be reused. Qolymorphism in programming languages permits the programmer to generates high;le$el reusable components that can be tailored to fit different applications by changes in their low;le$el Qarts. 2n&ormation hiding: ' 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 ha$e detailed information concerning matters such as the techniques used to implement the component. Thus the interconnectedness between software system is reduced. 3:E '$/3/ $F 2+:E<230+'E Exec tion speed (rogram /ize =essage!(assing overhead (rogram 'omplexit.

Exec tion speed: 2t 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 speciali ed 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 de$elopment. (rogram /ize: The use of any software library frequently imposes a si e penalty not imposed by systems constructed for a specific project. 'lthough this expense may be substantial, as memory costs decrease , the si e of programs becomes less important . 5ontaining de$elopment costs and producing high quality and error Rfree code rapidly are Dow more important than limiting the si e of programs. =essage!(assing overhead: =uch has been made of the fact that passing messages is by nature a more costly operation than simply in$oking procedures. 's which o$erall execution speed, howe$er, o$er concern about the cost of messaging passing frequently penny wise and pound foolish. (rogram 'omplexit.: 0lthough object;oriented programming is often touted as a solution to software complexity, in fact ,o$eruse of inheritance can often simply replace one from of complexity with another. Nnderstanding the control flow of a program that uses inheritance may require se$eral multiple scans up and down the inheritance graph.

19
=ethod $verriding : ' method in a subclass has the same , type of the $ariable s and order of the $ariables as a method in its super class, then the method in the subclass is said to be o$erride the method in the super class. The process is called 6ethod -$erriding . In such process the method defined by the super class will be hidden. Ihen the method is called , the method defined in the super class has in$oked 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 $ersion of that method from the subclass. Dote( 1. 6ethod -$erriding occurs only when the name and type signature of the two methods are identical. % . if method name is identical and the type signature is different , then the process is said to be method -$erriding. Example: class ' ) int i,j. public '!int a, int b" ) i0a. j0b. + $oid show!" ) System.out.println!2i034i43Sn343j034j". + + class K extends ' ) int k. K!int a,int b,int c" ) Super!a,b". T0c. + $oid show!" ) System.out.println!2k034k". + + class o$erride ) public static $oid main!String args78" ) K obj0new K!1,%,&".

11
-bj.show!". + + -utput(

k0&

Example2: class ' ) int i,j. public '!int a,int b" ) i0a. j0b. + $oid show!" ) System.out.println!2i034i43Sn343j034j". + + class K extends ' ) int k. K!int a,int b,int c" ) Super!a,b". k0c. + $oid show!" ) super.show!". System.out.println!2k034k". ++ class o$erride ) Qublic static $oid main!String args78" ) K obj0new K!1,%,&". -bj.show!". + + -utput( i01

1%
@0% T0& 0bstract 'lass: classes from which objects cannot be instantiated with new operator are called 'bstract 5lasses. #ach 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. 'n abstract method is declared as Syntax( abstract type method;name!parameter;list" 2abstract( 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 . Do -bjects are created to an abstract class. :or the abstract methods , the implementation code will be defined in its subclass. #xample( abstract class figure ) double dim1,dim%. :igure!double x, double y" ) dim10x. dim%0y. + abstract double area!". + class rectangle extends figure ) rectangle!double a, double b" ) super!a,b". + double area!" ) System.out.println !2Cectangle area 3". return dim1Edim%. + + class triangle extends figure ) triangle!double x, double y" ) super!x,y".

1&
+ double area!" ) System.out.println!2triangle area3". return dim1Edim%*%. + + class ) public static $oid main!String args78" ) **figure obj0new figure!19,19".** error rectangle obj10new rectangle!H,B". System.out.println!2'rea034obj1.area!"". triangle obj%0new triangle!19,P". figure a. a0obj%. System.out.println!2'rea034a. area!"". + + Dote( 1. Ie cannot declare any abstract constructor. %. 5oncrete !general" methods are also being inside any abstract class. i"'bstract classes are used for general purpose. ii"'n abstract class must be subclass and o$erride it methods . iii" super class has only method name and signature end with semicolon. i$" abstract classes cannot be used to instantiate objects. Kut they can used to create object reference due to ja$a supports Cun;time polymorphism.

Explain abo t s per -e.*ord? Super keyword is used for two purposes 1. If the super class and the subclass ha$e the data members with same name them to access super class data members from sub 5lass super keyword is used. Syntax( super. >atamember

1A

**Nsing super to o$er come name hiding class ' ) int i. **creating a subclass by extending 5lass ' + class K extends ' ) int i.** this i hides the i in ' K!int a,int b" ) Super.i00a. i0b.**i in b + $oid show!" )System.out.println!2 i in super class( 34super.i". System.out.println!2 i in subclass(34i". + + class Nsesuper )

1B

Qublic static $oid main!2String args783" ) K subob0new K!1,%". Subob.show!". + + -utput( i In superclas(1 i in subclass(%

%. Super keyword is used to in$oke super class constructor from subclass.

#xample( class box ) double width. double height. double depth. box!double w, double h, double d " )

1F

width0w. height0h. depth0d.

double $olume!" ) return!widthEheightEdepth". + + class ) double weight. + Koxweight!double w,double h,double we" ) Super!w,h,d". Ieight0we. + + boxweight extends box

1L

class demo ) public static $oid main!String args78" ) Koxweight ob0new boxweight!19,%9,&9,199". System.out.println!2$olume of box is(34ob.$olume!"". System.out.println!2weight of box is (34ob.Koxweight!"" + + Explain abo t 2nheritane &or specialization5speci&ication5constr ction? /pecialization: The child class is a special case of the parent class in other words, the child class is the subtype of the parent class. 5omponents =abels Textcomponents Kuttons 5heck box Text field Text area #xample program( class figure ) double dim1. double dim%. $ +$oid set>ata!double d1,double d%" ) dim10d1. dim%0d%.

1P

+ class rectangle extends figure ) $oid area!" ) double a0dim1Edim%. System.out.println!2'rea of rectangle is (34a". + + class demo ) public static $oid main!String args78" ) rectangle r0new rectangle!". r.setdata!19,%9". r.area!". + + /peci&ication: 3he parent class defines beha$iour that is implemented in the child class but not the parent class. There are two different mechanisms pro$ided by the ja$a to support the idea of inheritance of specification. 1"'bstract class %"Interface #x( 'bstract class figure ) abstract $oid area!". abstract $oid perimeter!". + class rectangle extends figure )

1H

double length. double breadth. $oid set data!double l, double b" ) lenth0l. breadth0b. + $oid area!" ) double a0lengthEbreadth. System.out.println!2area of rectangle is(34a" + $oid perimeter!" ) double p0%E!l4b". System.out.println!2perimeter of rectangle is(34p". + + class demo ) Qublic static $oid main!String args78" ) rectangle r0new rectangle!". r.setdata!%9,B9". r.area!". r.peremeter!". + + 'onstr ction: 3he child class makes use of the beha$iour pro$ided by the parent class but is not a subtype of the parent class. #x( class stack extends $ector ) public object push!object item"

%9

) add#lement!item". return item. + Qublic boolean empty!" ) return isempty!". + public synchroni ed object pop!" ) -bject obj0peek!". remo$e#lement't!si e!";1". return obj. + Qublic synchroni ed object pee-() > ? return element't!si e";1". + + Explain abo t 2nheritance &or extension5limitation5combination? 2nheritance &or extension: The child class adds new functionality to the parent class but does not change any inherited beha$iour. #x( import ja$a.io.E. class student ) int rno. String name. $oid getdata!"

%1

) Scanner in0new Scanner!System.in". System.out.println!2#nter the name and rollno3". name0in.next=ine!". rno0in.nextInt!". + $oid showdata!" ) System.out.println!2Cno is(34rno". System.out.println!2Dame is(34name". + + 5lass marks extends student ) Int m1,m%,m&. Goid getmarks!" ) Scanner in0 new Scanner!System.in". System.out.println!2#nter marks in & subjects3". 610in.nextInt!". 6%0in.nextInt!". 6&0in.nextInt!". + Goid showmarks!" ) System.out.println!2m1034m1". System.out.println!2m%034m%". System.out.println!2m&034m&". + + 5lass demo )

%%

Qublic static $oid main!String args78" ) 6arks ob0 new marks!". -b.getdata!". -b.getmarks!". -b.showdata!". -b.showmarks!". + + Inheritance for limitation(; The child class restricts the use of some of the beha$iour inheritance from the parent class. 5lass figure ) >ouble dim1. >ouble dim%. :igure!double d1,double d%" ) >im10d1. >im%0d%. + Goid area!" ) System.out.println!2'rea of figure is undefined3". + + 5lass rectangle extends figure ) Cectangle!double d1,double d%" ) Super!d1,d%". +

%&

Goid area!" ) System.out.println!2'rea of rectangle is 24!dim1Edim%"". + + 5lass demo ) Qublic static $oid main!String args78" ) Cectangle r0new rectangle!19,%9". r.area!". + + Inheritance for combination(; The child class inherits features from more than one parent class. 'lthough multiple inheritance is not supported directly by ja$a, it can be simulated in part by classes that use both inheritance and implementation of an interface, or implement two or more interfaces 5lass figure ) >ouble dim1. >ouble dim%. Goid getdata!double d1, double d%" ) >im10d1. >im%0d%. + + Interface methods ) Goid area!". Goid pUmeter!". +

%A

5lass rectangle extends figure implements methods ) Qublic $oid area!" ) System.out.println!2'rea of rectangle is(34!dim1Edim%"". + Qublic $oid pUmeter!" ) >ouble p. Q0%E!dim14dim%". System.out.println!2Qerimeter of rectangle is(34p". + + 5lass demo ) Qublic static $oid main!String args78" ) Cectangle r0 new rectangle!". r.setdata!%9,&9". r.area!". r.pUmeter!". + +

Potrebbero piacerti anche