WWW.VIDYARTHIPLUS.COM CS2311 OBJECT ORIENTED PROGRAMMING UNIT-I Problem solving approaches: There are two problem solving approaches: i) Procedural programming ii) Object Oriented Programming Difference between procedural & Object Oriented Programming: UQ: Difference procedure oriented and object oriented programming. PROCEDURE ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING It executes series of procedures It is a collection of object. sequentially. This is top-down approach. This is bottom up approach. Major focus on procedures. Major Focus on objects. Data Reusability is not possible. Data reusability is one of the features. Data hiding is not possible. Data hiding can be done by making it private. It is simple to implement. It is complex to implement Example: Example: C,FORTRAN,COBOL C++,JAVA OBJECT ORIENTED PROGRAMMING CONCEPT: UQ: Explain the elements of object oriented programming. (M/J’12-10M, A/M’11-4M) Object Oriented Programming concept also called as characteristics of oops (or) Elements of oops (or) basic concept of oops. Various Characteristics of OOPS Languages are: 1. Object 2. Class UNIT I 3. Data Abstraction Object oriented programming 4. Data Encapsulation concepts – objects-classes- methods and 5. Inheritance messages-abstraction and encapsulation- 6. Polymorphism inheritance- abstract classes- 7. Dynamic Binding polymorphism. Introduction to C++- 8. Message Passing objects-classes constructors and 1. Object: destructors Object is an instance of class. Object is a runtime (or) real world entity. It represents a person, place or any item that a program handles. In C++ the class variables are called Objects. Using Objects we can access the member variables (Attributes) & member function (procedures). A Single class can create any number of objects. Example: Cycle Student Make Move() Name Total() Frame size Repair() Roll no Avg() Wheel size Assemble() DOB Display() Material Marks Member Variables Member Functions SYNTAX: Object creation Classname Objectname1, Objectname2…. Member Function Access Objectname1.function_name( ); Example: Student S1,S2; WWW.VIDYARTHIPLUS.COM V+ TEAM WWW.VIDYARTHIPLUS.COM S1.total( ); 2) Class: A class is an entity in which data and function are put together. It is also collection of objects. Member function are defined in two ways: i. Inside of the class ii. Outside of the class “Scope Resolution Operator (::)” used to define the function in outside of class. Access Specifier is a main role in class. Access Specifier is specifying the access method of data (or) Functions. Access Specifier Classified into 3 types: i. private - Access with in class ii. protected-Access with in class & inherited class iii. public-Anywhere access In definition of class must put a semicolon (;) at the end. “class” is the keyword used to define the class. SYNTAX: INSIDE OF CLASS OUTSIDE OF CLASS Class class_name Class class_name { { Access_Specifier: Access_Specifier: Variable declarations; Variable declarations; ___ ___ ___ ___ Access_Specifier: Access_Specifier: function declarations; Function definitions; ___ __ ___ __ }; }; return_type class_name::function_name() { ------------------------ ------------------------- } Example: //Inside of the class: OUTPUT: class rectangle Enter the Length & Breath:10 { 20 private: Area = 200 int len,br,area; Enter the Length & Breath:10 public: 40 void get_data() Area = 400 { cout<<”enter the length & breadth:”;//Output Statement cin>>len>>br;//Input Statement area=len*br; cout<<”area=”<<area; } }; void main() { OUTPUT: rectangle r1,r2,r3; Enter the Length & Breath:10 r1.get_data(); 20 r2.get_data(); Area = 200 } Enter the Length & Breath:10 //Outside of the class: 40 class rectangle Area = 400 { WWW.VIDYARTHIPLUS.COM V+ TEAM WWW.VIDYARTHIPLUS.COM private: int len,br,area; public: void get_data(); }; void rectangle::get_data()//Scope resolution operator { cout<<”enter the length & breadth:”;//Output Statement cin>>len>>br;//Input Statement area=len*br; cout<<”area=”<<area; } void main() { rectangle r1,r2,r3; r1.get_data(); r2.get_data(); } 3. Data Abstraction: Data Abstraction means representing only essential features without including background (or) Implementation details. In C++, Class is an entity used for data abstraction purpose. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT). Example: class student { int roll; char name[10]; public: void input(); void display(); } In the main function we can access the functions of class using object. student obj; obj.input(); obj.display(); 4. Data Encapsulation: They wrapping up of data and function into a Single Unit (class) is known as encapsulation. The data is not accessible to the outside world. These functions provide the interface between the objects data & Program. Data Encapsulation is also called as “Data Hiding” (or) “Information Hiding”. Example: Other Object Own Object Data 5. Inheritance: Inheritance is the Process by which Objects of one class acquire (join) the Properties of objects of another class. It is a process of deriving new classes from existing class. It supports the concept of Hierarchical classification. Exiting class - Baseclass (or) Superclass Derivedclass - New class (or) Subclass The concept of inheritance provides “reusability”. We can add additional features to an existing class without modifying it. Type of Inheritances: i. Single Inheritance ii. Multiple Inheritances iii. Multilevel Inheritance WWW.VIDYARTHIPLUS.COM V+ TEAM WWW.VIDYARTHIPLUS.COM iv. Hierarchical inheritance v. Hybrid (or) Multipath Inheritance A i) Single Inheritance: One base class, one derived class. B A B ii) Multiple Inheritance: A Two base class, one derived class. iii) Multilevel Inheritance: C B One base class, one intermediate class, one derived class. A iv) Hierarchical Inheritance: One base class, more than one derived class. C v) Hybrid (or) Multipath Inheritance: More than one inheritance combined together. B C A Hierarchical Inheritance B C Multiple Inheritance D 6. Polymorphism: Polymorphism is a Greek term; it means the ability to take more than one form. Poly => Many Morphs =>Forms. An Operation may exhibit (display or Show) different behaviors on the types of data used in the Operation. Polymorphism divide into two types: i. Compile Time Polymorphism ii. Runtime Polymorphism i) Compile-time Polymorphism: It can be execute the code in compile time. It’s divide into two types 1. Operator Overloading 2. Function Overloading 1. Operation Overloading: The Process of making an Operator to exhibit different behaviors in different instance is known as Operator Overloading. Operation of addition For two numbers, the Operation will generate a “Sum”. For two strings, the Operation will produce a third String by “Concatenation”. 2. Function Overloading: Using a Single Function name to perform Different types of tasks is known as function overloading. A Single function can be used to handle different number & different types of arguments. A Particular word having several meanings depending on the context. Polymorphism plays an important role in allowing objects having different internal structures. Example: WWW.VIDYARTHIPLUS.COM V+ TEAM Syntax: Object_name. Methods & Messages Messages: A function calling with help of object is called message.COM V+ TEAM . Methods: A function can return any information (response) to message is called method.fun(). Creating Classes 2. Message Passing involves the following steps: 1.VIDYARTHIPLUS. This message can send & receive the information through objects. Types: i. WWW. It is associated with Polymorphism & Inheritance. Process of sending message through objects is called message passing. Information is called as arguments. WWW. It is also called “Late Binding”.b). A Message for an object is a request for execution of a procedure and receiving object that generates the desired result. With response ii. Static Binding ii.VIDYARTHIPLUS. Establishing communicate with One another by Sending & receiving information. Two types of binding i.COM 7.int y)//Function Definition { __ __ } Binding 8. Creating Objects from class definitions 3. Sending information through arguments of function. Dynamic Binding 1) Static Binding: In Static binding which function is to be called for object is determined at “Compile time”. 2) Dynamic Binding: Dynamic Binding means that the code associated with a given procedure (or) function call at “run time”.//Function Calling void fun(int x. Example: Circle. Dynamic Binding: Binding refers to the linking of a Procedure (or) function call to the code to be executed in response to the call (function definition). Message Passing: An object Oriented Program consists of a set of objects that communicate each other. Without response Above two types of methods can divide with their responses.draw(10). 1) With Response: Information can send & receive through messages. Example: Obj.function_name(arguments). Example: fun(a. C is a Procedure Oriented Language. WWW. Input & Output is done using scanf & printf The input & Output is done by using “cin” and 3. C++ is an Object Oriented Program Language. 4) Compiling C++ Program using “Ctrl +F9” Short cut key. & objects.COM Hello World V+ TEAM . 2) Simulation & modeling 3) Object Oriented Databases. 5) Neural networks & Parallel Programming.h> void main() OUTPUT: WWW. I\O Operations are supported by “iostream. 2. “cout”. class C++ supports inheritance polymorphism. %s) for getting Control strings are no need for getting input & 5.cpp” that means C plus plus. Example: // A simple Program #include<iostream. 7) Office Automation Systems.h” header 4. functions. polymorphism. Virtual 6. 3) Type the Program & Save as “filename. 4) Artificial Intelligence (AI) & Expert Systems. It use top down approach of problem solving. file. Structure of C++: // title of the Program Include file section Preprocessor Section Global variable section Class declaration Member function definition Main function section Simple C++ program: 1) Open Commend prompt & type of the following instructions: >cd\ >cd TC >Cd bin >TC 2) Now new editor window will be open.No. classes & object concepts. C does not support inheritance. Difference between C and C++: S.VIDYARTHIPLUS. %C.COM 2) Without responses: Information can send only through messages. 6) Decision Support Systems. Introduction to C++: Language Developed by Year C Tennis Riche 1976 C++ Bjarne Stroustroup 1980 JAVA James Gosling 1991 C++ is a One of the advanced language of ‘C’. It uses bottom-up approach of problem solving.h header files. I\O Operations are supported by stdio. printing output. Applications of oops: Applications of oops are beginning to gaining importance in many areas: 1) Real-time systems. C C++ 1. Control strings are used (%D. functions. input & printing Output.VIDYARTHIPLUS. Keywords 2. try 4. “a+b”. WWW. arrays.COM { cout<<”Hello World”. return 28. float 21. auto 9. Example: “Apple”. class 7. char 12. white spaces and the syntax of the language. asm 5. Integer constant ii. etc. volatile 8. unsigned 6..VIDYARTHIPLUS. “7sent”. break 10. inline 10. ”a+92t>”… String handling functions: WWW. do 16. Keywords are “Predefined Identifiers”. The Keywords Supported by “C language” and also available in C++. register 27. if 24. 5) The maximum number of characters used in forming an identifier=32 char. new 11. classes.e. struct 2. They are the fundamental requirement of any language. typedef 4. union 5. default 15. They can Classified as i. sizeof 31. 3) Constants: A Constant does not change its value during the entire execution of the program. digits and Symbols are enclosed with in double quotation marks are called string. Identifiers 3. All keywords are “Lower case”. } Tokens: The smallest individual units in a program are known as tokens. else 18. 1) Keywords: The keywords are known as “Reserved words”. protected 14. Operators A C++ Program is writing using these tokens. 3) Identifiers are “case sensitive” i. public 15. static 32. this 2. long 26. switch 3. int 25. for 22. C++ has the following tokens: 1. void 7. template 16. throw 3. signed 30. Identifier has the following RULES: 1) Only alphabetic characters.. 4) Keywords are not allowed. goto 23. while The following keywords are “Only supported in C++” (16 keywords) 1. const 13. virtual 2) Identifiers: Identifiers are used to give names to variables. So these words cannot be used for other Purposes. extern 20. delete 8. short 29.VIDYARTHIPLUS. operator 12. functions. case 11. Identifier used to identify something. enum 19. 2) The name cannot start with a digit. friend 9. Constants 4. Character constant iii.COM V+ TEAM . private 13. Variable names are identifiers used to name variables. double 17. Variables: A Variables is an entity whose value “can be changed” during Program execution. digits & Underscores are permitted. Enumeration constant 4) Strings: Group of (or) Set of Characters. continue 14. Strings 5. Floating Point constant iv. lower vase (or) Upper case. (32 Keywords) 1. catch 6. ) 2) Relational Operator (<.<=. *.compares two strings.||.%.VIDYARTHIPLUS. Except void. The most commonly used string handling functions.concatenates (join) two strings 2) strcmp() . &.!) 4) Assignment Operator ( = ) 5) Increment & decrement Operator (++. * ) 3) Pointer to member Operator (->.!=. 5) strupr() – convert strings into upper case 6) strlwr() . Built-in-type: Both C and C++ compilers support all the built-in(also known as basic or fundamental) datatypes.finds the length of a string. Types of operators: C & C++ Provides following Operators: 1) Arithmetic Operator (+. 4) strlen() . Datatypes: Datatypes specify the size and type of values that can be stored. WWW.&->) Arithmetic Operators has Operators Precedence “BODMAS” “B”racket “O”f “D”ivision “M”ultiplication “A”ddition “S”ubtraction.>. Some Operators require only one Operand called “Unary Operators”. Some other Operators in C++: 1) Scope Resolution Operator ( :: ) 2) Pointer to member declaratory ( :: .*. Blocks & Scope can be used in Constructing Programs.==) 3) Logical Operators (&&. -. Derived type 1./.COM The C++ library has a large number of string handling functions.C++ is also a block Structured language. 3.!.convert strings into lower case. : ) 7) Bitwise Operator (&. WWW. Some Operators require two Operands called “Binary Operators”. Types of Datatypes: 1. 3) strcpy() . 5) Operators: An Operator is a symbol that specifier an Operator to be Performed on the Operands. Built-in-type 2. 1) strcat() .COM V+ TEAM . .VIDYARTHIPLUS. The variety of data types available allow the programmer to select the type appropriate to needs of the application. unsigned.copies one string over another. User-defined type. sizeof.>=. long and short may be applied to character and integer. The modifiers signed. the basic datatypes may have several modifiers preceding them to serve the needs of various situations.|. >* ) 4) delete – Memory release Operator 5) new – Memory allocation Operator 6) endl – Line feed Operator 7) setw – field width Operator Scope Resolution Operator ( :: ) C.&&*.--) 6) Conditional (or) Ternary Operator (? .^) 8) Special Operator (. char author[25]. It is divided into following types: 1. gp=ip. WWW.COM void datatype: Uses of void datatype: 1. Class 1. But the differences the size of union is equal to the size of largest member element. WWW. Syntax: struct structure_name { datatype member1. datatype member2. Structure 2. 2. }. The declaration of generic pointers. int pages. 2. 3. To indicate an empty argument list to a function. Enumeration 4. Structure: Structures are used for grouping together elements with dissimilar types.book2. Example: struct book { char title[25]. To specify the return type of a function when it is not return any value. struct book book1.//return type and argument list void *gp. Structures and union are same in declaration.VIDYARTHIPLUS. Example: void function(void). Union: Union also used for grouping together elements with dissimilar types. …. float price. 2.//Generic pointer int *ip. Union 3. User-defined datatype: User can define the type of data.book3.COM V+ TEAM .VIDYARTHIPLUS. }. .h. Array b.b1.a1. Cannot provide a default value in the middle of an argument list.int k=10) In valid: int mul(int i=5. 4.b. In such cases the function assigns a default value to the parameters which does not have a matching argument. Must add defaults from right to left. Valid: int mul(int i=2. Example: enum shape{circle.h> #include<conio.VIDYARTHIPLUS. The volumes are: cin>>l>>b>>h.b. Pointer Control structures: 1. triangle}. Function c.vol2.2 and so on. Vol1=120 vol1=l*b*h.b. Selection structure (branching) i) if – else (two way branch) ii) switch (multiple branch) 3. OUTPUT: public: Enter the value of l.1 3. Derived Datatype: Derived datatype is deriving the data from the existing.int j. It can be different from parameter passing with particular datatypes. Syntax: enum enum_name{Item1.int j=5.COM 3. It is divided into following types: a. Sequence structure (straight line) 2.h:4 void get() 5 { 6 cout<<"Enter the value of l. The enum keyword automatically enumerates a list of words by assigning them values 0. WWW.Item2.}.VIDYARTHIPLUS. int vol1.vol3. thereby increasing at length (comprehensively) of the code. } Vol2=210 Vol3=60 WWW. Example: //Function Overloading and Default Argument #include<iostream. Class: Refer the page No.….int j=5.int j) int mul(int i=5.h> class volume { int l.c1. Loop structure (iteration or repetition) i) do – while (exit controlled) ii) while (entry controlled) iii) for (entry controlled) Default Arguments: C++ allows calling a function without specifying all its arguments. Enumerated datatype: It provides a way for attaching names to numbers.COM V+ TEAM .int k=10) int mul (int i.int k=10) Function overloading: More than one function definition for same function name. square.1.h:". get(5. WWW. a switch or goto.6. 4) If inline functions are recursive.get(5). } Pointers: It is a Derived Datatype. vol2=l*b*h. cout<<"\nVol1="<<vol1<<"\nVol2="<<vol2<<"\nVol3="<<vol3. It can be used to access and manipulate data stored in the memory.int y. v.VIDYARTHIPLUS. Ordinary Variable: int a=5.int z) { l=x. v.VIDYARTHIPLUS. volume v. Some of the situations inline function may not work: 1) Returning values if a loop. } }.display().COM void get(int x. } void get(int x. void main() { clrscr().7). Syntax: inline return_type function_name (argument) { ======================= } Example: inline int sqr(int x) { return(x*x*x).get(). vol3=a1*b1. if a return statement exits. getch(). It execute faster.COM V+ TEAM .b1=y. 3) If contain static variables. a variable WWW. } void display() { cout<<"The volumes are:". v. 2) Not return values. aaccess the value &a access the address of variable.int y=12)//Default Argument { a1=x. } void main() { cout<<sqr(4). v. getch().h=z. } Inline Function: To eliminate the cost of calls to small function the C++ Provides inline function.b=y. Properties (or) Characteristics (or) Rules for constructor: 1) The constructor name must be as class name. So that memory allocate for the each object to saving of memory. WWW.COM V+ TEAM . If the variables are not initialized then they hold some “garbage value”. It just initializes the variables. Implicit calling ii. 5) Constructors cannot be virtual. Explicit calling Syntax: i) Implicit calling: classname objectname(args). 2) It can call automatically when object is created. 3) Constructor with dynamic allocation: The constructor can also be used to allocate memory while creating objects. It is non parameterized constructor. 4) It cannot return any value.COM 5 value 4002 address Constructors: Objects need to initialize the variables. The constructors that can take arguments (or) parameters are called “Parameterized constructor”. The constructor name as the class name. Allocation of memory to objects at the time of their construction is known as dynamic memory allocation (or) dynamic constructors. To avoid that above problem use the special member function is called constructor. The amount of memory for each object varying one. 3) It must be declared with “public” access specifier. The constructor can be called automatically whenever a new object is created. 2) Parameterized constructor: Passing arguments (or) parameters to the constructor function when the object is created. Types of Constructors: 1) Default constructor 2) Parameterized constructor 3) Constructor with dynamic allocation 4) Copy constructor 5) Default argument constructor 6) Destructor 1) Default constructor: Default constructor is the basic constructor.VIDYARTHIPLUS. Syntax: class classname { public: classname() { __ __ } }. We can call the Parameterized constructor using two ways: i. ii) Explicit calling: classname objectname=classname(args). WWW.VIDYARTHIPLUS. It should not have return type. length=strlen(name1). m1=n1.name1). If any value is missing this will be taken from the argument list values in definition of constructor. The process of initializing through a Copy constructor is known “copy initialization” Send object as parameter. avg=total/3. public: stu()//Default Constructor { m1=m2=m3=total=0. Syntax: classname object1.h> #include<string.VIDYARTHIPLUS.//Implicit passing classname object3=object2. WWW.long int regno1.char *name1. name=new char(length+1). Syntax: ~destructorname() { ___ ___ } Example: //Example for Multiple constructor or Constructor overloading & Destructor #include<iostream.h> #include<conio. classname object2(object1).dept[10].int n3. float avg.//Explicit passing 5) Default argument constructor Give the initial values to inside the argument list of constructor.m2=n2. Parameterized constructor { int length. strcpy(dept.m3=n3. Like a constructor the destructor is a member function whose name is the class name but is preceded by “tilde (~)” symbol.m3. 4) Copy constructor: Copy constructor is used to declare and initialize an object from another object. long int regno. ….) { ___ ___ } 6) Destructors: Destructor is used to destroy the objects that have been created by a constructor. WWW. Syntax: variablename = new datatype[length].total.dept1).h> class stu { int m1.//Dynamic allocation constructor strcpy(name.0. regno=regno1. char *name.VIDYARTHIPLUS.m2. Syntax: constructorname(datatype variable=value.char *dept1="EEE")//Default argument.int n2. total=m1+m2+m3. } stu(int n1.COM V+ TEAM .COM The memory is allocated with the help of “new” operator. Explain the different types of constructors with example. (A/M’11. (M/J’13 18.dept<<"\t"<<o1. Explain in detail the concept of constructor overloading (or) multiple constructors. What is mean by dynamic constructor? (N/D’10) 6."senthil").(N/D’11-8M 4.(N/D’11-10. } University Questions: PART-A 1. Explain function overloading with example.333332 { clrscr(). (A/M’11 14. What will happen to an object if a destructor is not coded in the program? (N/D’10 PART-B 1.VIDYARTHIPLUS.M/J’12.656566.10 9. How are data and functions organized in an object oriented programming? (M/J’12 12.12-16M. What is the use of ‘this’ pointer in C++? (N/D’10 24.333336 stu s1. (ND’11. N/D’11-8M. Write the significance of void datatype. 3.m1<<"\t"<<o1.(N/D’11-8M 5. WWW. (A/M’11 17. How will you define a string? (A/M’11 16. (N/D’10 25.(N/D’11-8M. What do you mean by constructor? List out the important characteristics of constructor. Define inline function with example.name<<"\t"<<o1. Explain the concept of pointers in detail. void main() senthil 656566 EEE 45 56 35 136 45.M/J’12) 2.m3<<"\t"<<o1. stu s4(55."IT"). List the various unconditional branching statements. Write any four string manipulation functions.N/D’12-16.56. cout<<"\nName\tRegno\tDept\tMark1\tMark2\tMark3\tTotal\tAverage"<<endl. What is Object Oriented paradigm? (M/J’12 11.COM V+ TEAM . What do you mean by dynamic utilization of variable? (M/J’13 19.(N/D’12) 7. M/J’13-8) WWW. Write any five differences between C and C++. What is the significance of empty paranthesis in a function declaration? (M/J’13 20.total<<"\t "<<o1.95.76. Give the applications of OOP. What is an inline function? (N/D’11 4."kumar". Define an array. Write the program to find number is ODD or EVEN. (N/D’11-10. List out the types of operators. What are the restrictions for writing inline function? (N/D’12. (N/D’12.m2<<"\t"<<o1. What are the operators that are specific only to C++. Differentiate Object based programming languages and Object Oriented programming languages. (N/D’10 23. Define a Class and object.COM } stu(stu &o1)//Copy constructor { cout<<o1. stu s2(45. Explain the various datatypes available in c++. (N/D’12 8. (N/D’10 22. M/J’13-8M. stu s3=s2. getch().regno<<"\t"<<o1. N/D’10 15. What is mean by data hiding in OOP? (N/D’10 21.M/J’12-16M. } ~stu()//Destructor OUTPUT: { } Name Regno Dept Mark1 Mark2 Mark3 Total Average }. M/J’13-8) 2. Difference procedure oriented programming and object oriented programming.N/D’12-8. (N/D’11) 3. Explain how objects can be passed and returned from a function with an example. kumar 756566 IT 55 76 95 226 75.VIDYARTHIPLUS. A/M’11) 5.756566. stu s5=s4. What are the datatypes in C++? (A/M’11 13. A/M’11 10. M/J’13-8M 6.avg<<endl.35.(N/D’11. Compare overloading and overriding. What is a copy constructor? (N/D’11. N/D’10-6M 17. A/M’11-8) 9. { (or) ___ object1 symbol object2. e) Declare the operator function in “public”. templates - Inheritance – virtual functions. If can be either normal member function or friend function.COM 7. Some operators are cannot overloadable: UQ: Write any four operators that cannot be overloaded. Operator Overloading: UQ: Define a class string and overload +. (M/J’12-8M 14. b) Default arguments may not be used. (N/D’11-6M) 8. (M/J’13-8M 19. (M/J’12-16M) Write a program to explain unary operator overloading. (N/D’10-12M 21.(A/M’11-6M. (M/J’12-8M 15. Write a C++ program to print the following output using for loops. WWW. =. What are the features of OOP? Briefly comment on them. (A/M’11-6M. Explain special operators in C++. (N/D’10-12M UNIT-2 UNIT . (N/D’12-8M) What do you mean by operator overloading? (A/M’11-4M) Create a class FLOAT that contains one float data member overload all the four arithmetic operators so that they operate on the objects of FLOAT.friend functions. Create a function to compute simple interest. 13. Operator overloading can be defined as an ability to define a new meaning for an existing operator.VIDYARTHIPLUS. (N/D’11-8.(N/D’12-8M 1 22 333 …… 10. (N/D’12-16M. 12. (M/J’12-10M. (M/J’13-8M) An operator that has multiple meanings is called Operator overloading. What is an array? Write a C++ program to find the maximum of n numbers and arrange a set of numbers in ascending order using array. Rules for Operator overloading: UQ: What are the various rules for overloading operators? (N/D’11) a) The order of precedence cannot be changed.VIDYARTHIPLUS. c) No new operators can be created.type conversions. (N/D’10-12M 20.II Operator overloading .COM V+ TEAM . Give notes on i) Expressions ii) String operations. Describe about default and parameterized constructor. How will you initialize an object in C++? (A/M’11-4M 18. Write any five differences between C and C++. (N/D’12) WWW. Write a C++ program for the following: (N/D’12-8M SUM=1+(1/2)2 + (1/3)3 + (1/4)4 11. Supply default arguments to the function. Write a C++ program which gets student details and sort them according to the Name using Class and Objects. == and <= operators using C++ program. How will you access an element from a two-dimensional array? Implement a program that multiplies two matrixes and stores the result in third matrix. ___ (or) } object1= object2 symbol object3. Explain the elements of object oriented programming. d) Number of operands cannot be changed.runtime polymorphism. A/M’11-4M. A/M’11-8M. Operator can use to define special member function of a class is called operator overloading. How does a C++ type string differ from C type string? Explain. Give the syntax and its uses of control statements. N/D’10-6M 16. Syntax: Definition Part: Calling part: return_type operator operator_symbol(args) symbol Object1. { WWW. a>b. ii) Binary operator overloading: Binary operators have the two operands. a<b. Unary operators are: Unary -. another object works conversely. a%b. WWW. ->*) 4) Sizeof operator (sizeof()) 5) Pointer to member declarator(:: *) Types of overloading: i. Because of updated after value is used.COM V+ TEAM . ++. In unary operator overloading no arguments need in definition part. Overloading these two operators memory allocation for members of the class. . Assignment operator overloading i) Unary operator overloading: UQ: How many arguments are required in the definition of an overloaded unary operator member function? (M/J’13) Unary operator can take only one operand and process it. a>=b. The data member of the first object is accessed without using “dot” operator. Binary operators are: (a-b. Overloading with friend function v. a+b. New and delete operator overloading iv. Syntax: Definition Part: Calling part: retutn_type operator operator_symbol() Symbol object_name. a==b) Syntax: Definition Part: Calling part: retutn_type operator operator_symbol(class_name object) Obj1=obj2 symbol obj3. a<=b. Unary operator overloading ii.VIDYARTHIPLUS. Binary operator overloading iii.. { } Limitations of increment/decrement operators: Postfix increment/decrement code not affected. a/b. { ___ ___ } iii) New & delete operator overloading: New & delete are used for allocating & de-allocating memory dynamically. This operator overloading using two operators: new & delete Syntax: New: Definition Part: Calling part: void * operator new(size_t item) Pointer_Obj1=new classname(). { ___ ___ } Delete: Definition Part: Calling part: void operator delete(void *p) delete pointer_Obj1.*.COM 1) Conditional operator (?:) 2) Scope resolution operator (::) 3) Class member access operator (.VIDYARTHIPLUS. The first object as an implicit operand and second operand must be passed explicitly. a*b. -- Take unary minus symbol can change the sign of the number. Stream operator overloading vi. unary +. Assignment operator is symbol denoted by “=”. { (or) ___ Obj1 symbol obj2.COM ___ delete p. } Cout: Definition Part: Calling part: friend ostream & operator <<(ostream &os. WWW. } vi) Assignment operator overloading: It acts as the copy constructor.classname &obj) Cout<<Obj1. Class member access operator -> d. Subscripting operator [] 2) It requires two arguments. it must be overloaded as a global function. { ___ os<<obj. both must be global functions. Similarly. overloaded >> has left operand of istream & Thus.variable. Assignment operator = b.arg2) { ___ ___ } }.VIDYARTHIPLUS. return os.VIDYARTHIPLUS. Assignment operator another name is “copy” operator. v) Stream operator overloading: Left operand of type ostream & Such as cout object in cout << classObject To use the operator in this manner where the right operand is an object of a user-defined class. Syntax: Definition Part: Calling part: Class classname Obj1=obj2 symbol obj3.classname &obj) Cin>>Obj1. Syntax: Definition Part: Calling part: WWW. { ___ is>>obj. } iv) Overloading with friend function: Operator overloading can be do with the friend function. Rules: 1) Some operators cannot be overloadable with friend function: a.variable. return is.COM V+ TEAM . ___ friend operator operator_symbol(arg1. Syntax: Cin: Definition Part: Calling part: friend istream & operator >>(istream &is. Function call operator () c. stream.dept<<"\t"<<n1. Now allocate memory } }. assignment Operator overloading #include<iostream.Dept.m3.m3. is>>n1.M3:senthil void main() it 555 WWW.M2.COM V+ TEAM 44 33 22 .M3:". return is. } friend ostream & operator <<(ostream &os. float avg. unary.VIDYARTHIPLUS.dept[10].m1>>n1.rollno>>n1. delete.M1.h> #include<string. OUTPUT: m3+=10.m2>>n1.lname[20].result[10].m1<<"\t"<<n1. int rollno.m3.VIDYARTHIPLUS.m2.new1 &n1)//stream operator overloading with friend function { cout<<"\nEnter the Fname. Enter the Fname. os<<n1.Dept. cout<<"\nAfter join the FName and LName:"<<fname<<endl.rollno<<"\t"<<n1.total. } void operator -())//Unary operator overloading { m1+=10. binary. return os.fname<<" "<<n1. void * operator new(size_t s)//new operator overloading { void *t=new size_t(s).M2. } friend istream & operator >>(istream &is.M1. WWW.h> #include<conio.dept>>n1. return t.n1. } new1 operator +(new1 &n1)//Binary operator overloading { strcat(fname. else { cout<<"\nNow allocate memory". delete p. m2+=10.h> #include<ctype.lname). } } void operator delete(void *p)//delete operator overloading { cout<<"\nNow de-allocate the memory".fname>>n1.Rollno. { ___ ___ } Example: //new.new1 &n1) { cout<<"\nFname\t\tDept\tRollno\tM1\tM2\tM3"<<endl.m1.h> class new1 { public: char fname[20].COM void operator =(classname obj) Obj1=classname(obj2). return n1.m2<<"\t"<<n1.Rollno. if(!t) return NULL. cout<<"\nTotal="<<total.//Assignment operator overloading cout<<n5. void get() { cout<<"\nEnter the 3 Marks for Class1:".total.COM V+ TEAM .//friend function declaration }. char c. cin>>m1>>m2>>m3.n2.h> #include<conio. Friend function declared anywhere in the class but have given special permission to access the private members of the class.m3. n5=n2.h> class class2. This function is given by a keyword “friend”. class class1 { public: int m1.class2).class2 c2) //friend function definition WWW.n3.lname. cout<<"\nU want to add some marks:". } friend void compare(class1. cout<<"\nTotal="<<total.VIDYARTHIPLUS."kumar"). cin>>n2.VIDYARTHIPLUS.n4. void get() { cout<<"\nEnter the 3 Marks for Class2:". total=m1+m2+m3.m3.class2). class class2 { public: int m1.m2. getch().COM { clrscr().total. strcpy(n3. total=m1+m2+m3. cout<<n2. delete n1.n5.m2. new1 *n1. Example: //friend function #include<iostream. } friend void compare(class1. //friend function declaration }. } Friend Function: UQ: What is friend function? (M/J’13) It is a function that is not a member of the class but it can access the private & protected members in the class. n1=new new1(). n4=n2+n3. cin>>c. cin>>m1>>m2>>m3. It can use in single class also more than one class is called friend class. WWW. void compare(class1 c1. if(c=='y') -n2. COM V+ TEAM . double.145. char. WWW. OUTPUT: else Enter the 3 Marks for Class1:56 cout<<"\nClass-2 is top". Syntax: Definition Part: Calling part: constructorname(classname object) Classname Obj1(obj2). Enter the 3 Marks for Class2:67 class1 o1.COM { if(c1. float x=3. Here used constructor for conversion. m=x. It is also done by using copy constructor.get(). getch(). WWW. Example: int m. Class-2 is top compare(o1. Syntax: Definition Part: Calling part: constructorname(datatype variable) Obj1= variable (or) value. Total=221 o2. } Type conversion: UQ: What do you mean by implicit type conversion? (N/D’11) One type of data convert into another type of data is called type conversion. This function is called conversion function. Syntax: Definition Part: Calling part: Operator type_name() variable= type_name(object). 87 class2 o2. 45 } 67 void main() { Total=168 clrscr(). But it stored only m=3 The user-defined type conversions can be divided into 3 types: i) Conversion from basic to class ii) Conversion from class to basic iii) Conversion from one class to another i) Conversion from basic to class: Conversion of basic datatype values to object in a class is called basic to class conversion. Basic datatypes int.VIDYARTHIPLUS.o2).VIDYARTHIPLUS.get(). The assignment operator is automatically converted to the type of left variable sometimes is called “implicit conversion”.total>c2. One class object can send as parameter to another class. 67 o1. { ___ ___ } iii) Conversion from one class to another: Assign the value of one class to another class.total) cout<<"\nClass-1 is top". { ___ ___ } ii) Conversion from class to basic: This conversion is done by casting operator function. float. These type conversions use some operator functions. void main() { clrscr(). sec=(i%3600)%60.//class to class getch().COM { ___ ___ } Example: //Basic to class.sec. hours h1. class another_hour { public: another_hour(hours h2) //class to class { cout<<"\nIncreased seconds(100):"<<h2.rsec. Total Seconds=5604 } Increased seconds(100):5704 }. cout<<"\nTotal Seconds="<<i<<endl.VIDYARTHIPLUS.//basic to class s=int(h1). hours() { hour=min=sec=0.rsec+100. class.h> #include<ctype. min=(i%3600)/60.h> #include<conio. another_hour ah(h1). etc.h> #include<string. } Templates: Template support generic programming which allows developing reusable components such as functions. hour=i/3600. 1 : 33 : 24 return s1. class to basic and class to class type conversion #include<iostream. It reduces the number of functions (or) classes in program.h> class hours { public: int hour.COM V+ TEAM . Because template perform the same operation on different datatypes.VIDYARTHIPLUS.//class to basic cout<<"\nTotal Seconds="<<s. } operator int()//class to basic OUTPUT: { Total Seconds=5604 int s1=(hour*3600)+(min*60)+sec. WWW. int s. WWW.min. It supports different datatypes in single framework. } }. cout<<hour<<" : "<<min<<" : "<<sec. h1=5604. } hours(int i) //basic to class { rsec=i. 10).i<n.VIDYARTHIPLUS.//float data type for template class T2 WWW. Syntax: template<class T> return_type function_name(arguments) { ___ ___ } Example: // Example for function template and overloading function template #include<iostream.h> template<class T1.COM Types of templates: 1.i++) cout<<a<<endl.//integer or float data type for template class T1 T2 c. } void main() { clrscr().h> template<class T> void add(T a) { T b=10. Class template 1.h> #include<conio. At least one argument must be template type. add(5. Class Template: It is used proceeding of class is called class template. } OUTPUT: template<class T> Total=15 void add(T a. getch().T b) { Total=30 cout<<"\nTotal="<<a+b<<endl. If a program contain more than one function template for same function name is called function template overload. Function template 2.3). add(5). add(20.class T2> class avg { T1 a. Function template: It is performed with the keyword “template” and list of template type arguments. It is declared in front of function definition. cout<<"\nTotal="<<a+b<<endl. add("Senthil".VIDYARTHIPLUS. } 2. Example: //Example for Class Template #include<iostream. } Total=12 template<class T> Senthil void add(char *a.3).T n) Senthil { Senthil for(int i=0.h> #include<conio.7.COM V+ TEAM . The template can use throughout the class end.b.6. WWW. disp(). a2. child class. Give a brief note on hybrid inheritance with an example. The inheritance can be achieved by incorporating the definition of one class into another. //creating object for template class in <float. Syntax: class class-name1 { __ __ } class class-name2 : access_specifier class-name1 { __ __ } Types of Inheritance: 1) Single Inheritance 2) Multilevel Inheritance 3) Multiple Inheritance. 4) Hierarchical Inheritance WWW. } Inheritance: UQ: Define inheritance. } Enter the two float numbers:3. avg<float. //creating object for template class in <int.COM public: void get() { OUTPUT: cin>>a>>b.float> a1.0. WWW.float> cout<<"\nEnter the two float numbers:". a1. Illustrate multiple inheritance with an example.6 4.VIDYARTHIPLUS. a2. New class.get(). Create a base class called vehicle and add relevant data members and functions to it. Class Template } void disp() Enter the two integer numbers:2 5 { A=2 cout<<"\nA="<<a<<"\nB="<<b. It is mainly used for “reusability” purpose.7 }. avg<int.super class.15 clrscr().5 cout<<"\n\tAverage:"<<c. 2. B=5 c=(a+b)/2.sub class. base class.VIDYARTHIPLUS. derived class. Add some properties in existing class is called inheritance. Write a main program and create objects for derived class and access the member functions.6 void main() B=4.get(). A=3.7 { Average:4. Existing class. getch(). Create derived classes that directly inherit the base class called two wheeler and four wheeler and relevant data members and functions to them. What are the types of inheritance? 1. parent class. 4. A new class derived from the existing class.float> cout<<"\nEnter the two integer numbers:". 3. //find average here Average:3. a1. Explain the different types of inheritance with sample code. Inheritance is one of important features of OOP.COM V+ TEAM .disp(). cout<<"\n\tClass Template".float> a2. WWW.VIDYARTHIPLUS.COM 5) Hybrid Inheritance 1) Single Inheritance: UQ: Write down the different access specifiers. (N/D’10) It contains only one super class, and sub class. The sub class is specialized for adding some properties. The access specifier is used for mode of access class members The access specifiers are: o Private, protected, public Syntax: class class-name1 { __ A __ } class class-name2 : access_specifier class name1. B { __ __ } 2) Multilevel Inheritance: A new class derived from existing class from that class derived new class is called multilevel Inheritance. In multilevel inheritance there is one super class, one intermediate class, and one derived (or) sub class. This act as relationship: Grandfather Father Son Syntax: class A ADD A { __ __ __ SUB B } class B : access_specifier A { __ MUL C __ } class C : access_specifier B { __ __ } 3) Multiple Inheritance: A class can inherit the attributes of two or more classes are called multiple inheritance. It allows combining the features of several existing class. It will achieve two base classes are inherit in single derived class. Syntax: class A { __ __ A B __ } class B { C __ __ WWW.VIDYARTHIPLUS.COM V+ TEAM WWW.VIDYARTHIPLUS.COM } class C : access_specifier A, access_specifier B { __ __ } 4) Hierarchical Inheritance: This type of inheritance shares the information to other classes. That means one super class, many sub class in this inheritance. Hierarchy is followed one head other classes are Labors. In this inheritance some problem will occur. So that we can use abstract class as “Super class”. Syntax: class A { MUL A __ __ } class B : access_specifier A { B C DIV MOD __ __ } class C : access_specifier A { __ __ } 5) Hybrid Inheritance: To apply more than two inheritances for design a program is called hybrid. It is also called as multipath inheritance (or) virtual base class. Example: //Example for Single, Multilevel, Multiple, Hierarchical, Hybrid Inheritance #include<iostream.h> #include<string.h> #include<conio.h> class Basic_Info { public: int regno; char name[20],dept[5]; void get_Basic_Info() { cout<<"\nEnter Regno, Name, Dept:"; cin>>regno>>name>>dept; } }; class academic:public Basic_Info { public: int m1,m2,m3,total; Basic_Info float avg; Single char result[5]; Inheritance void get_academic() Multilevel { Academic Inheritance cout<<"\nEnter the 3 Subjects marks:"; cin>>m1>>m2>>m3; total=m1+m2+m3; Personal WWW.VIDYARTHIPLUS.COM V+ TEAM Hierarchical WWW.VIDYARTHIPLUS.COM avg=total/3.0; if(m1<50||m2<50||m3<50) strcpy(result,"Fail"); else strcpy(result,"Pass"); } }; class personal: public academic { public: char address[20],blood_group[5]; long int phno; void get_personal() { cout<<"\nEnter the address, blood Group, Phone Number:"; cin>>address>>blood_group>>phno; } }; class hoppy : virtual public personal { public: char sports[20], cultural[20]; void get_hoppy() { cout<<"\nEnter the Sports and Cultural Details:"; cin>>sports>>cultural; } }; class Extra : virtual public personal { public: char event[20],prize[10]; void get_Extra() { cout<<"\nEnter the Event and Prize:"; cin>>event>>prize; } }; class display : public hoppy,public Extra { public: void get_display() { cout<<"\nStudent Details\n"; cout<<"------------------\n"; cout<<"\nRegNo\tName\t\tDept\tM1\tM2\tM3\tTotal\tAvg\tResult\n"; cout<<"--------------------------------------------------------------\n"; cout.precision(2); cout<<regno<<"\t"<<name<<"\t"<<dept<<"\t"<<m1<<"\t"<<m2<<"\t"<<m3<<"\t"<<total<<"\t"<<avg<<"\t"<<result ; cout<<"\nAddress\t\tBloodGroup\tPhno\n"; cout<<"--------------------------------------------------------------\n"; cout<<address<<"\t"<<blood_group<<"\t\t"<<phno; cout<<"\nSports\t\tCultural\n"; cout<<"--------------------------------------------------------------\n"; cout<<sports<<"\t"<<cultural; cout<<"\nEvent\t\tPrize\n"; cout<<"--------------------------------------------------------------\n"; cout<<event<<"\t"<<prize; OUTPUT: WWW.VIDYARTHIPLUS.COM Student Details V+ TEAM ------------------ WWW.VIDYARTHIPLUS.COM } }; void main() { clrscr(); display d; d.get_Basic_Info(); d.get_academic(); d.get_personal(); d.get_hoppy(); d.get_Extra(); d.get_display(); getch(); } Polymorphism: Polymorphism is a Greek term; it means the ability to take more than one form. Poly => Many Morphs =>Forms. An Operation may exhibit (display or Show) different behaviors on the types of data used in the Operation. Polymorphism divide into two types: iii. Compile Time Polymorphism iv. Runtime Polymorphism Polymorphism Compile-Time Run-Time Function Operator Virtual Pure Virtual Overloading Overloading functions function ii) Compile-time Polymorphism: It can be execute the code in compile time. It’s divide into two types 3. Operator Overloading 4. Function Overloading 3. Operator Overloading: The Process of making an Operator to exhibit different behaviors in different instance is known as Operator Overloading. Operation of addition For two numbers, the Operation will generate a “Sum”. For two strings, the Operation will produce a third String by “Concatenation”. 4. Function Overloading: UQ: What do you mean by function overloading? (A/M’11) WWW.VIDYARTHIPLUS.COM V+ TEAM VIDYARTHIPLUS. getch(). A Single function can be used to handle different number & different types of arguments. (M/J’12. Pure virtual functions Virtual Functions: UQ: Define virtual functions. Rectangle Area:200 } Rectangular Box Area:6000 void area(int b.30).20.h> #include<string. area(10. area(10. It’s divide into two types: 1. M/J’13) It is a function that is declared within a base class & redefined by a derived class.20). The function in base class is declared as virtual using the keyword “virtual” preceding its normal function.int b. WWW. Virtual Functions 2.h> void area(int a) OUTPUT: { Cube Area:1000 cout<<"\nCube Area:"<<(a*a*a).COM V+ TEAM . ii) They cannot be static members. iii) They are accessed by using pointer objects.VIDYARTHIPLUS. Multiple functions performing different task that is mean by polymorphism. } void area(int l. } iii) Run-Time Polymorphism: It can be execute the code in Run time.int l) { cout<<"\nRectangle Area:"<<(l*b). Use the same function name in both the base & derived class. Rules: i) It must be members of some class. A Particular word having several meanings depending on the context. Example: #include<iostream. WWW.h> #include<conio. A/M’11. (N/D’10- 12M) Using a Single Function name to perform Different types of tasks is known as function overloading. Polymorphism plays an important role in allowing objects having different internal structures.int h) { cout<<"\nRectangular Box Area:"<<(l*b*h).COM Write a program to find the area of different shapes using function overloading and explain it. } void main() { clrscr(). area(10). Declared virtual in a base class 3. If the class contains the pure virtual function is act as “abstract class” or “abstract base class”.h> class base { public: void display() { cout<<"\nDisplay Base". This same function name re-declared in the derived class. p1->display().COM iv) It can be friend of another class. Such functions are called “do-nothing” functions. p->display(). It is a function declared in a base class that has “no definition”. p1=&d.*p1.VIDYARTHIPLUS.h> #include<string. Used to support polymorphism with pointers and references 2. OUTPUT: void main() Display Base { Show Base using virtual function clrscr(). Display Derived base b. p=&b. p1->show(). getch(). Show Derived derived d. If the base class is abstract class. WWW. v) It is in a base class must be defined even though it may not be used. Can be overridden in derived class Example: //Example for Virtual function #include<iostream.COM V+ TEAM .VIDYARTHIPLUS. Advantages: UQ: What are the main advantages of virtual functions? (N/D’12) 1. } }. p->show().h> #include<conio. } void show() { cout<<"\nShow Derived". WWW. class derived : public base { public: void display() { cout<<"\nDisplay Derived". } Pure virtual function (or) Abstract class: UQ: What is an abstract base class? What is pure virtual function? Give its syntax. should create the pointer object for that class.*p. } }. } virtual void show()//virtual function { cout<<"\nShow Base using virtual function". h> #include<string. Example: //Example for pure virtual function (or) Abstract base class #include<iostream. getch(). } Explanation: The base class represented as the “shape” & other classes are rectangle.h> #include<conio. p=&r. triangle t. p->area(). } }. Syntax: virtual return_type function_name()=0.COM This abstract class is mainly used in hierarchical inheritance. void main() { clrscr().VIDYARTHIPLUS. class rectangle:public shape { public: void area() { cout<<"\nRectangle Area". This above example represents the hierarchical inheritance. These classes are usually outcome of generalization process which finds out common elements of class. WWW. class circle:public shape { public: Circle Rectangle Triangle void area() { cout<<"\nCircle Area". circle and triangle. circle c. }. rectangle r. University Questions: PART-A 1. p->area(). p->area(). shape *p. p=&t.h> class shape { public: Shape virtual void area()=0. What do you mean by implicit type conversion? (N/D’11) WWW. } }.COM V+ TEAM .VIDYARTHIPLUS. p=&c. Rectangle Area } Triangle Area }. class triangle:public shape { public: void area() OUTPUT: { Circle Area cout<<"\nTriangle Area". COM V+ TEAM . What are the main advantages of virtual functions? (N/D’12) 5. Give a brief note on hybrid inheritance with an example. =. Write a program to find the area of different shapes using function overloading and explain it. N/D’09. (N/D’11-8M) 6. (N/D’12-8M) 11. A/M’11-8M) 9. Describe how an object of a class that contains objects of other classes created. Explain the different types of inheritance with sample code. What is pure virtual function? Give its syntax. M/J’12) How is an exception handled in C++? (N’09. Define inheritance. How many arguments are required in the definition of an overloaded unary operator member function? 11. Write a main program and create objects for derived class and access the member functions. Write any four operators that cannot be overloaded. N/D’10) 8. (N/D’10) 12. Write down the different access specifiers. WWW. (N/D’10- 12M) Unit-3 Exception Handling UQ: What is an exception? (M/J’11. What do you mean by function overloading? (A/M’11) 9. (M/J’12-16M) 10.COM 2. == and <= operators using C++ program. Illustrate multiple inheritance with an example. (M/J’13-8M) 14. Give 3 different constructs and explain the working of them. Exception refers to unusual conditions in a program. (N/D’10) PART-B 5.VIDYARTHIPLUS. Define virtual functions. M/J’13) 7. What do you mean by operator overloading? (A/M’11-4M) 12. WWW.VIDYARTHIPLUS. What are the types of inheritance? (A/M’11. 10) What are the types of exceptions? C++ provides what type of exceptions. (N/D’12) 4. (M/J’12-16M. What is an abstract base class? (M/J’12) 6. Describe the different ways by which the public member function can be accessed. Create a class FLOAT that contains one float data member overload all the four arithmetic operators so that they operate on the objects of FLOAT. What is friend function? (M/J’13) 10. (N/D’12-8M) 8. What are the various rules for overloading operators? (N/D’11) 3.( M/J’13-8M) 13. (M/J’12. Define a class string and overload +. Create a base class called vehicle and add relevant data members and functions to it. Create derived classes that directly inherit the base class called two wheeler and four wheeler and relevant data members and functions to them. A/M’11. (N/D’11-8M) 7. (M/J’13-8M) 15. Write a program to explain unary operator overloading. (M/J’07) Explain how exception handling is achieved in C++. Asynchronous: The asynchronous exception occurs due to extend throw-1 events of the program or beyond the control of program. Synchronous 2. throw Block catch-1 3. try block (or) Construct: The main job of the try block is to find the abnormal Action statement conditions for the given statements. 3. causing an error which in turn causes the program to fail. Errors such as: Keyboard interrupts throw-2 Hardware mal functions Disk failure & so on. Catch Block (or) Construct: WWW. UQ: What is mean by asynchronous and synchronous exception?( N/D’10) Exceptions two types: 1. The general form: catch-n try { Action statement Statement-1. WWW. Under flow 4. logic is not suitable to handle the data.COM The unusual conditions could be faults. catch Block Action statement The diagrammatical representation of Exception handling models is catch-2 1. The general form: throw error obj.VIDYARTHIPLUS. The error handling mechanism of C++ is general referred to as exception handling.COM V+ TEAM . } 2. Blocks also called as constructs Those are: 1. Divide by zero The above errors are within a program. __ a __ __ Statement-n.VIDYARTHIPLUS. 1. Errors such as: 1. statement 2. Then using throw blocks it throws the exception objects. try Block 2. Over flow try Block 3. Synchronous: The exception occurs due to wrong input. (or) throw. Asynchronous. Exception handling model: throw-n This exception handling model contains blocks. Out of range 2. Throw-Block (or) Construct: This throw block is used to throw the selected exception objects. (or) throw (error obj). The general form: catch (errorobj) { Statement-1 __ __ __ __ __ __ Statement A. Then it executes the required action statement handle the exceptions. } try { fun(). Take correct actions Example: fun() { if(operation fail) throw object 1. } catch (object 2) { //take corrective action for over flow } Terminate & Unexpected functions: There are some exception handling events 1. WWW. 2. } catch (object1) { //take corrective actions for operation fail. Catch block should immediately follow the try block. . Tasks of Exception Handling: 1. } Rules: 1. (M/J’07-8M) Defining the possible exceptions excepted in a program by the user.COM __ __ __ V+ TEAM statement n.COM This catch block is used to catch thrown exception objects by the try block. Underflow(stack) Exception specification: List of exceptions UQ: Explain multiple catch statement with help of suitable C++ coding. Receive the error Info 4. General form: return type function-name (list of arg) throw (list of error objects) { Statement-1. This function should be defined before try block. __ __ __ WWW. Divide by zero 2. Array reference out of bound 3. Catch object & throw object should match. Overflow (stack) 4. if (over fail) throw object 2. Detect the exception 2.VIDYARTHIPLUS. It is implemented with functions. Inform that an error has occurred 3.VIDYARTHIPLUS. void main() { array a[size]. char) { if (y==0) throw ’z’.COM Example: //Divide by zero void test (int x. else throw 0. } } Array Reference out of bound: If any attempt is made to refer to an element whose index is beyond array size an exception raised. class array { int arr[size]. public: class range{}. else if (x!=0) throw x. int y ) throw (int. float. } void main() { try { cout <<”\n Enter a&b value:”. } catch (int m) { cout<<”The value:”<<a/b.0. cin>>a>>b. a[1]=10. // range abstract class int & operator [] (int i) { if (i<0|| i>=size) throw range(). WWW. } catch (char c) { cout <<”Division by zero”. cout<<”max array size allowed:”<<size. Example: const int size=10.b).”. try { cout<<”trying to refer a[i]………. } catch (float f) { cout <<”The value =0”.VIDYARTHIPLUS. } }.VIDYARTHIPLUS. WWW. test (a. return arr[i].COM V+ TEAM . } catch (array : : range) { cout<<”out of range in array reference”. if (x= =-1) throw ’x’..) //catch all { cout<< caught an exception”. (ii)Output stream: The destination stream receives output from the program is called output stream. A stream is a sequence of bytes. a[15]=10.) { statement for processing all exceptions } Example: void test (int x) { try { if (x= =0) throw x.( N/D’10) It is a channel on which data flow from a source to destination. cout<<”succeeded”. Input Stream Input Device Extraction >> program Output Stream Insertion << Output Device WWW. Syntax catch(….COM V+ TEAM . test(0). list its types. The stream is divided into two categories: (i)Input Stream (ii)Output Stream (i)Input Stream: The source stream that provides data to the program is called the Input stream.VIDYARTHIPLUS. WWW.COM cout<<”succeeded”. } } Catch all exceptions: Catch all the exceptions during the exception handling. test(1). } } void main() { test(-1).VIDYARTHIPLUS.. } catch (…. cout<<”trying to refer a[15]……”. } Streams: UQ: Define stream and file stream class. if(x= =1) throw 1.0. Syntax: setw(int) 2. setprecision() 3. Syntax: setprecision(int). Syntax: setfill(char). Example: (I/O Manipulators) #include <iostream.VIDYARTHIPLUS. 4. setfill() This function fill up the characters in the unused space. Stream Classes ios istream streambuf ostream Input iostream Output istream_withassign iostream_withassign ostream_withassign The class ios provides the basic support for formatted & Unformatted I/O operations. iostream-withassign add assignment operators to these classes. iostream -> Both Input & Output Stream.COM Stream classes: The C++ I/O system contains a hierarchy of classes that are used to define various streams. endl: This operator is used to end the line (or) return the cursor in the first point of line. endl 1. Figure shows hierarchy of the stream classes used for Input & Output operations. N/D’10) What are manipulators? Explain in detail various manipulators used for I/O operations with example.11-10M Manipulators are the operators in C++ that are used for formatting the output. N/D’09. WWW. istream -> for formatted & Unformatted Input. These classes are called stream classes.h> WWW. istream-withassign. setprecision() This function is used to numbers of digits to be displayed after the decimal point. ostream-withassign.VIDYARTHIPLUS.10. setw() This function is used to set the minimum field width. The various manipulators are: 1.COM V+ TEAM . setfill() 4. 3. These classes are declared in the header file iostream. setw() 2. (M/J’12. ostream->for formatted & Unformatted Output. The header file “iomanip” provides a set of functions called manipulators. I/O Manipulators: UQ: What are manipulators? (M/J’12. Syntax: cin >> variable 1>> variable2>> …….i<=3. Variable1….2 1. WWW. } for(i=0..<<item n Example: cout<<a<<b<<c<<d. cout<<1. get()->read single char input put()->Display single char output Syntax: cin. int i. The two functions to handle the single character I/O operations. Syntax: cout<<variable1(or)item1<<item2<<….d..n already declared in the starting itself.i++) { cout<<setw(i+7).h> #include<iomanip. } for(i=0.COM #include<math.get(char ch).COM V+ TEAM .i<=3. | cout.h> void main() { clrscr().VIDYARTHIPLUS. The >> operator is overloaded in the istream class. WWW. Example: int a.h> #include<conio.(N/D’10-12M) Overloaded operators >> and << We have used the objects (cin & cout) for Input & Output of data of various types.2345 SENTHIL *SENTHIL **SENTHIL ***SENTHIL Unformatted I/O operations: UQ: Explain in briefly about formatted and unformatted I/O operations with example. } OUTPUT: SENTHIL SENTHIL SENTHIL SENTHIL 1. cout<<"SENTHIL"<<"\n".23456890<<"\n". } getch(). The << operator is overloaded in the ostream class. This has been made possible by overloading the operators >> & <<.VIDYARTHIPLUS.i<=3. cout<<"SENTHIL"<<"\n".i++) { cout<<setprecision(i+1).i++) { cout<<setfill('*').b.>>variable n. cin>>a>>b>>c>>d. Item1….put(char ch).23 1.234 1. cout<<setw(i+7).c.n are may be variables or constant (or) strings [cout<<”Enter the value:”] Put () & get () functions: The classes isteam & ostream two member functions get() & put(). for(i=0. o Those functions are: 1.getline(line.write(line. Syntax: cin. precision() To specify the number of digits to be displayed after decimal point of a float value.write(name.2). Example: void main() { OUTPUT: int cl. cout. getline(): This function reads a whole line of text that ends with a new line character.COM Example: #include<iostream.get (c). getch(). Senthil Kumar cout<<”using the write function”. Senthil Kumar cout<<”enter the name:”.get(c).20).put(c). size). Senthil char c.getline(name. write(): This function display a whole line of text. while (c!=’\n’) { cout.width(int). } cout<<”total no. getch().h> void main() OUTPUT: { Input Text:Senthil int count=0. WWW. Syntax: cout. cin. width() 2. WWW.20). } Formatted I/O: C++ supports a number of features that could be used for formatting the output. of Characters:7 cout<<”input text”.VIDYARTHIPLUS. Sentil Ku cout. Using the write function cin.size). Syntax: cout. precision() 3.write(name.precision(int). width() To specify the required field size for displaying an output value.VIDYARTHIPLUS. cin. se cout. fill() To specify a character that is used to fill the unused portion of a field. 3.10).write(name. 2. of characters:”<<count. These features are include: o ios class functions o Manipulators ios class functions: o This ios class contains some member functions. Syntax: cout. Enter the name: char name[20]. } Get line () and write () functions We can read and display a line of text more efficiently using the line-oriented I/O functions “getline()” and “write()”. count ++. Total No. fill() 1.COM V+ TEAM . 1. Programs can be designed to perform the read & write operations on these files.i<=5.width(i+7).( N’09.width(i+7). Input Stream Read Data Data Input Disk Program Files Output Stream Data Output Write Data Classes for file stream operations ios istream streambuf ostream iostream WWW.23456 cout<<”SENTHIL”<”\n”.(N/D’09) Using file handling methods of C++ write a program and explain how to merge the contents of two files into one file. SENTHIL } 1. WWW.COM Syntax: cout.//width function cout<<”SENTHIL”<<”\n”. SENTHIL } *SENTHIL getch().2345 cout. for(i=0. OUTPUT: } SENTHIL for(i=0.VIDYARTHIPLUS.i<=5.10.234567890<<”\n”.23 { Precision 1.h> #include<conio.precision(i+1).//fill function 1.fill(‘*’).fill(char).i++) 1.COM V+ TEAM . int i.h> #include<math. **SENTHIL } Fill ***SENTHIL File Handling ****SENTHIL UQ: Explain file and its operations.h> void main() { clrscr().i++) { cout.//precision function SENTHIL cout<<1.11-16M) A file is a collection of related data stored in a particular area on a disk. Example: //Example for Formatted I/O #include<iostream.i<=5.i++) SENTHIL { width SENTHIL cout.VIDYARTHIPLUS.2 for(i=0.234 cout. 4.size of (b)).read (char*) &b.txt”). Name the file on the disk. out. f1>>a. The close function takes no parameter and returns no value. Using file pointer: First create the file pointer with help of fstreams. size of (variable).5}. 2. Read content from file: If you want read the content from the file using read(). WWW. f1. Read the content in two ways: 1. Syntax: File stream object.txt”). Close file operation To close the file the member function “close()” is used. Open (filename.open(“Input. b[10]. Example1: in. Using file pointer 2. 3. Example2: //Read & Write in file (or) Multiple file Handling void main() { ofstream out. Process the file (read/write) 4. Using stream object 1. Syntax: ifstream in. Next open the stream. Check for errors while processing 5.COM Open file operation Manipulation of a file involves the following steps: 1. in.2.3.close(). It returns “true” when end of file or otherwise.write((char*) &a.VIDYARTHIPLUS. of stream (or) f stream. int a[10]={1. Syntax: ifstream object-name. The file operations are associated with the object of one of the classes: if stream.mode). Example: ifstream f1. Syntax: File stream object. Next step read the file content and assign the values to local variable.read(char*) & variable.VIDYARTHIPLUS. Detect when the end of an input file has been reached by the eof() member function of ios. Using stream object: Create & open the stream object. The file can be opened by the function called “open()”. WWW. Close the file after its complete usage. Open the file to get the file pointer. 2.COM V+ TEAM . size of (a)). out.open(“input. open(“odd. ifstream in.close().read((char*) &b.txt”. fp. //(or)fp>>ch. Example: fin. ios: :binary-Binary file.close(). } in. cout<<ch. fp1. File mode is included in the “ios” operations.txt”). fp2. (ii)if (fin. for (int i=0. while (fp) { fp. ios: :app-Append to end of file. fp2.VIDYARTHIPLUS.eof()!=0) Eof()-member function of “ios” class. 5. Detecting End-of-File: (eof) Detecting eof in two ways: (i)while(fin): It returns valus “0” when reaching eof condition. fp2. 6. i++) { if (b[i]%2==0) fp1<<b[i]<<” ”.txt”). 3. ios: :in).close().open (“even.txt”).COM V+ TEAM . 7. It returns a non-zero(1) values. in. fp.get(ch). 8.open(“input. } fp. in. } fp.open (“even.open(“odd. char ch.get(ch).txt”). while (fp) { fp. if stream fp. //(or)fp>>ch. ios: :ate-Go to end of file on opening.open(“Input.COM out. 2. 4. cout<<ch. ios: :noreplace-open fails if the file already exists. } FILE MODES: File mode specifies the purpose for which the file is opened.txt”).close(). ios: :in-open file for read only. ios: :out-open file for writing only. getch(). size of (b)). WWW. cout<<”the odd file contents are:”. i<10. else fp2<<b[i]<<” “.VIDYARTHIPLUS. if the eof condition.close(). fp1. ios: :trunc-Delete the contents of the file.close(). Some file modes and meaning of file modes: 1. ofstream fp1. ios: :nocreate-open fails if the file does not exist. cout<<”the even file contents are:”. WWW. cout<<”at the end”. reference-position).open(“stu.seekg(0.getline(data. in.tellg()-Current position of get pointer S2. seekg()-get pointer location for “reading” 2.seekg(offset.COM V+ TEAM .tellp()-Current position of put pointer Example: (Random Access) void main() { ifstream in.ios::beg). namespace ns1 WWW.VIDYARTHIPLUS.close().seekg(-14. and functions under a name. (1) seek (2) tell (1) Seek: The seek operation is using two functions: 1. cout<<data.h> using namespace std. Example: #include<iostream> #include<stdlib.VIDYARTHIPLUS.getline(data. in.COM RANDOM ACCESS: UQ: Explain the concept of random access in file and namespace. we must be able to reach at any desired position inside the file. reference-position).txt”). 3) Bad()-returns true(1) if an invalid operation. Namespaces: UQ: What is standard namespace? How it differs from other namespaces?(N/D’09) What are the ways of using namespaces? (M/J’12) Namespace avoids the name conflict problem.seekp(offset. objects. in. Example: S1. WWW. variables. To access the variables from outside of namespace use scope resolution operator(::). char data[80]. in.A/M’06-16M) While performing file operations.80). Namespaces are used to group the entities like class. end or current position If can be specified ios: :beg->for beginning ios: :end->for end ios: :cur->for current (2) Tell: This function tells us current position. (M/J’07. where each sub-scope has its own name. cout<<data. The keyword “using” is used to introduce the namespace being used currently. For this purpose there are two operations used. Where offset-any constant specifying location Reference. in.05.ios::end).80). seekp()-get pointer location for “writing” Syntax: Object. in. The namespaces help to divide global scope into sub-scopes. Object. 2) Fail()-returns true(1) when an input (or) output operation has failed. } Error handling during file operations: UQ: What are the error handlings functions used in file systems?( N/D’10) 1) Eof()-It returns value(1) if end-of-file.position-position is beginning. cout<<”initial statement”. (N/D’09) List out and explain string functions in ANSI. Using a Constructor: Ex: str1(“Kumar”). They cannot be assigned.11-12M) Need for String Objects: Strings are implemented in “C” as character arrays. However. which is used to perform string based I/O operations. Function Name Description WWW. } namespace ns2 { char a[]="hello". Operations on strings: 1. } int main() { cout<<ns1::a<<endl.08. #include<iostream> using namespace std. b.VIDYARTHIPLUS. character arrays have a few limitations when treated as strings: 1. system("PAUSE"). WWW. cout<<ns2::a<<endl. Which uses any entity declared in iostream. 2.(A/M’05. return 0. 3. Finding characteristics of a string. They cannot be compared like other variables. (or) str1=”Kumar”. it is treat as separate objects. 4. iii. std namespace cannot be extended. All the library files declared within std namespace. Appending substring to a string. e. ANSI String Objects: UQ: Give the possible operations on string objects. 2. Swapping two strings. Creation of strings.COM V+ TEAM . 3. Finding location of substring. Erasing a string. 2. Creation of strings: A string object can be created in three ways: i.VIDYARTHIPLUS. b. } Std Namespace: It is a namespace where the standard library functions are defined. Copy and Comparison function. Inserting a specific substring. Substring operations: Various functionalities provided by string class are Sno. Replacing specific characters. Therefore.(A/M’06) Explain the ANSI string objects with example. That’s why in the C++ program the std namespace is declared as. ii.COM { int a=5. Concatenation. d. Using initialization: Ex: string str2=str1. Substring operations: a. Defining a string object in normal way: Ex: string str1. 5. Initializing with another string is not possible. Operations involving multiple strings: a. Find the location at the character. 1. Here used sstream library file. c. C++ overcomes by providing string objects. //insert cout<<"\nAfter insert:" <<str1.str2("India").3). str1. .//string datatype str1+=str2. int main() { string str1("Hello").str3). ==.insert(5. Function Name Description 1) size() It returns size of the string 2) empty() If string is empty it returns “true” that means 1 3) max_size() It return maximum permissible size of string 4) resize() It resizes the string by the number of supplied as argument 5. WWW. return 0.COM V+ TEAM .VIDYARTHIPLUS.COM 1) append() Appending one string to another 2) at() Get the char at specific location 3) find() Searching 4) insert() Inserting char or string 5) replace() Replaces char or string 3. system("PAUSE"). Erasing a string.//size string str4=str1. (M/J’12-16M) WWW. Sno.substr(2. cin>>str3.swap(str4). . cout<<"\nMaximum Size of str4:"<<str4.str3.erase(5. >.//erase cout<<"\nAfter erase of 6Characters:" <<str1. Function Name Description 1) + Concatenation of two strings 2) = Assigning one string to another 3) <. } OUTPUT: Enter the string:Greate After insert:HelloGreateIndia Empty :0 After erase of 6Characters:HelloIndia Size of Str1:10 Find substring in Str4:llo Maximum Size of str4:1073741820 After swap: string2:llo string4:India Press any key to continue . Standard Template Library(STL) UQ: What is Standard Template Library? List the components of STL.//concatenation cout<<"\nEnter the string:".//substring cout<<"\nFind substring in Str4:" <<str4.VIDYARTHIPLUS.empty(). Function Name Description 1) erase() Removing the specified char Example: #include<iostream> using namespace std.//swap cout<<"\nAfter swap:" <<"\nstring2:"<<str2 <<"\nstring4:"<<str4<<endl.//Max Size str2.size().max_size(). cout<<"\nSize of Str1:"<<str1. Finding characteristics of strings: Sno.6). cout<<"\nEmpty :"<<str1. Operations involving multiple strings: Sno.//find Empty or not str1. != Comparing between two strings 4) swap() Swapping two strings 4. COM V+ TEAM .VIDYARTHIPLUS. Block diagram of STL Algorithm1 Iterator1 Container Iterator2 Object1 Object2 Algorithm2 Object3 Iterator3 Algorithm3 Container: o Container is an object that actually stores data. o STL implemented by template classes & therefore to hold different types of data.COM The Standard Template Library(STL) is collection of well structured generic C++ classes (templates) and functions. Element0 Element1 Last Element Iterator Begin() End() The Sequence container provides three types of applications: WWW. Already programmed functions are consisting in STL. o It is a way data is organized in memory. o Container categories into 3 groups. WWW. Those are: 1) Sequence container 2) Associate container 3) Derived container Container types in represent block diagram. Container Sequence Derived Associate container container container Vectors Stack Set Deque Queue Multiset List Priority queue Map Multimap 1) Sequence container: It store elements in a linear sequence like as line.VIDYARTHIPLUS. Basic STL consist of three components: 1) Container 2) Algorithms 3) Iterators These three components works in conjunction with one another. Each element is related to other elements by its position along the line. set_union(). Allows rapid look-up. Permit direct access to any element.VIDYARTHIPLUS. 3) Derived container: The derived containers are created from sequence containers. 2. rotate(). Set algorithms: It is used to do some set operations: Set_difference(). WWW. mismatch(). Relational algorithms: Relational algorithms used to do some relational operations. 3. set_intersect(). min(). There are four types of associative containers: SNo. forward(). o Some operations of iterators: Input().10) 3. countif(). etc. merge().VIDYARTHIPLUS. Multimap For storing key with value pairs which one key may be associated with more than one value. Write the syntax for that. find_if(). output(). University Questions: PART-A 1.N/D’09. What are the ways of using namespaces? (M’12. They are not sequential.M/J’12) 2. WWW. Priority Queue A priority queue. List A bi-directional linear list. equal(). 3. o They are often used to traverse from one element to another. Container Description 1. Iterators: o Iterators behave like pointers and are used to access container elements. Relative or non-mutating algorithms 2. Algorithms: o Algorithms are functions that can be used for processing their contents. etc. Container Description 1. Vector A dynamic array allows insertions and deletions at back. Sorting algorithms 4. (N/D’10) 5. find(). Allows insertions and deletions at both ends. Mutating algorithms: The summarized operations of mutating algorithms: Copy(). bi-directional(). sort_heap(). max().(LIFO) 2. How is an exception handled in C++? (N’09. 4. reverse(). Multiset For storing non-unique sets. Container Description 1. swap(). What is mean by asynchronous and synchronous exception?( N/D’10) 6. What are the types of exceptions? C++ provides what type of exceptions. 2.. 4. Queue A standard queue. Relative or non-mutating algorithms: This algorithm has some operations: Count(). max(). for_each(). Deque A double ended queue. min(). Etc.COM SNo. 5. fill(). generate(). 3. What is an exception? (M/J’11. Relational algorithms 1. 2) Associative container These are designed to support direct access to elements using keys. mismatch(). Mutating algorithms 3. first element out is always the highest priority element. Allows insertions and deletions anywhere. etc. etc. (M/J’07) 4. partial_sort(). Each key is associated with only one value. etc 2. The derived containers are: SNo. Set algorithms 5.(FIFO) 3. Equal(). Stack A standard stack. equal().COM V+ TEAM . Define multiple catch statements. replace(). Sorting Algorithms: Sorting algorithms are processed various methods: Binary_search(). o Although each container provides functions for its basic operations. o STL algorithms based on the nature of operations and types of algorithms: 1. Map For mapping unique key with value pairs. random(). remove(). Set For storing unique sets. (A/M’08. Virtual base class. Portable & Platform Independent 7. N/D’11. 3. List out and explain string functions in ANSI.11) 8. Dynamic virtual machines – objects – classes 6. High performance – Javadoc – packages – 8. This language was initially called “Oak”&renamed as “Java” in 1995. What are manipulators? (M/J’12. (M/J’12. 11. 5. What are the error handlings functions used in file systems?( N/D’10.COM 7. list its types. This means that we need not wait for the application to finish one task before beginning another.08. Java like as C.11) 6. Operator overloading. Secure 1. Using file handling methods of C++ write a program and explain how to merge the contents of two files into one file. Structure & Union. Simple: Java is a simple programming language. Explain in briefly about formatted and unformatted I/O operations with example. What is container? What are the three types of containers? Explain.(N/D’09. go to statement. Multithreaded: Multithreaded means handling multiple tasks simultaneously. N/D’10 8. Explain file and its operations. 13. Multithreaded Introduction to JAVA . 10. 14. Explain the concept of random access in file and namespace. Simple 2. 4.10. (M/J’12.11 4. Explain how exception handling is achieved in C++.(N/D’10) 7.(A/M’05. bytecode.( N’09. Define stream and file stream class. Java supports multithreaded programs. Dynamic: WWW. Discuss in detail about Standard Template Library. (M/J’07) 2. The object model in java is simple & easy to extend. Object oriented Syllabus: 3. (M/J’07. But java there is not use Pointer. WWW. What is standard namespace? How it differs from other namespaces?(N/D’09. 5.VIDYARTHIPLUS. Explain the ANSI string objects with example. N/D’09. Distributed UNIT IV 4.VIDYARTHIPLUS. 5.M/J’12) 3. 12.(A/M’06) PART-B 1. 2. Robust Arrays – Strings 9. What is Standard Template Library? List the components of STL 15. Give the possible operations on string objects. 9. Object Oriented: Java is a true Object Oriented language. Give 3 different constructs and explain the working of them.(N/D’09.05. Explain the various features of Java in detail (N/D’11-10M) 1. Explain multiple catch statement with help of suitable C++ coding. C++ Language.(M/J’12). Distributed: Java is designed as distributed language for creating applications on networks. Java features: UQ: List the features of java.10.COM V+ TEAM . What are manipulators? Explain in detail various manipulators used for I/O operations with example. This can be achieved by Remote Method Invocation (RMI). Java must be at least one class present.A/M’06) UNIT-4 Introduction to Java Java was invented by James Gosling at Sin micro systems in 1991.( N/D’10. Interface (GUI). the application is running on. pointers. Secure: UQ: How is Java more secured than other languages? (M/J’13) Java enables construction of virus free.COM Java is more dynamic language than C. C++ is simple to use & implement. Java is platform independent. JAVA is safe & more reliable. Robust: It has strict compile time & run time checking for datatypes. (A/M’11) Documentation section Package statement Import statement Interface statement Class definitions Main method class { Main method definition } Simple JAVA program: //Example simple java program import java. 9. Scripting language. Java does not support multiple inheritances. Java can be compiled using unique compiler. C++ can be compiled with variety of compilers. Graphical User 2.VIDYARTHIPLUS. Reading or writing file without permission. 8. Interface (GUI). Java servlet can be created which can interact 3. class Simple { public static void main(String args[]) { System. C++ does not support multithreading. 2. Difference between C++ and JAVA: UQ: Can we write a JAVA program without class? Justify your answer. Graphical User Java supports multithreading.COM V+ TEAM . C++ supports multiple inheritances. Database handling using C++ is very complex. Java ensures portability in two ways: 1. tamper free system. 4. 7. The C++ is platform dependent. 7. Java programs can be executed on variety of systems. (N/D’10) Sno. C++ JAVA 1. Scripting language.C++. The sizes of primitive datatypes are machine independent. It is designed as garbage collected language. JAVA program structure: UQ: Give the JAVA program structure. 5.VIDYARTHIPLUS. 6.out. Templates. Java must be at least one class present.*. 6. Portable & Platform Independent: 1.io. Templates. with the database. C++ we can write a program without a class. High performance: The bytecode can be translated on the fly into machine code for particular CPU. WWW. 2. } } Compilation & Output: WWW. Java compiler generates bytecode instructions that can be implemented on any machine. pointers. Libraries can freely add new method & instance variable without any effect.println("It is simple JAVA Program"). WWW.out.DataInputStream.i.io.println("Enter the limit:").COM C:>javac Simple. The Armstrong Numbers are: j++. import java. while(i>0) { OUTPUT: r=i%10.*.in). System.COM 371 V+ TEAM 407 .VIDYARTHIPLUS.println("Program for Armstrong Numbers"). 1 } 153 370 WWW.io.*.out.io. i. try { DataInputStream din=new DataInputStream(System.println("It is simple JAVA Program").println("The Armstrong Numbers are:").VIDYARTHIPLUS.-6M) //Example java program for Armstrong Numbers import java. max=Integer. class inside { void display() { System.println(j). } } Compilation & Output: C:>javac Simple.parseInt(din.java C:>java Simple It is simple JAVA Program UQ: Write a program to print the first n Armstrong numbers (accept n as command line argument) (N/D’11- 6M) How will you access class members in JAVA? (A/M’11.max.j=1.out. System.java C:>java Simple It is simple JAVA Program //Example another simple java program import java.out.display(). System. Program for Armstrong m=m+(r*r*r). m=0. Enter the limit: } if(j==m) 500 System. class armstrongno { public static void main(String args[]) throws IOException { int r.m. } } class Simple { public static void main(String args[]) { inside i=new inside(). Numbers i=i/10.readLine()).out. while(j<=max) { i=j. super. or three operands operates on them to produce a result. Separators 1. Arithmetic operators (+. Literals 4. An operator performs a function on one. Identifiers 3.. Assignment (=) 5. (N/D’10) Smallest individual units in program are knows as tokens.!=) 3. Floating point literals 3. Keywords 2. byte. methods. interface. 2. 2. import.>. Some keywords: final.VIDYARTHIPLUS. Identifiers: UQ: Enumerate the rules for creating identifiers in Java. Java language specifies five major types of literals. Operators 5. 3. |.%) 2. They can have alphabets. Character literals 4. Keywords: Keywords are an essential port of language definition. Integer literals 2. Logical (&&.>=. digits. Operators: UQ: What are the various types of operators in JAVA? (A/M’11-4M) Operators are used in programs for manipulating data and variables. package. They are: 1.VIDYARTHIPLUS. They are used for naming class. Java language has reserved 50 words as keywords. The Java programming language has one ternary operator ?: Types of operators: 1. interfaces of thee program.out.(dot). instance of] 5. boolean. Keywords are must be in lower case letters. 4.println(e). underscored & dollar sign. variables. extends. They can be any length.||. objects. two.-. Example: ++ is a unary operator that increments the value of its operand by 1. Upper case & lower case are distinct.!) 4.COM V+ TEAM . WWW. Separators: WWW. Example: = is a binary operator that assigns the value from its right-hand operand to its left- hand operand. labels. !) 8. } } } JAVA Tokens: UQ: List few tokens available with JAVA. An operator that requires two operands is a binary operator. Java language includes five types of tokens: 1. Relational (<. native. String literals 5.--) 6. A ternary operator is one that requires three operands. Literals: Literals in java are sequence of characters that represent constant values.==. An operator that requires one operand is called a unary operator. 3. Increment & decrement (++.*. implements. packages. Boolean literals 4.<=.COM } catch(IOException e) { System. Special [./. Bitwise (&. Conditional (?:) 7. etc. Rules: 1. They must not begin with digit. (M/J’13) Identifiers are programmer-designed tokens. Parentheses()--. Semicolon. II. Comma. Storing the local variables of the method. The Java Application programming Interface (API) Myprogram. M/J’12) 1.for end of statement 5.separate the variables. Character constants 4. It is virtual machine that can execute Java byte code. Garbage collected heap 3. That does not change during the execution of program. Brackets[]--. Registers 4. WWW. The java platform is a software only platform that runs on other hardware based platforms. Operating system is called platform. Some separators: 1. WWW. 11. The stack The stack is performing following functionalities: I.COM V+ TEAM . Stack 2. String constants Java virtual machine (JVM) UQ: What are JVM and JDK? (N/D’10.for array 4.VIDYARTHIPLUS.for creating blocks 3. Real (or) floating point constants 3. Method area Program Counter Vars Frame Optop (PC) Registers Garbage Method Stack Collected Heap Area 1. The Java virtual Machine (JVM) 2.COM Separators are symbols used to indicate where groups of code are divided & arranged.--.for function 2. objects… Constants: UQ: Define constant in JAVA. (A/M’11) Constants are referring to fixed values.java Compiler Interpreter Application Programming Java Interface(API) Platform Java Virtual Machine(JVM) Hardware-based Platform Java virtual machine is a set of software & program components. Types of constants: 1.VIDYARTHIPLUS. Integer constants 2. Java platform components: 1. Braces{}--. JVM is divided into several components: 1. Java platform: A platform is the hardware or software environment in which a program runs.--. Storing various arguments passed to the method. jar file. Java source Java Java Network program compiler (or) bytecode filesystem Bytecode JVM Java Operating byte code Verifier System Java Just In Time (JIT) compiler The programs that are running on JVM must be compiled into a binary format which is denoted by . The vars-point to the local variable in the stack. The bytecode is to be executed by Java Runtime Environment which is called Java Virtual Machine (JVM). Registers: A stack performs manipulation of data with the help of vars. This verification helps to prevent the crashing of host machine. frame & optop.class.the stack operations are pointed. 3. Class level comments 2. Java supports automatic garbage collection mechanism. There are two types of comments: 1. WWW. Example: /** *@ author Kumar * The employee class contains salary of each employee */ WWW. 2. Java doc is a special format of comments. It is used in most JVM’s today to achieve greater speed. Java Doc: UQ: Explain about Java Doc in detail. The bytecode verifier verifies all the bytecode before it is executed.COM III. Byte code: Bytecode is an intermediate form of java programs. Using program counter (PC) JVM keeps track of the currently execution instruction. 4. Method area: This area stores the byte code of various methods. Bytecode consists of optimized set of instructions that are not specific to processor. (N/D’10-12M) Java doc is a standard way to document your java code.VIDYARTHIPLUS. Keeps track of method being invoked.point out the current byte code instruction. There can be multiple threads of a single process & all these threads can access the method area at a time. Class level comments: The class level comments provide the description and purpose of the classes. JVM is also called Interpreter. it is returned to this heap area. The JVM executes it or using a Just-In-Time (JIT) compiler.COM V+ TEAM . Garbage collected heap: The memory for objects can be allocated from this heap area. Optop.VIDYARTHIPLUS. When memory of these objects gets free. Some times for easy of distribution multiple class files are packaged into one . Frame. There are some utilities that read the comments & generate HTML document based on the comments. Member level comments The java doc comments start with /** and end with */ Example: /** This is java doc comment */ 1. COM public class Employee { =// Employee class code } 2. WWW. } /** *@ param int no-of-days-worked *@ param int payscale is for payment scale */ public void setsalary(int no_of_days_worked.VIDYARTHIPLUS. } /** *This method returns the salary *@ return integer value for salary */ public int get_salary() { return amtsalary.println("Salary="+amtsalary). Member Level Comments The member level comments describe the data members. The most commonly used tags: Tags Description @author The name of author who is writing the documents.amtsalary = no_of_days_worked*payscale. System.amtsalary=0. The name of the method used in the class (or) method’s @param parameter @return The return tag of the method (or) method’s return value @throws The exception that can be thrown by the method @exception The exception thrown by a method Example: /** *@ author Kumar * The Employee class contains salary of each employee */ class Employee { /** *Employee info for knowing the salary */ private int amtsalary.COM V+ TEAM .out.VIDYARTHIPLUS. /** *Constructor defined to initialise the salary */ Employee() { this. int payscale) { this. methods & constructors used in class. } } WWW. In this type of comments special tags are used to describe the things. Constructing Javadoc information...java.html. Building index for all the packages and classes. Generating \help-doc. Generating \deprecated-list.COM V+ TEAM byte Int .java Loading source file EmpJavaDoc. Building index for all classes....html... Generating \package-frame. } } OUTPUT: L:\Programs>javac EmpJavaDoc.... Generating \package-summary...html.VIDYARTHIPLUS. Data types: UQ: Write short notes on DataTypes in Java...setsalary(10.... Generating \allclasses-frame. Along with the above mentioned tags some HTML tags can also be included in javadoc comments. (N/D’10-4M) Describe various datatypes used in Java... (M/J’13-16M) Datatypes specify the size and type of values that can be stored.7... Primitive (or) Built-In Types 2.0_02 Building tree for all the packages and classes.html..html.html. WWW..VIDYARTHIPLUS.html.. Derived (or) Reference Types Data types Primitive Derived d Numeric Non-numeric Classes Interface Arrays d char Boolean Int Floating Point WWW..COM public class EmpJavaDoc { public static void main(String args[]) { Employee e=new Employee().4500). Generating \index. e.. The variety of data types available allow the programmer to select the type appropriate to needs of the application. Generating \index-all.. Generating \package-tree.html.html. Generating \EmpJavaDoc. Generating \constant-values. Standard Doclet version 1.html..html. Data types divided into two major categories: 1.. Generating \allclasses-noframe.java L:\Programs>java EmpJavaDoc Salary=45000 L:\Programs>javadoc EmpJavaDoc. Give examples. Generating \overview-tree......html. etc.VIDYARTHIPLUS. Instance variable: They are created when the objects are instantiated & therefore they are associated with the objects. } } Wrapper class: UQ: What is wrapper class? (N/D’11) Wrapper classes are used to convert of primitive type into object of classes. Local variables Scope: The area of the program where the variable is accessible is called Scope. { Block-2 = int b=20.VIDYARTHIPLUS.COM = V+ TEAM } . etc. Command Line Arguments: UQ: What are the command line arguments? (A/M’11) Command line arguments are parameters that are supplied to the application program at the time of invoking it for execution. They take different values for each object. Character. Class variables: They are global to a class & belong to the entire set of objects that class creates.plintln (“Number of arguments”. Example: Class comline { Public static void main (String args[]) { int count=0. Class variables 3. 6 double 8bytes double f= 7 Char 2bytes char g=’a’. So that they stored in collection classes such as Vector. WWW. Set. Boolean. Local variables: They are declared & used inside methods can functions are called local variables.No Data type Size Example 1 Byte 1byte byte a=10. 3. count=args.out. r=new rectangles 2. System. Instance variables 2. Some of wrapper classes are Integer.length. Float. 5 Float 4bytes float e=34. 3 Int 4bytes int c=32507. { Block-1 int a=10. WWW. 1. Scope of Variables UQ: How will you identify scope of variables in JAVA? (A/M’11) Java variables are classified into three kinds: 1.75f. 4 Long 8bytes long d=343210. 2 Short 2bytes short b=1070.COM S. Rectangle r1. They are not available for outside of method definition. count. Only one memory location is created for each class variable. List. The development tools are part of the system known as Java Development Kit (JDK). Symbol=> ? : Which can be thought of as short hand for if-else statement. Ex: Result = value<50? “fail” : “pass”. Branching (or) Jump 1. Types of control statements: 1. Decision making (or) Selection Statements: Types of decision making Statements. 2. If …. When these two conditions met a widening conversion takes place. The destination type is larger than or equal to source type. Nested if …. 1.COM V+ TEAM .else 3.VIDYARTHIPLUS.COM JDK (Java Development Kit): UQ: What are JVM & JDK? (N/D’10. Looping (or) Iteration 3. WWW. It is also has three operands so that called ternary operator. The source & target types are compatible. Simple if: If statement in which one or more statement is followed by this statement Syntax: if(condition) Statement Example: If (a>b) { System. JDK is a collection of tools that are used to developing & running java programs.out. Switch case 1. Example: Byte bt=100.VIDYARTHIPLUS. (N/D’11-6M) Programmers can take decisions in their program with help of control statements. Widening conversion all numeric types are compatible with each other.println (“A is big”) } WWW. 11. Widening Conversion UQ: What is meant by widening conversion? (N/D’10) An automatic type conversion will take place if the following conditions are met: 1. Java Control Structures: UQ: Write the syntax & explain the various Java control & looping statements. Simple if 2. Decision making (or) selection 2.else 4. Int x=bt. M/J’12) Java environment includes a large number of development tools & hundreds of classes & methods. Ternary Operators: UQ: What is the use of ternary operator? (N/D’10) It is also called as conditional operator. else is have one or more if…else statement ….out.COM V+ TEAM .out. It provides select the operation with the proper condition.VIDYARTHIPLUS. Else Statement: A if ….else: Given Condition is true execute the if block. Nested if ….println(“A is big”). This break statement used to break the each set of operation. Syntax: if(condition) { __ __ __ } statement-1 } else { __ __ __} statement-2 } Example: if(a>b) { System.out. else System. if(condition1) { if(condition 2) { Statement2 } else { Statement3 } } else { Statement 4 } Example: if(a>b) if(a>c) System.VIDYARTHIPLUS.out. } else { System. } 3.println(“B is big”).println(“B is big”). WWW.is called nested if….COM 2. If …. 4.else statement. In the switch – case statement has the “break” statement. switch case statement: The switch statement is multiway branch statement.println(“c is big”).out.println(“A is big”).out. else System. condition is false execute the else block. else if(b>c) System. WWW.Println(“B is big”). i<=n. It has the only condition checking expression. It terminates a statement 2. While 2. and Increment/decrement operation. Looping (or) Iteration statements Iteration (or) Looping statements enable program execution to repeat one or more statements. continue. break. WWW.COM Syntax: switch (expression) { case value1: Statement-1. It is returns from the method. default: Statements.COM V+ TEAM . conditional checking. (ii) Continue: Some of the code not execute in the program just jump the line of codes. break. Do-while statement: There is only difference b/w while & do-while that while loop first evaluates the condition and if it is true then only the program enters into the loop. WWW. While statement: The while loop is most fundamental looping statement. These statements are: break.VIDYARTHIPLUS. Java’s Looping Statements are: 1. In case of do-while will enter into the loop without evaluating condition for the first time. i++) { } 4. break. Jump statement: These statements transfer control to another part of the program. Syntax: for (i=0. (i) Break: The break statement has two uses: 1. } 2. It repeats a statement (or) block while its controlling expression is true. Do-while 3. For 1. case value2: Statement-2. 3. and return.VIDYARTHIPLUS. For: There are three portion is used. (iii) return: 1. Those are initialization. It can be used to exit a loop. Syntax: do { ___ ___ }while (condition). These statements repeatly execute the same set of instructions until a termination the condition. Syntax: While (condition) { ___ ___ / / body of the loop } 2. } } Main Program: import mypack. Steps for creating a package: Step1: The above program create saved as file name “Balance. WWW. 500. The name of the package should be written as the first statement in program. Step6: Compile the java program like as “javac Account. Package can create with keyword “package”. Example: Package Program: package mypack. M/J’12. Packages provide a way to “hide” classes. b1.java”.40/mypack>javac Balance.println(name+”:Rs.COM 2.00). class Account { public static void main (String args[]) } Balance a1= new Balance (“Senthil”. Packages also provide a way for separating “design” from “coding”. Multiple hierarchies of packages: package pkg1. Step4: Now create other java file outside of the package directory.”+bal). public class Balance { String name.pkg3. Java classes can be grouped into the packages. Explain about Java API packages. 12. } public void show () { System. N/D’10. Control is returned back to the caller of the method. 11. Benefits: The packages of other programs can be easily reused.show(). a1.2000.*.*. Syntax: package name-of-the-package.java”. Step5: Import the package in our java program like as “import mypack. In packages.”.VIDYARTHIPLUS.java” Step2: The file must store in the folder “mypack” as the package name. float bal. bal = b.00).VIDYARTHIPLUS. Java program can import the system packages.Balance. Balance b1= new Balance (“Kumar”. classes can be unique compared with classes in other packages. 13-16M) Packages are container for classes. A/M’11) Explain how to design a Java package with an example. Step7: Run the java program like as “java Account”.Balance. Step3: Compile the program “C: /jdk1. } } WWW. float f)) { name = n. public Balance (string n.COM V+ TEAM . (A/M’11.show(). The package name must be the same as the directory (or) folder name. Packages: UQ: What do you mean by package in JAVA? (N/D’10.Pkg2.out. public class ClassA { public int rollno. } public void displayB() { System. } } Output: E:\j2sdk l. System.500.ClassA.2000.COM OUTPUT Senthil: Rs. System."Raja").out.println(" Total: "+total). ClassA objectA=new ClassA(1001.int m2) { mark1=m1.out. public int mark2.java Import the Packages College and student import student.00 Another Example: I ) Package student package student.mark2. total=objectB. public String name.java II) Package college: package college. public class ClassB { public int mark1.println("Name :"+name). class PackageTest { public static void main(String args[]) { int total. } } WWW.4\bin\college>javac ClassB.VIDYARTHIPLUS.out. mark2=m2. objectA.println("Mark 2 :"+mark2). } public void displayA() { System. public ClassA(int rl. ClassB objectB=new ClassB(90. } } OUTPUT: E:\j2sdk l.00 Kumar: Rs. WWW. objectB. import college.String nl) { rollno=rl.println("Mark 1 :"+mark1). name=nl.displayA().out. System.ClassB.out.COM V+ TEAM . public ClassB(int m1.VIDYARTHIPLUS.100).println("Roll Number : "+rollno).4\bin\student>javac ClassA.displayB().mark1+objectB. util 5. Syntax: WWW.net 3. For example- Specify it as import java. Here*means all the classes from java. Default Constructor 2.VIDYARTHIPLUS. WWW. Parameterized Constructor 3. Constructor automatically called whenever object is created. The specific class that needs to be used in our program from a particular package then it can be mentioned in import statement. Types of Constructor: 1.applet package contains all necessary classes and interfaces are required for handling applets.io 2.VIDYARTHIPLUS. Java. Java.net. Java.io This package provides useful functionalities for performing input and output operations through data streams or through file system. Java.COM V+ TEAM .applet The java.java E:\j2sdk l. Java. Some of the useful packages are enlisted as below: 1. It is used to initialize the variables. Multiple Constructor or Constructor Overloading 1) Default constructor: Default constructor is the basic constructor. Java. It just initializes the variables. (A/M’11-8M) Constructor is a special member function. Class name and function name are same.awt This package contains all the interfaces and classes that are required for creating the graphical user interface (GUI). Java. Copy Constructor 4. Constructor: UQ: Construct a class with constructor in JAVA to print a pay slip of an employee.4\bin>java PackageTest Roll Number :1001 Name :Raja Mark 1: 90 Mark 2: 100 Total: 190 Java API or Core packages: Various classes and interfaces from java library packages using the import statement.applet Java.awt 6.*. system properties are stored in util package. event model. Java.COM OUTPUT: E:\j2sdk l.net package. Java. It is non parameterized constructor.lang 4. Java.lang This package provides core classes and interfaces used in design of Java language. Java.util Some commonly used utilities are random number generation. date and time facilities.4\bin>javac PackageTest.net This package is for providing the useful classes and interfaces for networking applications which are used in sockets and URL. int b)//Parameterized Constructor { length=l. class consr { int length. Parameterized. } consr(int l. The constructors that can take arguments (or) parameters are called “Parameterized constructor”.//Explicit passing 4) Multiple Constructor or Constructor Overloading: Any program having more than one constructor (Default.out.length. 2) Parameterized constructor: Passing arguments (or) parameters to the constructor function when the object is created. breath. 3) Copy constructor: Copy constructor is used to declare and initialize an object from another object. System.//Implicit passing classname object3=object2. WWW.*.VIDYARTHIPLUS.println("\n Length = "+length + " Breath = "+breath). We can call the Parameterized constructor using two ways: i. Copy.COM class classname { classname() { __ __ } }. } consr(consr s)//Copy Constructor { length=s. breath=b.println("\n The Area of the Rectangle="+(length*breath)).VIDYARTHIPLUS. } void function() { System. Implicit calling ii. breath=s. The process of initializing through a Copy constructor is known “copy initialization” Send object as parameter. WWW. Syntax: classname object1.io.COM V+ TEAM . Example: //Example for Default.out. consr()//Default Constructor { length=10. Parameterized. iv) Explicit calling: classname objectname=classname(args). Copy constructor) is called multiple constructors or Constructor Overloading. classname object2(object1).breath. Multiple Constructor and Constructor Overloading import java. Explicit calling Syntax: iii) Implicit calling: classname objectname(args). breath=20. Restrictions: 1. consr copy=new consr(parameter).println("\n The Perimeter of the Rectangle="+(2*(length+breath))). Java creates only one copy for a Static variable which can be used even if the class is never actually instantiated. } } class mathapplication { public static void main(String args []) WWW. } } Output: G:\KARTHI\JAVA>java constructor <=========== Default Constructor =========> Length = 10 Breath = 20 The Area of the Rectangle=200 The Perimeter of the Rectangle=60 <=========== Parameterized Constructor =========> Length = 30 Breath = 40 The Area of the Rectangle=1200 The Perimeter of the Rectangle=140 <=========== Copy Constructor =========> Length = 30 Breath = 40 The Area of the Rectangle=1200 The Perimeter of the Rectangle=140 G:\KARTHI\JAVA> Static members: UQ: Explain the use of static members in java. System. They are also available for use by other classes. parameter. consr parameter=new consr(30. They can only access static data. WWW.COM System.out.function(). parameter.VIDYARTHIPLUS. defaut.COM V+ TEAM .function(). System. (M/J’12-6M) Static variables are used when we want to have a variable common to all instances of a class. They cannot refer to this (or) super in any way.out.VIDYARTHIPLUS. float y) { return x*y.out. Static methods can be caused without using the objects. 2. } } class constructor { public static void main(String args[]) { consr defaut= new consr().println("\n <=========== Parameterized Constructor =========>"). float y) { return x/y.out. They can only call other static methods. Example: class mathoperation { static float mul(float x.println("\n <=========== Default Constructor =========>").function(). System.println("\n <=========== Copy Constructor =========>"). } static float div (float x. 3.40). io.80.50}.COM { float a=mathoperation.{70. Typically arrays are written along with size of them. System.40.20.90}}. Table as a matrix consisting of rows & columns.6}. float b=mathoperation. (A/M’11. datatype specifies type of data array elements.out.5. The individual values are called elements. Array name represent name of the array ”new” keyword is used to allocate the memory for arrays.9}}.8.{4.{40.j.0. }} Arrays: UQ: How will you define a two-dimensional array in JAVA? (A/M’11) Write a program and explain about Arrays to perform matrix multiplication using array.VIDYARTHIPLUS.5. Example: int a[]= {10.mul(4. This process is known as initialization.N/D’11.{7.*. Syntax: Datatype array-name[]=new datatype[size].20. Types of arrays: One dimensional Array Two dimensional Array One Dimensional Array: A list of items can be given one variable name using only one Subscript is called one dimensional Array.12- 16M) Array is a collection of similar type of elements.3}.60}. Syntax: Datatype arrayname[]= {List of values}.VIDYARTHIPLUS.30}. a[0]=2 a[1]=3 a[2]=7 a[3]=10 a[4]=5 a Initialization of arrays: The values put into the array created. Example: Int a[]= new int [10]. Thus grouping of similar kind of elements is possible using arrays. Syntax: int myarray [] []= new int [3] [4]. Two Dimensional Arrays: There will be situations where a table of values will have to be stored.println (“b=”+b). public class matrix_array { public static void main(String args []) throws IOException { int i. WWW. Example: //Example Matrix Multiplication for Arrays import java.2. Example: Int a []=new int[5].50. int b[][] = {{1. Java allows us to define such tables of items by using two-dimensional arrays. int a[][] = {{10. size represent the size of 2 3 7 10 5 the array.0).COM V+ TEAM . WWW.30.0).div(a.2. j<3. } break.VIDYARTHIPLUS.println("The Substraction:").VIDYARTHIPLUS.COM V+ TEAM . char choice. case '3': for(i=0. (ii) Final method: Making a method final ensures that the functioning defined in this method will never be altered in any way. Subtraction for(j=0.i++) 63 72 81 for(j=0.out. 10 40 90 160 250 360 for(i=0. Declare them as final using the keyword “final” as a modifier.Addition \n2.j<3.print(c[i][j]+" "). The value of final variable can never be charged.i<3.out. System.j++) System.in. 12) Explain Final variable.read(). j<3. The Multiplication: System.out.println("Main menu \n1.i++) { for(j=0.out.i++) 490 640 810 { for(j=0. System.out. WWW. Multiplication c[i][j]= a[i][j]+b[i][j].out. (N/D’12-8M.i++) The addition:1 { 11 22 33 for (j=0. 9 18 27 case '2': 36 45 54 for(i=0. M/J’12-8M) (i) Final variable: All methods & variables can be overridden by default in subclasses. } break.out. choice = (char)System.out. } } } Final Variable.j<3.j++) 3. for(i=0.println(). Enter your choice:2 } The subtraction: break. Example: WWW.Substraction \n3.i++) 2.i<3. 77 88 99 System.j<3. j++) 44 55 66 System. Addition for(i=0.j<3.j++) Enter your choice:3 c[i][j]= a[i][j]-b[i][j]. (constant) Example: final int SIZE = 100.i<3. System.j++) System.j++) c[i][j]= a[i][j]*b[i][j]. methods & classes UQ: When do we declare a method or a class as Final? (N/D’10.println().println("The Addition:").println("The Multiplication:").println().print(c[i][j]+" "). switch (choice) OUTPUT: { Main Menu: case '1': 1.i<3.i<3.out.print(c[i][j]+" ").COM int c[][] =new int[3][3]. Enter your choice: for(i=0. To prevent the subclasses from overriding the members of the superclass. System. System.i<3.out.Multiplication \nEnter your choice:").i++) for(j=0. methods and class. ’y’). Replace all x with y. (A/M’10. A java string is an instantiated object of the string class.13) Write a Java program to add. 2) S2=S1. Some of the most commonly used string methods: Methods Description 1) S2=S1.VIDYARTHIPLUS. compare and find the length of an input string. String Arrays: We can also create & use arrays that contains Strings. This is achieved in java using the keyword “final”. Java Supports a concept called finalization. It automatically frees up the memory resources used by the objects. StrArray of size 3 to hold three strings constants. Example: String strArrays[]=new Sting [3]. 3) S2=S1. M/J’12. Syntax: String name=new String(“Senthil”). 4) S2=S1.VIDYARTHIPLUS. Example: final class A class { __ __ } final class B extends some class { __ __ __ __ } (iv) Finalizer Methods: A constructor method is used to initialize an object when it is declared. We can assign the strings to the strArray element by element using “for” loop.N/D’10- 8M) String is a collection of characters. A class that cannot be subclassed is called a final class.trim(). In order to free these resources we must use a “finalizer” method. Converts to lower case. The finalizer method simply “finalize()” & and can be added to any class. The garbage collector cannot free these resources.ToUppercase. Java is an automatic garbage collection system. Strings: UQ: List any four string functions. The string class defines a number of methods that allow us to accomplish a variety of string manipulation tasks. But objects may hold other non-object resources such as file descriptors (or) system fonts. String Butter.11-6M.Toreplace(‘x’. Converts to upper case. How does Java handle strings? (A/M’11. Remove white spaces.COM final void show () { __ __ } (iii) Final classes: Sometimes to prevent a class being further sub classes for security reasons. String 2.ToLowercase. which is just Opposite to initialization. WWW.COM V+ TEAM . WWW. In java strings are class Objects & implemented using two classes: 1. out.out. // declaring without size Vector list =new Vector (3). What is the advantage of vector over arrays? (M/J’12.println("S1="+S1+"\nS2="+S2).equals(S2) Returns ‘true’ if S.(M/J’12) 2.element At (10) List. 3.println("S1&S2 are equal"). System. 10) S1. 2.compareTo(S2)==0) Length:7 System.toString() String representation of object P. S2=Kumar String S2=new String ("Kumar"). Vector that can hold objects of any type and any number. +ve if S1>S2. 7) S1. Vector int Vect=new Vector().add Element (item) List.length()+"\n S2="+S2+"\n Length: "+S2. University Questions: PART-A 1. 8) S1. 6) S1.out.substring(n. Comment.COM 5) S1.println("S1 greater than S2").size() List. S1=Senthil if(S1.List the features of java. S1 greater than S2 System.How will you define a two-dimensional array in JAVA? (A/M’11) 3. Some methods: list.out. (N/D’12) 4. We can add & delete objects from the list. } } Vectors: UQ: Define vectors.println("After joining two strings: "+S2). Zero S1=S2.length()).concat(S2). After joining two strings: SenthilKumar else System.out.n).compareTo(S2) Returns –ve if S1<S2.COM V+ TEAM . System. 12) WWW. N/D’12) What is Vector? How it is created? Explain few methods available in Vector.out.remove Element (item) List. Example: // Program to add. // declaring with size.println("S1="+S1+"\nLength:"+S1. (N/D’11-8M) The vector class contained in the java.m) Giving substring starting nth char to upto mth char. The objects do not have to be homogeneous. equal to S2. S2=Kumar else if(S1. compare & find length of the string public class Demostring { OUTPUT: public static void main(String args[]) D:\Javapgms>java Demostring { S1=Senthil String S1=new String ("Senthil").compareTo(S2)<0) Length: 5 System.println("S1 Smaller than S2").VIDYARTHIPLUS.VIDYARTHIPLUS.concat (S2) Join the two strings.insert Element (item.charAt(n) Gives nth character. A vector can be used to store a list of objects that may vary in size. 9) S1.util package. Arrays can be easily implemented as vectors.length() Gives the length.JAVA is free form language. It is convenient to use vectors to store objects. This class can be used to create a generic dynamic array. Advantages: 1.When do we declare a method or a class as Final? (N/D’10. S2=S1. WWW. 11) P. (M/J’13) 12.What are the various types of operators in JAVA? (A/M’11-4M) 13.-6M) 4.What is the use of ternary operator? (N/D’10) 21.What is wrapper class? (N/D’11) 17. How does Java handle strings? (A/M’11. M/J’12) 15. What is the advantage of vector over arrays? (M/J’12. The inheritance can be achieved by incorporating the definition of one class into another. (A/M’10.Enumerate the rules for creating identifiers in Java. (N/D’12-8M.How will you identify scope of variables in JAVA? (A/M’11) 18. (N/D’11) 13. (A/M’11.Write a program to print the first n Armstrong numbers (accept n as command line argument) (N/D’11-6M) 3.How is Java more secured than other languages? (M/J’13) 7.Describe various datatypes used in Java. (N/D’10) 10.Give the JAVA program structure. N/D’10. M/J’12. (N/D’10) 8. Explain about Java API packages.12-16M) 10. (A/M’11) 9.Define vectors. (N/D’10-4M. Add some properties in existing class is called inheritance.N/D’10-8M) 12.List few tokens available with JAVA. (A/M’11.List any four string functions.Explain the use of static members in java. WWW.What are JVM & JDK? (N/D’10. 11.Explain about Java Doc in detail. compare and find the length of an input string. M/J’12) 19. 11. Give examples.VIDYARTHIPLUS. A new class derived from the existing class. (M/J’12) 6.Write a program and explain about Arrays to perform matrix multiplication using array.11-6M. (A/M’11) 14.Explain how to design a Java package with an example. M/J’12.How will you access class members in JAVA? (N/D’12-8M.COM V+ TEAM . Syntax: class class-name1 Syllabus: { UNIT V __ __ Inheritance – interfaces and inner } classes . (A/M’11-8M) 8.exception handling – threads - class class-name2 extends class-name1 Streams and I/O { __ __ WWW. (N/D’11-6M) UNIT-5 Inheritance UQ: Describe different forms of inheritance with example.Write a Java program to add. using the keyword “extends”.Explain the various features of Java in detail (N/D’11-10M) 2. N/D’12) 22.COM 5. 11.13) 11. 12.Define constant in JAVA.What is meant by widening conversion? (N/D’10) 20. (M/J’12-6M) 9. M/J’13-16M) 6.Write the syntax & explain the various Java control & looping statements.What are JVM and JDK? (N/D’10.What is Vector? How it is created? Explain few methods available in Vector. (N/D’10-12M) 5. (M/J’13-16M) Inheritance is one of important features of OOP.What are the command line arguments? (A/M’11) 16.Explain Final variable.Write a program to count the number of objects created from a class.Can we write a JAVA program without class? Justify your answer. M/J’12-8M) 11. It is mainly used for reusability.N/D’11. 13-16M) 7.What do you mean by package in JAVA? (N/D’10.Construct a class with constructor in JAVA to print a pay slip of an employee. A/M’11) PART-B 1.VIDYARTHIPLUS. A/M’11. methods and class. and sub class. base class. (5)Hybrid Inheritance New class. That means one super class. (1)Single Inheritance: A It contains only one super class. The sub class is specialized for adding some properties. derived class. Syntax: class A { MUL A __ __ WWW. many sub class in this inheritance.COM V+ TEAM B C DIV MOD . Hierarchy is followed one head other classes are labor. Existing class. This act as relationship: Grandfather Father Son Syntax: class A { ADD __ A __ __ } SUB B class B extends A { __ __ MUL C } class C extends B { __ __ } 3) Hierarchical Inheritance: This type of inheritance shares the information to other classes. and one derived (or) sub class. In this inheritance some problem will occur. So that we can use abstract class as “Super class”. In multilevel inheritance there is one super class.sub class. Syntax: B class class-name1 { __ __ } class class-name2 extends class name1. WWW.COM } Types of Inheritance: (1) Single Inheritance (2) Multilevel Inheritance (3)Hierarchical Inheritance (4)Multiple Inheritance. { __ __ } (2)Multilevel Inheritance: A new class derived from existing class from that class derived new class is called multilevel Inheritance. parent class.VIDYARTHIPLUS. child class. one intermediate class.super class.VIDYARTHIPLUS. Multilevel.*.println("SUB="+e). System.VIDYARTHIPLUS.b. } } class MUL extends SUB //Multilevel Inheritance { int f.out. class ADD { int a. The process of creating one sub class from more than one super class is called multiple inheritance. WWW.COM } class B extends A { __ __ } class C extends A { __ __ } (4)Multiple Inheritances: UQ: Which type of inheritance is not allowed in java? What is the equivalent representation? Explain with example.VIDYARTHIPLUS.io.out. Hierarchical and Hybrid Inheritance) import java.i. c=a+b. WWW. (A/M’10) In java cannot perform the multiple Inheritance directly.b=5. SUB Inheritance } } class DIV extends MUL MUL Hierarchical Inheritance { int h. OUTPUT: System. We can avoid this problem using “Interfaces”.e. EXAMPLE: // Example for Inheritance (Single. DIV=10 public void sub_op() MOD=0 { d=5. Inheritance g=e*f.println("ADD="+c).g.out. Multilevel System. (5)Hybrid Inheritance: The process of combining more than one inheritance (single. e=c-d. public void add_op() { a=10. public void mul_op() ADD { Single f=5. } ADD=15 } SUB=10 class SUB extends ADD //Single Inheritance MUL=50 { int d.c.println("MUL="+g).COM DIV MOD V+ TEAM . multi level. Hierarchical) in classes is called Hybrid inheritance. d. d.div_op().out.VIDYARTHIPLUS. (2) The abstract methods of an abstract class must be defined in its subclass.VIDYARTHIPLUS. (3) Cannot declare abstract constructors (or) abstract static methods. Abstract Class Class A Abstract function Fun1() Fun2() WWW. d.mul_op(). thus making Overriding.k. } } public class Arith_Inherit { public static void main(String args[]) { DIV d=new DIV().println("DIV="+i).mod_op(). (M/J’12-8M) A method must always be redefined in a sub class. MOD m=new MOD().out. Syntax: abstract class shape { __ __ abstract void draw (). m. it should also be declared abstract class. } } Abstract methods & classes: UQ: Abstract methods and classes in detail. k=g%j. WWW.COM V+ TEAM . Ex: Shape S=new shape (). Conditions: (1) Cannot use abstract classes to instantiate objects directly. __ __ } When a class contains one or more abstract methods.COM public void div_op() { h=5. public void mod_op() { j=5.add_op().sub_op(). This is done using the modifier keyword “abstract” in the method definition. System. } } class MOD extends MUL { int j.println("MOD="+k). System. d. i=g/h. VIDYARTHIPLUS. That is classes in java cannot have more than one super class.println("class B").out. N/D’10) Explain about the defining extending and implementation of interfaces in java.fun1().fun1(). C c=new C(). } } Interfaces: UQ: How Java achieves multiple inheritance? (N/D’11) How are interfaces different from classes? (N/D’11) What is an interface in JAVA? (A/M’11.VIDYARTHIPLUS. (M/J’12-8M) Explain how interfaces are used to achieve multiple. (M/J’13-16M) Java does not support multiple inheritance. Class A extends B extends C // is not permitted in java { __ __ } Java provides an alternate approach known as “interfaces” to support the concept of multiple inheritance. } } class B extends A { void fun1() { System.println("class C").fun2(). WWW.fun2().out.COM Example: abstract class A { abstract void fun1(). (N/D’11-10M) Give an example where interface can be used to support multiple inheritances. } } public class abstract_Demo { public static void main(String args []) { B b=new B(). void fun2() { System.out.println("class A"). b. c.COM V+ TEAM . c. b. WWW. Develop a standalone Java program for the example. OUTPUT: } Class B } class C extends A Class A { Class C void fun1() { Class A System. Syntax: interface interfaceName { static final datatype variableName=value.println("Mark2="+mark2).out.COM Java class cannot be a subclass of more than one super class.VIDYARTHIPLUS.int m1. Example: //Example for Interface and Multiple Inheritance class student { STUDENT SPORTS int rollno. WWW.println("Student Details"). RESULTS mark1=m1.println("Sports Wt="+sportwt). Interface & Multiple Inheritance System. } } class MultipleInheritance { public static void main(String args[]) { WWW. it can implement more than one interface. put_details(). Defining Interface: An interface is basically a kind of class.VIDYARTHIPLUS. } void display() { total=mark1+mark2+sportwt.mark1.println("Total="+total).out. List of methods without anybody statements.out. } class Results extends student implements sports //Interface Implementation { int total. public void putwt() { System.out. datatype MethodName (Parameters).out.int m2) { rollno=rno.out.println("RollNo="+rollno). Like classes. OUTPUT: System. void get_details(int rno. interfaces contain methods & variables but with major difference. Interface define only abstract methods & final fields. } void put_details() { System. } All variable are declared as constants. This means that interfaces do not specify any code to implement these methods & data fields contain only constant. ---------------------------------- System. System. Student Details } RollNo=1234 Mark1=57 } Mark2=75 interface sports //Interface Creation Sports Wt=7 { Total=139 final int sportwt=7. mark2=m2.COM V+ TEAM .mark2.println("Mark1="+mark1). void putwt(). putwt(). The function called in subclass using “Super” keyword. The methods are abstract methods.fun().out. The method can be abstract (or) non abstract.57. It can use various access specifiers.out.VIDYARTHIPLUS.COM V+ TEAM . It cannot be used declare objects.fun(). System. It inherited by a class. r1. System. It can use only public access specifier. 2)Methods are declared along with the datatypes. 1)The variables must be final. } } class B extends A { void fun() { super.75). Overriding: UQ: Explain with example. (M/J’12-4M) What is method overloading in java? (A/M’10) WWW.VIDYARTHIPLUS. } Class Interface The members can be constant or variable.println("----------------------------------------------"). Results r1=new Results(). The members are always as constant. r1. Ex: Super. } } Overloading: UQ: Differentiate method overloading & overriding in java. } } class overridingtest { public static void main(String args[]) { B b=new B(). 3)Constructors can invoked by the sub classes. WWW. b. } Difference between Class & Interface Difference b/w Abstract Class & Interfaces UQ: What is the major difference between an interface and abstract class? (N/D’12. (A/M’10) Method Overriding is a mechanism in which a subclass inherits the methods of super class.println("Class B").get_details(1234. The Overridden method must be called from subclass. method overriding in java. 2)Methods are public abstract methods.display(). It can be instantiated by declaring objects.out. Example: //Example for Overriding class A OUTPUT: { void fun() Class A { Class B System.println("Class A"). Sometimes the subclass modifies the implementation of method defined in superclass.println("Example for Interface and Multiple Inheritance").COM System. 3)There is no constructor defined.out.method name(). M/J’13) Abstract Class Interfaces 1)The variables are declared by using datatypes. 5f). Incompatible types in assignment or initialization Bad references to objects. Such programs may produce wrong results due to wrong logic or may terminate due to errors such as stack overflow.println("Sum="+(a+b)).out. Run-time Errors 1.6f.println("Example for Function Overloading"). } public static void sum(int a.30). Sum=13.1 sum(5.int b) { System.println("Sum="+(a+b)).COM V+ TEAM . Run-Time Errors Sometimes.20. Sum=60 sum(10. Misspelling of identifiers and keywords. these errors are called compile-time errors.out. Example: //Example for Function Overloading class overloadingDemo { OUTPUT: public static void main(String args[]) Example for Function Overloading { ------------------------------------------- System. }} Error: Error is common to make mistakes while developing as well as typing a program. 2. System. functionname(datatype variablename1. Compile-time Errors 2. Missing brackets in classes and methods. } public static void sum(int a.out. Types of Errors: 1. Missing double quotes in strings.COM Overloading is a mechanism in which we can use many methods having the same name but number of parameters may be different (or) different datatypes of parameters.class file but may not run properly.float b) { System.int b. WWW.println("--------------------------------").datatype variablename2).out. Use of undeclared variables. Use of = in place of == operator.println("Sum of two Integers"). o Most common compile-time errors are: Missing semicolon.out.println("Sum of three Integers").int c) { System. These errors due to typing mistakes.println("Sum of two Floats").20).out. a program may compile successfully creating the .println("Sum="+(a+b+c)). Sum of two Integers System.out.out. Sum of two Floats System. Syntax: functionname(datatype variablename). } public static void sum(float a. Compile-time Error: All syntax errors will be detected and displayed by the compiler.VIDYARTHIPLUS.7.VIDYARTHIPLUS. Most common run-time errors are: Dividing an integer by zero Accessing an element that is out of the bounds of an array WWW. Sum of three Integers sum(10. Sum=30 System. exception is handled using five keywords: try. 2. Receive the error information (Catch the exception) 4.COM Trying to store a value into an array of an incompatible class or type Trying to cast an instance of a class to one of its subclasses Passing a parameter that is not in a valid range or value for a method Trying to illegally change the state of a thread Attempting to use a negative size for an array Converting invalid string to a number Accessing a character that is out of bounds of a string Exceptions Exception in Java is an indication of some unusual event. Tasks: 1. the difference lies only in the way they are handled.Exception class. Usually it indicates the run-time error. Find the problem (Hit the exception). Unchecked exceptions: these exceptions are not essentially handled in the program code. WWW.VIDYARTHIPLUS. instead the JVM handles such exceptions. Inform that an error has occurred (Throw the exception) 3. Checked exceptions are extended from the java.lang.COM V+ TEAM catch Block . catch. Exception Handling: The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken. It is important to note that checked and unchecked exceptions are absolutely similar as far as their functional is concerned. Unchecked exceptions are extended from the java. throw. throws and finally. try Block Exception object creator Statement that caused an exception WWW.lang.Runtime Exception class.VIDYARTHIPLUS. Take corrective actions (Handle the exception) Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions: these exceptions are explicitly handled in the code itself with the help of try-catch blocks. Blocks and Keywords: In Java. If anyone statement generates an exception. finally block: UQ: Explain the use of the keyword ‘finally’ in java? (A/M’10) o Java supports another statement known as finally statements that can be used to handle an exception that is not caught by any of the previous catch statements.VIDYARTHIPLUS.COM V+ TEAM .Divide by zero.} Types of Exceptions: Exception Description ArithmeticException Used for representing arithmetic exceptions.VIDYARTHIPLUS. throws block: When a method wants to throw an exception then keyword throws is used. ArrayIndexOutOfBoundsException Array index when gets out of bound. throw block: Java uses a keyword try to preface a block of code that is likely to cause an error condition and “throw” an exception. otherwise compilation error will occur. EmptyStackException An attempt to pop the element from empty stack NumberFormatException When we try to convert an invalid string to number this exception gets caused. Exception This is the most general type of exception. Remember that every try statement should be followed by at least one catch statement. this exception will be caused. Only catch block or only finally block without preceding try block is not at all possible. this exception will be caused. There should be some preceding try block for catch or finally block.COM try block: The try block can have one or more statements that could generate an exception. o Finally block can be used to handle any exception generated within a try block. catch block: A catch block defined by the keyword “catch” catches the exception “thrown” by the try block and handles it appropriately. o It may be added immediately after the try block or after the last catch block. RuntimeException To show general run time error this exception must be raised. If the catch parameter matches with the type of exception object. The syntax is- Method-name(parameter-list)throws exception-list {……. WWW. WWW. NullPointerException Attempts to access an object with a Null reference. The catch block too can have one or more statements that are necessary to process the exception. then the exception is caught and statements in the catch block will be executed. IndexOutOfBoundsException Array index when gets out of bound. For e. IOException When an illegal input/output operation is performed then this exception is raised.g. ArrayStoreException When a wrong object is stored in an array this exception must occur.. Rules: 1. the remaining statements in the block are skipped and execution jumps to the catch block that us placed next to the try block. } catch(ArrayIndexOutOfBoundsException e2)//ArrayIndexOutOfBoundsException { System.out.out. case '2': try { c=a[0]/a[2]. There can be zero or more catch blocks for each try block but there must be single finally block present at the end. } break.VIDYARTHIPLUS.COM V+ TEAM .println("Example for Exception"). switch(choice) { case '1': try { e=b/d.io.d=0.Arithmetic Exception\n2.IOException").println("In Arithmetic Exception").util.println("Caught exception: "+e1).println("1.throw block"). System.COM 2.b=5. import java.print("Choose your option:"). int c.*. try { System. DataInputStream din=new DataInputStream(System.e. //generates an exception } catch (Exception-type e) { Statement.VIDYARTHIPLUS. System. //after processes the exception } Example: //Program for Exception Handling in JAVA import java.read(). class ExceptionProg { public static void main (String args[]) { int a[]={10. choice=(char)din.out.Array IndexOutof Bound\n3. System.println("4.out.println("Caught exception: "+e2).5}. System. char choice='q'.println("This is finally of ArithmeticException"). Syntax: try { Statement.out.out. //processes the exception } finally { Statement. } finally { System. WWW. WWW.in).*.throws block\n5.out.out. } catch(ArithmeticException e1)//ArithmeticException { System. out. Sr. } break. It is sometimes called as light-weight process.println("This is finally of ArrayIndexOutOfBoundsException").COM } finally { System.IllegalAccessException: Some Operation Threads: UQ: Explain with examples of java threads.lang. Thread Process WWW.throws block 5.VIDYARTHIPLUS.println("Caught exception: "+e3).println("Caught exception: "+ea). case '3': try { throw new Exception("Exception occur"). But there lies difference between thread and process.No.lang. } } catch(IOException e3) //IOException { System.COM V+ TEAM .//throw the Exception } catch(Exception ea) { System.lang.Exception: Exception occur Choose your option:4 Caught exception: java.out. WWW. } catch(IllegalAccessException my) { System.Arithmetic Exception 2.IOException Choose your option:1 Caught exception: java.ArrayIndexOutOfBoundsException: 2 This is finally of ArrayIndexOutOfBoundsException Choose your option:3 Caught exception: java.println("Caught exception: "+my). } break. (N/D’10-12M) Thread is a tiny program running continuously.out.lang.ArithmeticException: / by zero This is finally of ArithmeticException Choose your option:2 Caught exception: java.Array IndexOutof Bound 3.throw block 4. } break.out. case '4': try { fun1(). } } static void fun1()throws IllegalAccessException//throws the Exception { throw new IllegalAccessException("Some Operation"). } OUTPUT: } D:\Javapgms>java ExceptionProg Example for Exception 1.VIDYARTHIPLUS. Waiting state Sometimes one thread has to undergo in waiting state because another thread starts executing. By executing various methods. multiprocessing Multiple parts of a single program gets executed by Multiple programs get executed by means 2.VIDYARTHIPLUS. New Waiting Waiting Completion Runnable Terminated Waiting for I/O Interval Interval I/O Completed Ends request Blocked Timed Waiting New state When a thread starts its life cycle it enters in the New state or a create state. It runs in the address space of the process to space to execute. During multithreading the processor switches During multiprocessing the processor 3. process uses CPU other processes has to wait.COM 1 Thread is light-weight process. Difference between Multithreading and Multitasking (or) Multiprocessing Sr. Blocked state WWW. Process is heavy weight process. It is cost effective because CPU can be shared It is expensive because when a particular 4. which it belongs to. among multiple threads at a time. Process is a fundamental unit of 1. of multiprocessing. the thread in waiting state enters in runnable state. means of multithreading. Thread States Thread always exists in any one of the following states- New or create state Runnable state Waiting state Timed waiting state Blocked state Terminated state Life Cycle of a Thread Thread Life cycle specifies how a thread gets processed in the Java program. Runnable state This is a state in which a thread starts executing. between multiple threads of the program. Threads do not require separate address space for its Each process requires separate address 2 execution.No Mulithreading Multiprocessing Thread is fundamental unit of multithreading. WWW. After the timing gets over.VIDYARTHIPLUS. This allows executing high prioritized threads first.COM V+ TEAM . Following figure represents how a particular thread can be in one of the state at any time. Timed waiting state There is a provision to keep a particular threading waiting for some time interval. switches between multiple programs or processes. After the I/O completion the thread is sent back to the runnable state.VIDYARTHIPLUS. blocked and so on. UQ: What are two methods of creating java threads? (N/D’10) In Java we can implement the thread programs using two approaches- Using Thread class Using runnable interface Following figure shows the thread implementation model Implementation of thread Extends Implements Thread Runnable (class) (Interface) Overrides Run () As given in there are two methods by whichmethod we can write the Java thread programs one is by extending thread class and other is by implementing the Runnable interface. Terminated state After successful completion of the execution the thread in runnable state enters the terminated state. runnable. 2. The thread may be initialized in the method() call. Various methods used in Thread class are: Method Description getName Obtain thread’s name Run By this method execution of thread is started Sleep Thread execution can be suspended for some time Start Starts the thread with the help of run method isAlive Checks whether thread is running or not yield() It makes current executing thread object to pause temporarily and gives control to other thread to execute. notify() This method wakes up a single thread notifyAll() This method wakes up all threads Join Waits for a thread to terminate Let us now discuss first create the programs containing single thread.COM When a particular thread issues an Input/Output request then operating system sends it in blocked state until the I/O operation gets completed. WWW. This is an expensive operation. If a class extends a thread class then it cannot extends any other class which may be required to extend. Runnable Interface Implementing thread program using Runnable interface is preferable than implementing it by extending the thread class because of the following two reasons- 1. Step3: Override the method run() by writing the code required to execute a thread. The Java Thread Model The threads can be in various states such as new. Thread Class The procedure to extend a thread class is as given below- Step1: The main class must extend the thread class. If a class thread is extended then all its functionalities get inherited. waiting.VIDYARTHIPLUS. it gets terminated. Step2: A thread is created in the class.COM V+ TEAM . Example: class threaddemo extends Thread//Thread Class WWW. After successful completion of a thread. start(). try { Thread.runnable_method("Using Runnable Interface"). In the following Java program.out.out.sleep(1000). Creation of Multiple Threads by extending the Thread class and Implementing Runnable Interface. runabledemo rt1=new runabledemo().thread_method("Using Thread Class"). void thread_method(String s) { str=s.out.start().COM V+ TEAM . threaddemo t1=new threaddemo().println(str). t1. OUTPUT: } public void run() D:\Javapgms>java thread_create { Example for Threads System.//directs to the run method } public void run()//Thread execution starts { for(int i=1.i++) System.i<=3.COM { String str="". WWW. thread_demo(String str) { msg=str.out. WWW. Thread t=new Thread(this). } } Handling Multiple Threads We can create multiple threads and execute them simultaneously. Using Thread Class } Using Runnable Interface } public class thread_create { public static void main (String args[]) { System.println(str1). void runnable_method(String s1) { str1=s1. three threads are created and handled.println("Example for Threads").//Initialize the thread } public void run()//Execute the thread { System. Multiple threads can be created by either extending the Thread class (or) by implementing the runnable interface. rt1. } } class runabledemo implements Runnable//Runnable Interface { String str1="".VIDYARTHIPLUS.println(msg). t. start(). Example: //Example for Multithreading using Thread class and runnable interface class thread_demo extends Thread//Using Thread Class { String msg.VIDYARTHIPLUS. out.. The value passed to this method as an argument denotes the time in milliseconds.... .out.Third thread Thread...... If you execute the program repeatedly then you may notice that the threads t1.println("---------------------------").. (N/D’10-12M) Stream is basically a channel on which the data flow sender to receiver...out. The execution of these threads will be started in run() method..COM } catch(InterruptedException e) { System.out.. runnable_thread rt1=new runnable_thread("First thread")...println(msg)..i++) .out..VIDYARTHIPLUS. . thread_demo t3=new thread_demo(". thread_demo t1=new thread_demo("First thread"). } } Program Explanation In the main function we have created three threads namely t1..Second thread try Multithreading using Runnable Interface { ....Third thread } .println("Example for Multithreading")...Second thread").Second thread").. An input object that reads the stream of data from a file is called input stream and the output object that writes the stream of data to a file is called output stream.. runnable_thread(String str) OUTPUT: { Example for Multithreading msg=str.Third thread { . System...//directs to the run method Multithreading using Thread class } First thread public void run() First thread First thread { .i<=3. } } } class runnable_thread implements Runnable//Using Runnable Interface { String msg.Second thread } ..Third thread catch(InterruptedException e) First thread { First thread System.println("Exception in thread")..t2 and t3 can execute in any order.VIDYARTHIPLUS.println("Exception in thread")... System.out.COM V+ TEAM .Second thread public class many_thread .Second thread for(int i=1.Third thread public static void main (String args[]) ...sleep(1000). runnable_thread rt3=new runnable_thread(". System...Third thread").... Streams and I/O: UQ: Explain with examples of Streams and I/O.t2 and t3 having the strings “First thread”. Types of Streams WWW.. WWW.println("Multithreading using Thread class")..sleep method in order to send a thread in timed state. This statement must be within a try-catch block by throwing the exception InterruptedException.println("Multithreading using Runnable Interface")... “Second Thread” respectively. Thread t=new Thread(this)..out. First thread } . thread_demo t2=new thread_demo(". runnable_thread rt2=new runnable_thread(". --------------------------- t...... We have invoked the Thread.Second thread System.start().Third thread")......Second thread } ...Third thread { System. COM In Java input and output operations are performed using streams. There are two super classes in byte stream and those are InputStream and OutputStream from which most of the other classes are derived.*.io. There are two super classes in character stream and those are Reader and Writer. These classes define several important methods such as read() and write(). WWW. These classes handle the Unicode character streams. Byte stream Stream Character stream Byte Stream (or) Text Stream: The byte Stream is used for inputting or outputting the bytes. And Java implements streams within the classes that are defined in java.VIDYARTHIPLUS. There are basically two types of streams used in Java. The input and output stream classes are as shown in.COM V+ TEAM . The two important methods defined by the character stream classes are read() and write() for reading and writing the characters of data. FileInputStream BufferedInputStream PipedInputStream DataInputStream FilterInputStream InputStream LineNumberInputStream ByteArrayInputStream PushbackInputStream SequenceInputStream StringBufferInputStream FileOutputStream PipedOutputStream BufferedOutputStream OutputStream FilterOutputStream DataOutputStream ByteArrayOutputStream PrintStream Character Stream or Binary Stream: The character stream is used for inputting or outputting the characters.VIDYARTHIPLUS. Various Reader and Writer classes are- FileReader PipeReader FileWriter PipeWriter FilterReader BufferedReader FilterWriter BufferedWriter DataReader LineNumberReader WWW. This mark remains valid until the n bytes are read.int This method returns the n bytes into the buffer which is starting at offset. Various methods defined by this class are as follows Methods Purpose void close() This method closes the output stream and if we try to write further after using this method then it will generate IOException void flush() This method clears output buffers. void write(byte buffer[]. int read(byte buffer[]. void reset() This method resets the input pointer to the previously set mart. boolean marksupported() It returns true if mark() or reset() are supported by the invoking stream. Various methods defined by this class are as follows Methods Purpose int available() It returns total number of byte input that are available currently for reading. void mark(int n) This method places a mark in the input stream at the current point. int read(byte buffer[]) This method reads the number of bytes equal to length of buffer.COM V+ TEAM . long skip(long n) This method ignores the n bytes of input.int offset. we are writing and reading some data to the file.io. FileOutputStream(String filename) FileOutputStream(Object fileobject) The app denotes that the append mode can be true or false. Example: //Example for FileInputStream and FileOutputStream import java. WWW. The FileOutputStream can be used to write the data to the file using the OutputStream. All these methods under this class are of void type.COM DataWriter LineNumberWriter PushbackReader ByteArrayReader PushbackWriter ByteArrayWriter SequenceReader StringBufferReader SequenceWriter StringBufferWriter I/O Handling using Byte Stream InputStream is an abstract class for streaming the byte input. int read() It returns the next available number of bytes to read from the input stream. It n) returns the number of bytes that are read successfully.VIDYARTHIPLUS. void write(byte buffer[]) This method allows to write complete array of bytes to an output stream. In the following Java program.VIDYARTHIPLUS.Boolean app). void write(int val) This method allows to write a single byte to an output stream.int offset. It then returns the actually ignored number of bytes.out. If the append mode is true then you can append the data in the otherwise the data cannot be appended in the file. FileInputStream(String fileobject. OutputStream is an abstract class for streaming the byte output. If we try to read further after closing the stream then IOException gets generated. Thus it returns the actual number of bytes that were successfully read. System.Boolean app). WWW. class filesstreamprog { public static void main(String[] args)throws Exception { int n.*. void close() The input source gets closed by this method. If this method returns the value-1 then that means the end of file is encountered.int n) This method writes n bytes to the output stream from an array buffer which is beginning at buffer[offset] FileInputStream/FileOutputStream UQ: What is the purpose of getBytes() method? (N/D’10) The FileInputStream class creates an InputStream using which we can read bytes from a file. The two common constructors of FileInputStream and FileOutputStream are: FileInputStream(String filename.println("Example for Writing and Reading content in the file"). VIDYARTHIPLUS.out. FilterInputStream/FilterOutputStream FilterStream classes are those classes which wrap the input stream with the byte.close(). System.available()). FileInputStream fiobj=new FileInputStream("D:/Javapgms/output.length.". } } OUTPUT: Example for Writing and Reading content in the file --------------------------------------------------- The data is written to the file Total available bytes:48 Reading first 24bytes at a time India is my Country I lo skipping some text still available: 12 D:\Javapgms>type output.available())).skip(n/4).println("Total available bytes:"+(n=fiobj.out.COM System. fiobj.out. String my_text="India is my Country\n"+"I love my country very much.println("\n still available: "+fiobj.close(). byte b[]=my_text.VIDYARTHIPLUS. That means using input stream you can read the bytes but if you want to read integers. fiobj. The superclass of DataInputStream class is FilterInputStream and superclass of DataOutputStream class is FilterOutputStream class.txt India is my Country I love my country very much.println("---------------------------------------------------"). FileOutputStream foobj=new FileOutputStream("D:/Javapgms/output.read()). int m=n/2.i<b. Various methods under these classes are: Methods Purpose WWW. WWW. doubles or strings you need to a filter class to wrap the byte input stream.out.println("\n The data is written to the file"). foobj. System. The syntax for FilterStream and FilterOutputStream are as follows- FilterOutputStream(OutptuStream o) FilterInputStream(InputStream i) The methods in the Filter stream are similar to the methods in InputStream and OutputStream DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive data type whereas the DataOutputStream converts the primitive data types into the bytes and then swrites these bytes to the stream.println("\n skipping some text").write(b[i]). for(int i=0. System.getBytes().COM V+ TEAM .print((char)fiobj.txt"). System. for(int i=0.out.out.out.i<m.txt").i++) System.i++) foobj. System.println("\n Reading first "+m+"bytes at a time"). out. But these methods add the buffers in the stream for efficient read and write operations.writeUTF("Keshavanand"). void writeInt(int val) Writes the integer value to output stream.readUTF()+":"+in.COM V+ TEAM . WWW. class BufferedStreamProg { public static void main(String[] args)throws Exception { DataOutputStream Obj=new DataOutputStream(new BufferedOutputStream(new FileOutputStream("in. Keshavanand:77 Obj.txt"))).out. void writeUTF(String str) Writes the string value in UTF from to output stream.COM boolean readBoolean() Reads Boolean value from the inputsteam byte readByte() Reads byte value from the inputstream char readChar() Reads char value from the inputstream float readFloat() Reads float value from the inputstream double readDouble() Reads double value from the inputstream int readInt() Reads integer value from the inputstream long readLong() Reads long value from the inputstream String readLine() Reads string value from the inputstream String readUTF() Reads string in UTF from. Obj.writeUTF("Archana").readDouble()). void writeFloat(float val) Writes the float value to output stream.VIDYARTHIPLUS.*.println("\nFollowing are the contents of the 'in. Following are the contents of the 'in.io. In the following Java program the BufferedInputStream and BufferedOutputStream classes are used. Let us see how these methods can be used in a Java Program- Java. void writeBytes(String str) Writes the bytes of characters in a string to output stream.readInt()). Archana:44.println(in.txt"))).Object Java.Object OutputStream InputStream FilterOutputStream FilterInptStream BufferedOutputstream BufferedInputStream BufferedInputStream/BufferedOutputStream The BufferedInput Stream and BufferedOutputStream is an efficient class used for speedy read and write operations.writeDouble(44.writeInt(77). Example: import java. All the methods of BufferedInputStream and BufferedOutputStream class are inherited from InputStream and OutputStream classes.close().67 Obj.readUTF()+":"+in. DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream("in. Obj. void writeBoolean(boolean val) Writes the Boolean value to output stream. void writeLong(long val Writes the long value to output stream.io.txt' file"). System. void writeDouble(float val) Writes the double value to output stream. OUTPUT: Obj.writeUTF("Chitra").writeChar('a').txt' file Obj.67).VIDYARTHIPLUS. Chitra:a Obj. System.out. System. WWW.io. We can specify the buffer size otherwise the default buffer size is 512 bytes.println(in. Reading char\n2. char ch.in)). In fact we should pass the variable System. WWW.println(ch). System. obj. Enter your Choice: 2 WWW.out. Hence the syntax is.read(). The writeUTF method converts the string into a series of bytes in the UTF-8 format and writes them into a binary stream.//count to keep track of 5 characters n } t break.out. int count=0.Reading String"). System.in to BufferedReader object.io.in.read(). Hence if we are going to use read() method in our program then function main can be written like this- public static void main(String args[])throws IOException Example: //Reading the input char and string from console import java. OUTPUT: switch(ch1) 1. The readUTF method reads a string which is written using the writeUTF method. The creation of buffers is shown by the bold faced statements in.in and System. For example the object named obj can be created as BufferedReader obj=new BufferedReader(new InputStreamReader(System. When we want to read some character from the console we should make use of system. Along with it we should also mention the abstract class of BufferedReader class which is InputStreamReader. But this is not the only thing needed for reading the input from console. System is a class defined in java. Then.in)).COM V+ TEAM Enter the strings: .read(). } } Program Explanation Note that in above program. String s. ch1=(char)obj. I/O Handling using Character Stream Reading the Input In Java.readUTF()+":"+in.//outputting it e count++. Basically UTF is an encoding scheme that allows systems to operate with both ASCII and Unicode.println("1.out.out.COM System. The character stream class BufferedReader is used for this purpose.*. h case '2': System. Normally all the operating systems use ASCII and Java uses Unicode.println("Enter the strings:"). out and err are the variables of the class System.lang and in.Reading char 2.println(in.g.Reading String { Enter your Choice: case '1': 1 System.VIDYARTHIPLUS.in)).//reading single character s System.println("\nEnter five characters"). along with other simple read and write methods we have used readUTF and writeUTF methods. BufferedReader object-name=new BufferedReader(new InputStreamReader(System.println("Enter your Choice:"). class ReadChar { public static void main(String args[])throws IOException { //declaring obj for read() method BufferedReader obj=new BufferedReader(new InputStreamReader(System.out.out. while(count<5) Enter five characters: { senthil ch=(char)obj. The only change is we have added buffers.VIDYARTHIPLUS. we have to mention the exception IOException for this purpose.out is an object used for standard output stream and System. using this object we invoke read() method.ch1. For e.err are the objects for standard input stream and error.readChar()). Hence System. Abstract methods and classes in detail. What is the major difference between an interface and abstract class? (N/D’12. (A/M’10) 5. Writing the Output The simple method used for writing the output on the console is write(). How Java achieves multiple inheritance? (N/D’11) 8.println(s). As given in above program. s=obj. (M/J’12-4M) 7. }}} This program allows you take the input from console. The method read() returns the integer value.VIDYARTHIPLUS. What is an interface in JAVA? (A/M’11. What is the purpose of getBytes() method? (N/D’10) 6. N/D’10) 10.out. Note that to read the string input we have used readLine() function. And these methods belong to PrintWriter class.out.write(int b) The bytes specified by b has to be written on the console. M/J’13) PART-B 1.equals("end")) { System. Here is the syntax of using write() method- System. Otherwise this program is almost same as previous one. Explain the use of the keyword ‘finally’ in java? (A/M’10) 3. method overriding in java. University Questions only: PART-A 1. WWW. (A/M’10) 4. } break. (N/D’10-12M) 3. Differentiate method overloading & overriding in java. How are interfaces different from classes? (N/D’11) 9. What is method overloading in java?(A/M’10) 2.13-16M.readLine(). Develop a standalone Java program for the example. What are two methods of creating java threads? (N/D’10) 7. read() method is used for reading the input from the console. hence it is typecast to char because we are reading characters from the console.Explain with examples of Streams and I/O.COM V+ TEAM .//for reading the string while(!s. (N/D’11-16M) WWW. (M/J’12. But typically print() or println() is used to write the output on the console.COM s=obj.VIDYARTHIPLUS. (M/J’13-16M) 4. Explain with example. Describe in detail about exception handling in java.readLine(). (N/D’10-12M) 2.Describe different forms of inheritance with example. N/D’11-10M) 6. Which type of inheritance is not allowed in java? What is the equivalent representation? Explain with example. (M/J’12-8M) 5.Explain with examples of java threads.Give an example where interface can be used to support multiple inheritances.