OOPS UNIT 1,2 Two Marks

You might also like

Download as pdf
Download as pdf
You are on page 1of 16
rs a ————— REVIEW QUESTIONS AND ANSWERS 1. What is object oriented programm concepts? 2? How doe differ Crom procedural * Object Oriented Programming (OP) isa new prograniming paradiam in which aeearnuins problem is divided into a set of Objects. Objects are created by cembining the data and the related operations (methods) + Inprocedural programming problem is divided into st of procedures and those are Focused vather then daka-Butin Ohiect Oriented Focused vather than dlgeyTthen ; 2 What are the most stril ravramming date is ing features of Object oriente* prograninin.s? + Data hiding and data abstraction «Inheritance + Polymorphism + Dynamic binding Define objects in Object oriented Programming. © Objects are the basic dynamic emtities in + Objects should be matched closely with t + Obicets contain dt an Object oriented system he real world Objects fata and fimetions which handles dita. What is Data abstraction? * The technique that reveals the essential features to the the background details is Known as Data abstraction. ¢ Both the dat: user without including ‘a. and functions can be abstracted in Class data type. 5. What is encapsulation? * The process of combining € data and functions together into. a sing called Encapsulation, le entity is Encapsulation plays a major role in Object oriented * Because the data and functions are access the data. This is known as D; system. tied into an Object, outside world cannot ata hiding, 6 Whatis the use of inheritance? Inheritance increases the Teusability of the code by d Because the newly created Class ing from the existing Class will have the combined features of both, What is mean by po! 2 lymorp * The ability of an Object to re: spond differently to the different messages is known as Polymorphism. * — Polymozphism provides a Way to take elements in more than one form, 'n inheritance, when new Objeets share common behavior and also com special behavior specific to that Object Pol 1a'yy lymorphism occurs to reduce the complexity, 3. UeWis the messuge passed berwern objects 9 + Objects in Object oriented system can communicate with each other using messages. | * Messages passing between Objects is necessary to simulate the real world Objects, | + Message iS passed by calling the procedures of the Object with information (arguments) © Message passing consists of Object mame, method name with arguments. 3 Libt the advantages of Gdjeet oriented programming, + Programs can he organized as a collection of Objects which ean he managed easily. + Datahiding provides security tothe data, as unrelated functions cannot access its data, 5 * Data abstraction enables the user to know only the essential details ofan Object. + Bevauise each Object is independent, changes in one Object will not affect ' others, * Ubject oriented systems can be easily extended by adding the additional Features, * Inheritance avoids the redundancy of code. + Polymorphism reduces software complexity. : 10. Din Ferentiate Object based ind Object oriented programming languayes, * Ubvect based programming approach supports only the object features and ‘encapsulation mechanisms. xample: Visual Basic = ~ Object oriented programming supports object features, inheritance and polymorphism. Example: C++, Java, Small talk 11, Compare Object oriented and Structured languages 7 Object oriented Procedural and Structured ] Program problem is divided into sct of | Program problem is divided into set objects _ i Emphasize is ob data Yath Emphasizeis on algorithia rathey than L algorithm data 12. List any four applications of OOPs. «Real time systems « Simulation and modeling © Object oriented databases » Hypertext and Hypermedia 13. List the features of java. * Object oriented programming > Compiled and interpreted transfation «Platform independent and portable code High security —~ . + Distributed network support © Multi-thread support ¢ Dynamje linking Automatic garbage collection «Direct database access * Core XML support TH” What kind of programs can be developed in Java? Java is an object oriented, general-purpose, portable programming tanguiage. It is suitable for both internet programs and application programs. So, two kinds of java programs can be developed. They are «Stand-alone applications «Web appleis = 15. Whut are tokens? Tokens are the smailest individual units in a program. Tokens are constructed from java support character set. Expressions and statements are constructed from tokens. “They are divided into 5 types. They are «Keywords eo — \dentifiers Constants © Operators » Seperakors 16. What are keywords? Keywords are the special reserved words having special meaning to the java compiler. These are reserved for special purpose in the program coding. So keywords cannot be used as Identifiers. All the keywords represented as lower case letters. Example ab: A continue goto 17. What are the rules to be followed to form identifiers? © Itcan consist of alphabets, digits, underscore (_) and dollar sign. © east not start with dig « Itcan be of any length © [tis case sensitive. That is upper and lower case letters are distinct 18. How does character constant differ from string literal? Character constant String literal Single character is used Sequence of characters are used Enclosed between single quotes Fnelosed between double quotes J 19. Inwhich situations, the conditional operator is replaced by if...else statement? , Even conditional operator follows simple structure, when nesting is made that becomes tuo complex and nesting gives logical errors. In this kind of situations celse statements are used. 20. Wh: is the difference between the statements d tt? nent(afier the increment value of a is used) a= preincr at t= postincrement(before the nerement value of a is used) 2. Separator | iain if a=10 means at+ gives 10 and then a becomes 11 ° 44a becomes 31 and gives 1 : List the separators available in java Purpose 1) __ | this used to enclose the parameters af finctinn tt is used to block a group of code 0) It is used to specify array index It is used to terminate a java statement It is used to separate variables in a declaration und used in the loops It is used to access the members of a class. 2B. 2. What are variables ? How will you declare it? Variable is a memory location identifier used to store data (values). Variable name must be a valid identifier Example Markl Book_name$ Declaring variables Before using a variable in a program it has to be declared. Declaration tells the following information to the compiler. » Name of the variable «: Type of data that is going to be stored What is the use of control structures? Control statements are vied jump. from one part of a program to another part of program. e statemet? What are the differences between switch and nested switch Floating point and instances cannot be | Floating point and instances can be compared compared Dilly once the expression is evaluated ‘More than once condition is evaluated at each if Handling ranges is very complex Handling ranges is not a problem 25. What is else...if ladder? nanested if..else statement, i eath if block is assc-iared with else blocK then it. known os else if ladder. 26. Write program to print the elements in an array using enhanced for loop. clase semplet publis static void main(String s{)) { int a{ J=£10,2,30,40,50,60,70,80,90,100}: for(int i:ayt ” System.out.printin(afi)); 3 4 27. What are the differences between break and continue statements? . ~ break continue It stops the execution of eurrent loop | It forces the execution of next iteration Itean be used in switch statement —_| It cannot be used in switch statement 28. List the characteristics of a class It can have fields and methods. + ttean have static and final members. 2: It-can be derived from another lass. + Mean be implemented from the interfaces. A class and members can be preceded with an access specifier. It can be normal or abstract. | | | 30. How will you Defining a class consists of two steps. They are ¢ Fields declaration e Methods definition What are the default initial values of ficlds? Default value 0 false pull What are the methods available to initialize afield? » Explicit initialization method © Initializing with constructors method © Initializing block method What are initializing blocks? Class declarations can have blocks of code to initialize fields. These hiecks are automatically exeeuted whenever an object of that class is created, classAdd { int NumJ,Num2,Obj_num; } ‘What is the purpose of using this keyword? this keyword is used to refer the object which invoked ihe method. this keyword can be used inside any method to refer to the current object. That is, this aiways has reference to the object on which the method was invoked. Nonnally a méthod is alJed with two 4 assigned to this, Example void Change_val( nt Numl int Num2){ this.Naml=Numi; this. Nam2=Num2; } 34. What are the parts available in a method? 3 Methed name —The name shat is used to invekests methed Temust be a wdlid ‘identifier. ‘© Arguinents list - List of valtes with daca types thatare required to do the process. “This may be empty, «Return type - The type of the data that is going to be returned after the processing, void is specified when it does not retarn anything. © Method body ~The process that is going to be done by this method. 35. Differentiate mutators and accessors. Mutators — Accessors Methods that change field values of an object arc called mutator methods. Example: — public void change(int nl int n2){ Numl=nl; Num2: 5 } 36. What are the three key characteristics of objects? «Identity - the name to identify the object uniquely among multiple objects 49dject name) «Behavior - the processes that can be'done on fields by the objects (Methods) + State - the changes in the data after the processing or initialization (Fields) 37. How will you create objects? Objects aré instantiated using new Operator. The new operator creates an object of the specified class and returns a reference to that Object. Memory space is allocated only to the fields and not to the methods. EEE ES General form ation and instantiation Declaration = class_name object_name: Instantiation : object_name = new classname(actual_arguments list); Harguments to the constructor Example Add A; Hdcclares the Object A=new Add); —_//instantiates the Object 38 What are implicit and plicit argaments? Methods of class receive two types of arguments while calling using objects. They are explicit and implicit arguments, Object name in a method call is the implicit argument and the arguments passed between the parentheses are explicit arguments Implicit argument makes this object which refers to the current object. Example A.Init_num(10,20); Here A is the implicit argument and 10 and 20 are explicit arguments. 39, List the access specifiers - private © protected + public 40. When is private specifier used? + Fields and methods that are to be protected highly are declared with private specifier. * private members are accessible only within its own class. * private members are not inherited in the subclasses, © private methods acts like final methods. 41. What is meant by static field? A field can be declared with static, Static fields are also known as class fiekls, Because it isnot related to any object. Normally each object has its own copy of ail instance fields. But, only one instance ig created for cach static field and that is shared by all the objects, Static fieldsare common to all the objects. So class name is enough to access the Static fields. But it is legal to use an object to access a static field. : ee lm 42. Write a sbort note on static block. Static initialization block is a initialization block declared with static keyword. if the static fields of a class require complex initialization code, a static initialization block is used. Static initialization ogcurs only when the class is first loaded. This block can process only static fields and methods. Example classAdd int Num1,Num2,Obj_num; static int 145 istatic initialization block static{ Random Gen = new Random(); Id = Gen.nextInt(1000) System.out.printIn(‘“Chass is started”); } /normal initialization block { Obj_num=ld++: } 43. 4¥hat are the characteristics of static methods? It can access only the static fields and the static methods. * — It can be accessed by the normal and static methods of its own élass. * — It.can be accessed using the class name or object name from another class. * It cannot refer this and final 44. What are the functions of a constructor? + It can be used to initialize the fields. » It can be used to allocate memory to the.fields. =», AS. What is a default constructor? Default constructor is a constructor with no argunjents. If no constructor is defined in a class, then a default constructor is automatically provided by the compiler. This default constructor assigns default values to all the ficlds ina class. That is, 0 ea ——eEeEEeE—ee ee 47, 43. 49. null is assigned to afl the objects. If at least one constructor is defined in a class, the compiler will not include any default constructor arid then it is illegal to construct objects without construction parameters. ° What are the steps followed when a constructor js called? 1. Default values are assigned to all the fields. 2. Field initializers and initialization blocks are executed one by one 5 they are declared in the class. Uf the first line of the constructor invokes the secoau constructor is executed, 4. The first constructor continues to the completion. What are the advantages of using packages? + Classes can be easily reused + Two lasses indifferent packages can have sanje name provides way to hide classes What is the use of static imports? This eliminates the need of class name before static members. static § to normal import. But it uses the static keyword after import keyword. Example IFimport static java.lang.Math.*;is included, the following statement is enough. sqrt(pow(x, 2) + pow(y, 2)) no need to use like the following Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) What is meant by array? ne. F script In Array is a collection of similar dafa type values thaf share a common element in an array can be-accessed by using the index number or sa java, array isan object. «7 Example To access the 3!) clement in the array mark{ J, following statesnent can be used. < mark[2} Si. 52. 3 Si. 32. Array dechira An array ean be dee red by specifying the data type followed by ( } with array name. Array declaration onily*declares the name of an array. No memory space is allocated. So we cannot use it before instantiation. Size should net be given to gn array at the time of declaration. General form of array declaration Method t: — data_type array_name[ J; M od 2: dots type! Varray name: Example int mark}; How is an array Jength is extracted? - Size of an array can be obtained by accessing the attribute length, Example: size=mark.length; What is meant by Anonymous Arrays? An anonymous array is an array created without any name. It is used to reinitialize an array without creating a new variable. General form array_name=new data_type[ }{ values_fist }; Example mark=new int{ }{ 10,20,30,40,50); Explain about arraycopyQ) method. ‘This is also doing the same job as copyOf method. But it does not return any reference. It just copies the content of one array in another. But the destinatjon must havé stfficient memory space to hold the source values. . General form System.arraycopy(souirce,source_index,destination,destination_index,count); What is meant by ragged Ragged arrays are arrays jn which different rows have different lengths. In Java, multidimensional arrays are represented as array of arrays, that is, collection of one dimension! array. There are no multidimensienal arrays in Java. Example int afJfFnew int{2}[J; a[0]=new int{S]; a[1}=new int] 10]; now a contains 5 elements in first column and 10 clements in the second column. Bari —— ai — REVIEW QUESTIONS AND ANSWERS What are the advantages of using packages? Classes can be easily reused «Two classes in different packages can have same name 2s Itprovides way to hide classes What is the use of static imports? ‘This eliminates the need of class name before static members. static import is similar to normal import. But it uses the static key word alter impest keyword. Example . statement is enough. Ifimport static java.tang Math.*:is included, the follow! sqet(pow{x, 2) + powly. 2)) no need to use like the following Math sqrt(Math.pow(x. 2) + Math.pow(y. 2)} How will you hide a class in packages? Only the public classes in a package are accessible from outside. Non-public classes are not accessible. Thus the classes are hidden in a packa Example package mypack; classA //sercured class { } public class B Hiaccessible from outside { Aa; J What is. meant by inheritance? * Inberitance is the process by which new classes called derived classes are created rom existing classes called base classes. What are the advantages of inheritance? © Reusability of code + Effort and Time saving © Increased reliability can be extended by a class Wit & How maay elas ‘4 class can extend only one class. class sferived_class_name extends base_class_name { © 1/smplementation code and overriding code : y . 7. List the types of inheritance. 7 1. Single Inheritance Multiple Inheritance Maltilevel Inhernanee Aficrarchical Inheritance 5, ebvid Inheritance What are final classes? ‘A class that is declared with final keyword is known as final class. A final class cannot be subelassed. This is done fot reasons of security and efficiency. Accordingly, e many of the Java standard library classes are final, for cxample java.fang.System and java.lang.String. All methods in a final class are implicitly final. ss | 9, ‘Why are the final methods used? These ars used te prevent a method from overriding by the subclasses. 4 10, Write a short note on final fields. ‘A final variable can only be assigned once. This assignment does not grant the variable immutable status. Ifthe variable isa field of a class, it must be assigned in the constructor of its class. The vafueofa final variable js not necessarily known at compile time, but value of constant is known at compile time. Example public static final double PI = 3.141592653589793; 1. What is a abstract class? ‘ ‘An abstract class is class that cannot be instantiated. (i.c.) objects are not created for an abstract class. It can only be used as a super class for other classes that extend the abstract class. 12. Write the general form of an interface? — vd erface InterfaceName 1 declaring methods Ipubli¢ abstract} returnType methoUName i (arguments); 11 defining constants I. Md, 15, 16, 17. 18. 19, {ype propertyName = value; What inherit ce ean be only achieved through interfaces? Multiple inheritance What are the mettiods available i the Object class « clone() © equals() CopytObject src) = finatiret \ + getClass() © hashCodeyy © notify() © notifyAll © koString() © Waitt) Wh: itis the use and the syntax of equals() method of Cbject class? Wt is used to check whether two objects are equal of not, Public bouican equals(Object uherObject) What is meant by object cloning? Object Cloning is the Process of creating identical copy of an object. A: copy of an object is c1 ni cdentical reated by invoking clone() on that object, What are the different types of cloning? + Deep Cloning + Shallow cloning What will be the results when we invoke the clone() method? * flu an Object reference to a copy of the object upon which it is mvoned, or + throw CloneNotSupportedException What are inner classes? An inner class is a class declares cd entirely within the body of anothe: ciass or interface. It is distinguished from a stibclass, List the types of inner classes. + Member class © Local class, + Anonymous class © Inver ¢lasses cannot have static members. only static final variables. e — Interfaces are never inner. es are not inner classes. inherjt static members that are not compile-time constants © Static clas © Inner ¢lasses may even though they may not declare them. 22. What is the use of + operator on strings? ‘The + sion can be tised to concatenate(join) two strings. During the concatenation conyertsd into sting type 1g operar:ds Example String s="Bala+ "krishnan"; 23. How will you compare two strings? : Strings are compared by using 3 methods. equals() , equalsignoreCase() and i compareTo(). I Example : strlequals(str2): - // if strl and str2 are equal returns true, otherwise false. strlequelslgnoreCase (str); same as above. but ignores the case strl.compareTo(str2); / stel=str2-0, strl>str2 - positive, strl

You might also like