Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
79 views
72 pages
Sem-4 Ppl.
bna
Uploaded by
Omkar Watpade
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save SEM-4 PPL. (1) For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
79 views
72 pages
Sem-4 Ppl.
bna
Uploaded by
Omkar Watpade
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save SEM-4 PPL. (1) For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save SEM-4 PPL. (1) For Later
You are on page 1
/ 72
Search
Fullscreen
Savitribai Phule Pune University Semester IV (Computer Engineering) Principles of Programming Languages Unit IIT : Java as Object Oriented Programming Language-Overview Q.1 Explain why Java is Secured, Robust, Portable, and Dynamic? Which of the concepts in Java ensures these? a : Sa 1. Simple ns. : Java Features 2. Platform Independent 38 Secured 4, Robust 5. Portable 6. Multithreading 7. Dietrbuted 1. Architectural Neutral 8 Dynamic 10, Interpreted Fig. 3.1 : Java Features Simple Syntax of language is very simple to use as compared to other programming languages. Platform Independent ‘+ Itis operating system and hardware independent. Its possible due to java bytecode. Bytecode is universally accepted code by any JVM implementation, ‘+ ‘Though JVM is dependent, bytecode is platform independent and be platform independent language. juse of which Java can be considered as Secured ‘© [tis most secured language because it does not provide the pointers. Security is added at different layers. * tis added during the programming in terms of methods andl private variables. JVM verifies the bytecode ‘means another layer of security is added. Scanned with CamScannerQuick Read rnc fPayamping ngage SPP) “4. Robust , © temeans strong, It uses very efficient memory management, It does not provide pointers 80 avolds security problems ‘+ Automatic garbage collection is supported by Java. Ciass lo oe Windows acios 3.2: Platform independent 5. Portable: Java application can be installed on any device without any change. 6. Multithreading ‘+ Toutilize the processor power, multithreading is supported by Java. Separate library is provided to multithread the program. 7. Distributed ‘© Distributed application development is possible using java, RMI and EJB can be used for It + File access through internet is possible. 8. Architecture Neutral: All programs can run on any platform and on any operating system: 9. Dynamic: Memory allocation to object of class is dynamic 10, Interpreted + _ Java bytecode is translated onthe My to native machine instructions andis not stored anywhere. ‘+The development process is more rapid and analytical since the tin ay the linking is an incremental and light weight @.2 Explain Java Virtual Machine(JVM) Architecture in details. Explain each com ‘Ans. : Java Virtual Machine Ponent briefly, (6 Marks) © Java Virtual Machine or simply JVM is the engine that Languages, compiler produce a compiled code for a particular Java Virtual Machine. % the Java eae, Mostly in other Programming 'ystem but Java compiler produce Bytecode for 2 Scanned with CamScanner& pnciplesotProgramming Languages (SPPU)_—__ 3. uk ead © When we compile any Java program, then bytecode is generated. In java, bytecode is the source code that can be used to run on any platform. Bytecode is an intermediary language between Java source and the system. In this. way, bytecode which gets interpreted on a different machine and hence it makes it Platform or Operating system independent. * Java is called platform or operating system independent because of Java Virtual Machine. As different computers with the different operating system have their different JVM, when we submit a class file to any oper system, JVM interprets the bytecode into machine level language. ‘+ JVMis the essential component of Java architecture, and itis the part of the JRE (Java Runtime Environment). In particular, a program of JVM is written in C Programming Language, and JVM is Operating System depenclent. JVM is responsible for allocating the necessary memory needed by the Java program. Lamia ‘Java Compiler Byte code toaded into JVAT [Java Virual Machine] ava interpreter t Operating System Fig. 3.3 :AJVM «JVM is responsible for de-allocating memory spaces, JVM Architecture ‘© Let's understand the Architecture of JVM. It contains, © Class loader © Memory area © Execution engine JA anguage Cases JVM Memory Fig. 3.4 : JVM architecture @s| Scanned with CamScannerQuick Read 1. Class Loader ‘The class loader is used for loading class fl Initialization. oading, Linking, and Jes. performs three major functions viz 10 ding, Linking, and Area stores class st the code for methods, metadat stant runtime pool. nd the constal JVM Method Area stores class structures like the code for met ods, mets 3. Heap are stored in the heap. This memory Is common ‘Allthe java objects, their related instance variables, and array and shared across multiple threads. 4, JVM language Stacks Java language stacks store local variables and its partial results. Each thread bas Is 08" ale simultaneously as the thread is created, Whenever a method is invoked, a new frame Is created’ 40000 CNS when method invocation process is complete, 5. PC Registers PC register store the address of the currently executing JVM instruction. In Java, each thread has its separate PC register. 6. Native Method Stacks Native method stacks hold the instruction of native code that depe ids on the native library. It is written in another language instead of Java. 7. Execution Engine + Wis a type of software used to test software, hardware, or complete systems. The test execution engine never carries any information about the any tested product. 8. Native Method Interface Its a programming framework that allows Java code which ts ru applications 9. Native Method Libraries ng ina JVM to call by librari and native Native Libraries are the collection of the Native Libraries ( +) which are needed by the Execution Engine. SEERA Primitive datatypes are also called sim ; simple data types, int, long, char, float, double and Boolean. These ie are eight primitive ified into data types in java : byte, short, " following cat 2 Amegers: This group include byt, short and tong which are _ Name | Ste cers) * for whole-valued signed numbers? byte | 8 | -128t0127 shor | 16 | -32,76810 32,767 it | 32 _|-2,147.483. 64802, ta aap long | 64 oe = 9,223,372, 036,854,775, 808 19 Scanned with CamScanner& Principles of Programming Languages (SPU) 5 Quick Read Floating-point numbers ‘This group includes float and double, which represent numbers with fractional precision. Name | Size (Bits) Range Moat | 32 | 14e-045 to3.4e+ 038 double} 64 | 4.9e~324to 1.8e + 308 3. Characters: ‘This group includes char, which represents symbols in a character set, like letters and numbers. 4, Boolean ‘+ This group includes Boolean, which is a special type for representing true and false values. + You can use these types as-is, or to construct arrays or your own class types. Thus, they form the basis for all other types of data that you can create. Q.4 What are Strings in Java? Explain following operations of class Stings in Java with example. 1. To find length of the sting 2. To compare two strings 3. Extraction of a character from sting Ans. : TREN I String Handling : String Class Methods + In java everything is class. String is also class. String class provides many methods to manipulate the string. String is object which represents characters sequence. Java implements string as object and not as array. ‘© String class has many methods like compare string, length of the string, getting character, etc. String object can be constructed using many different methods. After creating string object, characters within string cannot be changed. This property of string is called immutable. Which means string is immutable objects. ‘© Ifprogrammer wanted to modify the string during run time then StringBuffer can be used. String class is part of ig Systemoutprint() function, string object is created javalang. Whenever we display some message internally. + System.outpprint("String example"); ‘+ In above statement string object is created for "String example". String is created using many methods. Simple method is given as follows : + String str="This is example string"; «String is displayed using System.outprint() functions, Two strings can be concatenated using + operator. + Program 3.5 gives simple string example. String Constructor String provides almost thirteen constructors which are as shown in Fig, 35. aon Scanned with CamScanner4 7 Various String constructors 1. Stina) 2, Stingtbytell byes) J Stinglbyel bys, Charset charset) 7 Singlbyio[ bytes, int offset, int length) or & Siengtoytel bytes, it offset, int lent ‘Charset charsel) & Sring(bytel] bytes, int offset, int Fength, ‘String charsetName) 7, Suing(bytel| bytes, Sting charsetName)} ‘8. Sting(charl} value) ‘3. Sting(charl] value int offset, int count) ——— 10, Sting(ini]codePoins, int oftset, int count) 11. Sting(String orginal) 42, String(StingButter buffer) 418, String(StingBullder builder) Fig. 3.5 : String constructor string It initializes created String object to empty characters. String(bytet] bytes) “This constructs a new String by decoding the specified array of bytes, String(bytel] bytes, charset charset) “This constructs a new String by decoding the specified array of bytes, String(bytel] bytes, int offset, int ength) , “This constructs a new String by decoding the specified subarray of bytes. String(bytef] bytes, int offset, int length, charset charset) ‘This constructs a new String by decoding the specified subarray of bytes, String(bytel] bytes, int offset, int le th, String charsetName) ‘This constructs a new String by decoding the specified subarray of bytes, String(byte[] bytes, String charsetName) ‘This constructs a new String by decoding the specified array of bytes wick Read @rneiins Scanned with CamScanner& Principles of Programming Languages ($PPU)_—_7. Quick Read a St ia(char[] value) This allocates array argument. ‘new String so that it represerits the sequence of characters currently contained in the character String(char{] value, int offset, int count) ‘This allocates a new String that contains characters from a subarray of the character array argument. 10. String(int{] codePoints, int offset, int count) Th Hocates a new String that contains characters from a subarray of the Unicode code point array argument. 11, String(String original) This initializes a newly created Str argument; 18 object so that it represents the same sequence of characters as the in other words, the newly created string isa copy of the argument string. 12. String(String Buffer buffer) This allocates a new string that contains the sequence of characters currently contained in the string buffer argument. . 13. String(String Builder builder) ‘This allocates a new string that contains the sequence of characters currently contained in the string builder argument. String Operations and Character Extraction + Different operations are possible with string, © One of the famous operations is concatenation, ‘© Two strings can be concatenated. ‘* Concatenation of string, integer, characters, double, float and bytes are also possible. It is possible with + operator. Here + operator acts as concatenation and not addition. © Itmeans in string a + b is concatenation of number and not addition. ‘+, Ifaddition is needed we have to write (a +b). simple program to string operations ppublig elas { \gOperations public static void main(Steingl] args) { ‘System out.peintla("Operations on string in Java"); Original sti ig tel ="another string’; System.out.printhn( Length of string is:" +strlength())s stem.out printhn(*Length of abed is: "abe engthO)s ut printn('Fith position characterin "4st" is: "-FstecharAt(4); rgeiChars(2, 7, buf, Of; n(( Range of characters Qin Scanned with CamScannerRead ciples of Programming Languages (SPPU hae ae 3: : wz using character aay") rnewcharl2 Systemoutprint’ ystemoutprintb(strtaC aera , ) Output : Operations on steing in Java Length of strings: 15 Length of abed iss Fith position charaeter in Original string is: Range of characters + ng using character array Original sting String Comparison + Comparison of two stringiis possible with equals() and equalsignoreCase() method. ‘© Case sensitive comparison is possible with equals() method whereas equalsignoreCase() compares two string in case insensitive manner, But there is difference between equals() method and == operators. ‘+ Equals() method compares two strings character by character. erator compares two object references to check whether they refers to same instance of string. tr will pointing to same object but different reference © String str="hello” will create separate object. String str’ variables. sing object Heap Fig. 3.7.2 ‘+ String tr="Hello"; and String str2=new String str); will create two separate objects, Sting rtorence variable Sting rotornce varabio tin orc vata Fig. 3.7.3 ae @iy SIM Scanned with CamScannerRead Principles of Programming Languages (SPPU} Qu simple program to compare string. public class StringComparision { public static void main(String] args) ( ystem.cut.prinln tring comparison in Java"); System.out printn(str-#" & "+ str1+* are equal? *+ strequal(stel))s String s1 "abe", 2="ABC ‘System.out printin(s1-+" 8 "+ 62-4" are equal with ease sensitive? "+ s1-equals(s2)) NYT stem.out.println(s3+" & "+ 34+" ae equal if ease insensi ring «3="wy2", © + sB.oqualslgnoreCase(et))s System.out.printIn("Use of abe": new String(’abe"); System.out.println(ste3-+ "8" + str } operator”): String #4 are different? "4 (33 + Output : String comparison in Java abeSabe are equal? true abe& ABC are equal with ease sensitive? false aya NYZ are equal if ease insen operator abeSabe are different? : @.5 What is a Constructor ? ‘Ans. : Constructors Acconstructor can be used to set initial values for object attributes. Its a block of code that initializes the newly created object. At the time of calling constructor, memory for the object is allocated in the memory. ‘A constructor resembles an instance method in java but it's not a method as it doesn’t have a return type even void also. Constructor will be invoked by the JVM automatically, whenever you create an object. ina java code, Pee ‘© Constructor has same name as the class and looks like t public class MyClass { (his isthe constructor MyClass() { ) ss name and it doesn’t have a return type. qin Here you can note that the constructor name matches with the cl Scanned with CamScannerW principles of Programming Languages (SPPU)_10 types of cont front typos of constuctr or? Demonstrate wi suitable example te Oe ee ERTS an Types of Java Constructors ‘There are two types of constructors in Java: 4, Default constructor :A constructor that has no parameter is known as default constructor ina class then compiler creates default constructor with no argumer! the value that we passin place of parameters. If we write a constructor with arguments OF Mi the compiler does not crete a default constructor. Default constructor provides the default values to the obj like 0, null, ete. depending on the type. onstructor. Ifwe don’t define a ts for the class. Arguments are ‘arguments then ct mas parameterized constructor. If we 2. Parameterized constructor : A constructor that has parameters is know xd constructor. There are no ‘want to initialize fields of the class with your own values, then use a parameter “return value" statements in constructor, but constructor returns current class instance. We a inside a constructor. Program 1. class Project { int value]; int valueds Project () { valuel = 10; value2 = 20; System.out println( Inside Constructor’) ) public void display() { System.out.printIn('Valuel === *+valuel)s ‘System.outprintin('Value2 === "-+value2); ) public static void main(String argsf]) { Project pl = new Project pldisplay(s } } Scanned with CamScannerint variable int sovibleds Fvamplet Hw { vaviablel © 10; Med = 40: snoutyrinttn(” Nosangunent Camstctn’ public void show() Whn(variablel = "+ variable System.out.print y tublie statie void main(String ans) viable "“ variable2); { Examplel obj = new Examplel Qs ebjarhow 0: ) ) Output: Nonargument Const variable! = 30 ‘arial Program 3 class Example { int variable); Example2g. ( variablel = 15 argument constructor Exampte2(int a) 1 argumen Qin Scanned with CamScanner© Principles of Programming Languages (SPPU)_12 Quick Read t vavabel = a Spstemou prin Svan base Contra b publi wid show { Stem outgvinarabled === "4+ vaiblel) ‘System-out, n{"variable2 “+ variable2); d public static void main(String args[]) t Exampledderived ll = new Example Aaispan + ) clas Fsampleddrved exons Example? ( in variables in valet Exanple2lcrivel) { Nsuper(3)s variable = 3; variable = 45 ‘System.out.printin("The Constructor of Derived"); ) public vid show) t $)stem.ouprintlnVariable System prin Varabed SyetemoutprnltVarabel = Sstem.ou inl Variable , J output: Firat base Constactor The Consuetuof Desived Vurialet == 1 Varible2 Variable Voribled m= 4 Olutions Scanned with CamScannerBF principles of Programming Languages (SPPU 13 Quick Read 2.7 What do you mean by method overioading ? Write a program which adds two integers and tree integors by using ‘overloaded methods for adding two and thee integers respectively Ans. : Overloading Methods + Method Overloading is a feature that allows a class to have multiple methods with same name by chang parameters, Ifwe have to perform only one operation, has same name of the methods increases the readability of the program, * For example you have to perform addition of the given numbers but there can be any number of arguments, if for two parameters, and b(int, int, it) for three parameters then it may be rmmers to understand the behaviour of the method because its name you write the method such as aint, difficult for you as well as other prog Uiffers. So, we perform method overloading to figure out the program quickly. + Different ways to overtoad the method. There are three ways to overload the method in java 1. Number of Parameters For example: scot, int adit en in) Data type of Parameters For example: snl inti) suldGint, Not 3. Sequence of Data type of Parameters For example: atin, lot) alot, int) Invalid ease of method overloading Iftwo methods have same name, same parameters and have different return type, then this is not a valid method overloading. This will throw compilation error. Following example will give a compilation error. in aldQin, int) oat ade int) Advantages of Method Overloading © Method overloading increases the readability of the program, * Overloading in Java is the ability to create multiple methods of the same name, but with different parameters, +The main advantage of this is cleanliness of code. + Method overloading increases the readability of the program. ‘Overloaded methods give programmers the flexibility to calla similar method for different types of data, Overloading is also used on constructors to create new objects given different amounts of data. ‘You must define a return type for each overloaded method. Methods can have different return types. es Scanned with CamScannerPrinciples of Programming Languages (SPPU, 4 k Read Different Ways to Overload Method in Java When you overloading methods, you must check the following rules : 1. Method name must be same. 2, Return type can be anything. 3. Parameters must be changed in one ofthe following three ways a) Type of parameters b) Number of parameters ©) Order of parameters Here is a simple example that illustrates method overloading : Program to demonstrate method overloading. I Demonstrate method overloading, class Arithmetic { void test() { System.out.printin (°No parameters"); y 1M Overload test for one integer parameter. void test(int x) i System.out.printin (%:" + 3}5 ) 1 Overload test for two integer parameters Void test(int x, int y) { System.out.printin (x and yz" +x -+°" + y}i d 1 overload test fora double par Alouble test (double x) t System.out.printin ("double x: , ) class Overload Scanned with CamScannerae SS a WF rinciplesof Programming Languages (SPPU)__15, atest (20): atest (20, result = a.test (150.30); Systemoutprintln (Result of a.test (150-30): ) + result) ) Output: No parameters 20 0 30 double a: 150.30 Re s1(150.30): 2250.09 © As you can see, test( ) Is overloaded four times. The first versioy int seF parameter by passing argument value and 30, and the fourth takes one double param + The n takes no parameters, the second takes one 20, the third takes two integer parameters with argument value 20 neter by taking argument value 150.30. fact that the fourth version of test( ) also returns a value Feturn types do not play a role in overload resolution, {s of no consequence relative to overloading, since 2.8 Give exampie of static declaration, What. restrictions on methods which are declared static ? SIMA ‘Ans. : Static Variables * Static is a non-access specifier in Java. The static keyword in Java is mainly used for memory management. The Keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type. * This means that only one instance of that static member Is created which is shared across all instances of the class. We can apply java static keyword with variables, methods, blocks and nested class. a) Static variables are initialized only once, a the start ofthe executi before the initialization of any instance variables. | These variables will be initialized first, b)__Itisa variable which belongs to the class and not to object(instance). ©) static variable can be accessed directly by the class name and doesn’t need any object. 4) _Assingle copy to be shared by all instances of the class. ‘Static members are common for all the Instances (objects) of the class but non-static members are separate for each instance of class. + Ifyou need to do the computation in order to set your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded. Take a look at the below Java program to understand the usage of Static Block Program to demonstrate the use of static blocks public class BlockEx { static variable static int (rjcasy-solutions Scanned with CamScannerQuick Read ciples of Programming Languages (SPPU)__16 static inthe static Black Systemout.printin (Static block initialized." kairo: b pubic stati void main(Singf] ates) System.outprintln (Inside main method’): Systemoutrintln (Value of is “4i)s Systom.out.printia Value of k: + When you execute the above program, static block gets initialized and displays the values of the initialized variables. Output: Stati block initialized le main method Value ofS Value of be 5 ‘There are a few restrictions imposed on a static method : ‘+ The static method cannot use non-static data member or invoke non-static method directly. ‘* The this and super cannot be used in static context. + The static method can access only static type instonce variable, ‘+ There is no need to create an object of the class to invoke the static method. ‘+ Astatic method cannot be overridden in a subclass. @.9 Slate the use of final keyword in Java. SI Ans. + Keyword final is a non-access specifier in Java. You can declare final as a va contents. Whenever you declare final variable you must need to initialize it. It ‘method or a class. It can be initialized in the constructor only. riable. So, it stops to modify its is applicable only to a variable, a ‘+The blank final variable can be static also which will be initialized inthe static bh reference, t means that the variable cannot be re-bound to reference another object pointed by that reference variable can be changed ie. you can add or rem final collection, It i good practice to represent final variables in all uppercay words. ————— S GHETTO Scanned with CamScanner 'ock only. If the final variable is a object, but internal state of the ‘ove elements from final array oF ©, using underscore to separate| 3. Ablank final variable can be initializ a final variable > SSS final iot PH_INDICATOR = Se, ~ 4 Blank final variable final it PH_INDICATOR: ‘a final sic variable PH. static final double PH = 5.5085 ‘s blank final statie variable static final doable PH Ways to Initialize a final variable: Compiler will throw 2 compile-time error if we have not initialized final variable, I can init initializer or an assignment statement only once. There are three Wi al variable : 1. You can initialize a final variable when itis declare. tinal variable is not initialized while declaration is called blank final variable. Below are the two ways to initialize a blank final v A blank final static variable initialized inside static block, lized by an inside instance-Initializer block o inside constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise compile ti thrown. \e error will be aaa 's CONTIN Scanned with CamScannera & principles of Propramming Languages (SPPU) 18 ck Read ee sos ac eel el Tg Pn Q.1 What is Inheritance ? a Inheritances Inheritance is one ofthe keystones of object-oriented programming because it allows the creation of hierarchical classifications. The process by which one class access the data members (properties) and methods (functionalities) of another class is called inheritance. + The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class. Q..2 List and explain the efferent types of Inheritance, Demonstrate how Java supports Multiple Inheritance. Ta EN ‘Ans. 1. Single Inheritance ‘Single Inheritance refers to a child and parent class relationship where a class extends the another class. Class A Chass B Fig Single inheritance 2. Mattilevel Inheritance It refers to a child and parent class relationship where a class e tends the child cla class B and class B extends class A. child class. For example class C extends Cassa Class 8 4.2: Multilevel inheritance Scanned with CamScannerF principles of Programming Languages (SPPU) 19 3. Hierarchical Inheritance It refers to a child and parent class relationship where more than one classes extends the same class. For example, classes 8, C& D extends the same class A, class8 |} classe || caso Fig. 4.3 : Hierarchical inheritance 4, Multiple Inheritance Ik refers to the concept of one class extending more than one classes, which means a child class has two parent classes. For example : class C extends both classes A and B. Java does not support multiple inheritance. We have illustrated in interfaces section. Class A Ciass 8 Class ¢ Fig. 4.4: Multiple inheritance 5. Hybrid inheritance Combination of more than one types of inheritance ina single program. For example : class A & B extends class C and another class D extends class A then this isa hybrid inheritance example because its a combination of single and hierarchical inheritance. Program impo java.io.*: lane CFG { public statie void main(String} args) { dog AI ~ new dogl): dt dL runt); ete = new eats eLatwew ml) ) ) PEI Scanned with CamScannerW principles of Programming Languages csppu)____20 Quick Read { public void run() { String names String colours stem.out:printh is running’)s y y ‘lass dog extends Animal ‘ public Void bark0) { System.out.printla("wachtwooht dogris bas } public void run) 4 ‘System.out printin("dog is running); } ) ‘lass eat extends Animal 4 public void mew 4 System.out printn(*meww! meww!"); y } ‘Output: ‘wooh!wooh! dog is barking dog is running @.3 What are advantages of using inheritance? Ea mA ‘Ans. : Advantages of Inheritance Nottimited in ova, but in Genera Inheritance in Object Oriented Programming has ot of advantages, ‘Advantages : + Ithelps in code reuse. ‘+ Ithelps to avoid redundancy of code in subclass by inheriting from superclass © Saves time and effort as the main code need not be written + Inheritance provides a clear movel structure which i asy to understand without much ithout much complexit Using inheritance, classes become grouped together ina hie cies divided into parent and child classes. ae “archical ree stricture Code are easy to manage and Scanned with CamScannerpencils of Prowamming Languages (SPU) 2 een + Asthe existing code reused, it leads to less development and maintenance costs. «Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. Ifthe return type of a method is superclass. + Reusability - Reusability enhanced reliability. The base class code will be already tested and debugge to use public methods of base class without rewriting th + Extensi ity - extending the base class logic as per business logic of the derived class. + Data hiding - base class can decide to keep some data private so that it cannot be alte sd by the derived class + Overriding -With inheritance, we will be able to override the methods of th implementation of the base class method can be designed in the derived class. base class so that meaningful One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related c be refactored to move the common code up to a mutual superclas: organization of code and smaller, simpler compilation units. ses, the hierarchy can is also tends to result in a better @.4 What is method overriding in Java? What is advantage of using overtiding 7 Demonstrate method overriding with SEAL EET Ans. : Method Overriding © Ded ing a method in subclass which is already presen is done so that a child class can give its own i lass, superclass is known as m hod overriding, Overriding jplementation to a method which is already provided by the parent this case the method in parent class is called overridden method and the method in child class i ferriding method. Method Overriding Example called Let's take 2 one example to understand this. We have two classes: A derived class Monkey and a base class Animal. The Monkey class extends Animal class. Both the classes have a common method void jump(). Monkey lass is giving its own implementation to the jump() method or in other words it is overriding the jump() method Th purpose of Method Overriding is clear here. Derived class wants to give its own implementation so that it calls this method, it prints Monkey is jumping instead of Animal is jumping, Program ase Animal (nerritden metho spall seid yurmpdy Aninmal i jumping’): lane Monkey exterabe Anitnal veering ret Ss Conon Scanned with CamScannerpublic void eat) { ‘System.oat-println('M ) public static void main( String args [) { Monkey obj = new Monkey): cy is jumping "This will call the child class version of eat) */ ‘obj,jumpQs ) Output : Monkey is jumping ‘Advantages of method overriding ‘+The main advantage of method overriding is that the class can give its own specific implementation to an inherited method without even modifying the parent class code. This is helpful when a class has several child classes, so if child class needs to use the parent class method, it ‘an use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code. ©.5 What is Polymorphism ? Which type of polymorphism is method overriding ? ‘Ans. : Polymorphism + Itrefers to ability to take more than one form in the programming, \Which behaviour to use totally depends upon type of data used in the operation, If we consider the simple case of addition of two number. If we sid Ree call the Functions with two number then function But if we pass two different strings then instead of addition, conca performed automatically * Soncatenation of string operation should be Polymorphism can be compile time polymorphism and run time Compile time polymorphism is possible with polymorphism is possible with virtual functions. Polymorphism example is shown in Fig, 45. polymorphism. function and o mand operator overloading whereas run time ee fectaragle Draw staat) Scanned with CamScannerfee re eee Cee (rr ee i Read + As shown in the Fig. 45, wh functions. © If we are passing radius and centre coordis.ates then circle type of Draw_shape() should get called. If we passing just one side then Draw shape() for square should get called and so on. Another example is shown in below Fig. 46 ‘h Draw-shape() to call is totally depend upon the number of parameters to Liquid add) romove() svar) Cotteo Mk Tea ‘wiel() remove() | |roadFuture) swirl) | Fig. 4.6 @.6 Explain the concept of dynamic dispatch while overriding method in inheritance. Give example and advantages of doing so. ‘Ans. : Dynamic Method Dispatch '* Method Overriding is an example of runtime polymorphism. When a parent class reference points to the cl class object then the call to the overridden method is determined at runtime, because during method call which method (parent class or child class) is to be executed is determined by the type of object. This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch, © Let’s see an example to understand this. Program class A { Overridden method publi void display() { System out printla(display( method of parent class”) ) class Demo extends ABC ( HOversiding method publi void display() { ‘System.out.println(*display() method of Child class"); y publi void newMlehod) sz eae arin ESS? Scanned with CamScanner& Principles of Programming Languages (SPPU)__24 Quick Read ( System.out.println(“new method of child class”): } public static void maing String args{)) { /* When Parent class reference refers to the patent class object then inthis ease overridden method (the methoa of parent class)isealled.*/ ABC obj = new ABCO: objadisp 0s /* When parent class reference refers tothe child class object then the overriding method (method of child class) is called. This is called dynamic method dispatch and runtime polymorphism*/ A obj2 = new Show(); ‘obj2.display(); ) Output : splay method of parent class isplay() method of Childelass ‘+ In the above example the call to the display() method using second object (obj2) is runtime polymorphism (or dynamic method dispatch). Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overfdden ‘methods of base class but it cannct call the methods wich are newly declared in the child class. in the above ‘example the object obj2 is caling the disp(). + However, if you try to call the newMethod() method (which has been newly declared in De mo cl obj2 then you would give compilation error with the following messages : Joss) using a © Exception in thread “mai walang.Erro:. © Unresolved compilation problem. ©The method xy() is undefined for the type ABC. Advantages of Dynamic Method Dispatch + Dynamic method dispatch allows Java to support overriding of methods which polymorphism, central for run-time + Itallows a class to specify methods that will be common to all of its deny lerivatives, while allowin sses to define the specific implementation of some or all of those methods, es, while allowing subclasses t It also allows subclasses to adi its specific methods subclasses to defin those methods. e the specific implementation of some of +The main advantage of method overriding is that the class ean give its ow inherited method without even modifying the parent class code. ™ specific implementation to an ‘+ This s helpful when a class has several child classes, so fa child class needs to use can use it and the other classes that want to have differ = changes without touching the parent class code. the parent class method, it “ent Implementation can use overriding feature to make [cryeasy-solutions at Scanned with CamScannerQuick Read 1 Principles of Programming Languages (SPU) 25 0.7 state the difference with examples : Static and Dynamic Dispatch. ‘Ans. : Difference between Static and Dynamic Dispatch + Dispatch is the act of sending something s »mewhere. In computer science, this term is used STAT + To indicate the same concept in different contexts, like to dispatch a call to a function, dispatch an event to a listener, dispatch an interrupt to a handler or dispatch a process to the CPU. ‘+ There are two forms of dispatch, statie and dynamic. The former means that a call toa method is resolved at compile time and the latter means that is resolved at run time. Table 4.1 : Difference between static and dynamic dispatch Sr. ‘Static Dispatch Dynamic Dispatch No. | 1. | Static dispatch (or early binding) happens when | Dynamic dispatch (or run-time dispatch or virtual ‘method call or late binding) happens when I defer that decision to run time. This runtime dispatch requires either an indirect call through a function pointer, or a name-based method lookup. know at compile time which function body will be executed when I call a method 2. | Some languages allow us to use a special method call syntax to force static dispatch. This is useful when we want to avoid open recursion, eg. to make our base class more robust against Some languages allow function call syntax for methods. In such a case, the programmer selects the fully qualified name of the method, so no dynamic dispatch isnecessary. changes in subclasses. FTI Q.8 State the use of Abstract class in Java 17, May ‘Ans. : Abstract classes ‘© Anabstract class is one that is not used to build objects, but only as a basis for creation subclasses. An abstract class exists only to express the common things of all its subclasses. © Aclass that is not abstract is said to be concrete. You can create objects belonging to a concrete class, but not to an abstract class. *Avariable whose type is given by an abstract class can only refer to objects that belong to concrete subclasses of the abstract class. + A“abstract” keyword is known as abstract class which is declared using class, It can have abstract function {function without body) as well as concrete function (regular methods with body). ‘© Arnormal class(non-abstract class) cannot have abstract methods. In this subsection you will learn what is a abstract class?, why you use it and what are the rules that you must remember while working with it in Java. ‘© Anabstract class can not be instantiated, which means you are not allowed to create an object of it. Why? Why require an abstract class? «Let's say we have a class Animal that has a method sound() and the subclasses of it like Dog, Lion, Horse, Cat ete Since the animal sound differs from one animal to another, there is no point to implement this method in parent class, This is because every child class must override this method to give its own implementation details, like Lion class will say “Roar” in this method and Dog class will say “Woo? So when we know that all the animal child classes will and should override this method, then there is no point to implement this method in parent class. Thus, making this method abstract would be the good choice as by tnaking this method abstract we force all the sub classes to implement this method( otherwise you will get compilation error), also we need not to give any implementation to this method in parent class easy-solu Scanned with CamScannerPrinciples of Programming Languages (SPP 26. ‘© Since the Animal class has + Now each animal must have a sound, by making this me give implementation detail ‘2.9 Explain the folowing Java concepis and state the clifer ‘an abstract method, you must need thod abstract we made it compulsory to the child class to is to this method. This way we ensures that eve rence with examples : Interface and Abstract class. ick to declare this class abstract. ry animal has a sound. Ee Interface Class ‘Abstract class 1. | im Java, interface is a reserved word with an additional, technical meaning, An “interface” in this sense consists of a set of instance method interfaces, without any -—_ associated implementations. It is similar to class. It is 2 collection of abstract methods. ‘A class that is declared using “abstract” keywor known as abstract class. It can have abstract methods (methods without body) as well as concrete methods {regular methods with body). A normal class (non- abstract class) cannot have abstract methods. interface keyword an interface can never be ‘abstract keyword is used to create an abstract class in java. Ifa class have abstract methods, then { // declare constant fields // declare methods that abstract instantiated as the methods are unable to perform any action on invoking. the class should also be abstract using abstract keyword, else itwill not compile. 3.__| //Declaration using interface keyword [Declaration using abstract keyword Interface
Abstract
{//This is abstract method //Thisis concrete method with body Output : implementation of myMethod } //by default. { //Does something} 3 4 | Brample: Example: Interface Mylnterface /abstract parent class { abstract class Animal 7" compiler will treat them as: public abstract void | { paiva meting, mabe P i ase abstract vold soundQ; class Show implements Mylnterface ‘ Heat class extends Animal class /* This class must have to implement the abstract | Ne das Catertends Animal myMethod otherwise it will get compilation error a public void sound() public void myMethod() s { System.outprintin (CMaw’); Sysemoutprinta implementation of } ; ‘myMethod” 1 Public static voi ; ; 'evoid main(String args(]) public static void main(String arg(]) Animal obj=newCat() fl js is obj Mylnterface obj=newShow(); eee obj.myMethod(); ) ) Output: } Maw Fe asy-solutions, Scanned with CamScanner& principles of Programming Languay (orpu) 27 Quick Read .10 What is mean by Packages in Java’? Explain with sultable oxamplo EQUI Ans. : Defining a Package A Package can be defined as container that grouping of related types (classes, interfaces, annotations and enumerations) providing access protection and namespace management. Like all subroutines in Java, the routines in the standard APLare grouped into cass: ‘To provide larger-scale organization, classes in Java can be grouped into packages. One of the sub-packages of java, for example: is called "awe", Since aw “ontained within java, its full name is actually java.awt. This package contains classes that represent GUI components such as buttons and menus in the AWT, the older of the two Java GUI toolboxes, which is no longer widely used. However, javaawt also contains a number of classes that form the foundatioi for all GUI programming, such as the Graphics class which provides routines for drawing on the screen, the Color class which represents colors and the Font class which represents the fonts that are used to display characters on the screen. Since these lasses are contained in the package java.aw, their full names are actually javaawt.Graphics, java.awt.Color and javaawtFont. Similarly, javax contains a sub-package named javaxswing, which includes such classes as javax.swingJButton, javaxswingJMenu, and javaxswingJFrame, The GUI classes in javaxswing, together with the foundational classes in java.awt, are all part ofthe API that makes i possible to program graphical user interfaces in Java. ‘The jaya package includes several other sub-packages, such as java.io, which provides facilities for input/output, java.net, which deals with network communication, and java.util, which provides avariety of utility” classes. The ‘most basic package is called java.lang, This package contains fundamental classes such as String, Math, Integer, and Double. It might be helpful to look at a graphical representation of the levels of nesting in the java package, its sub- packages, the classes in those sub-packages, and the subroutines in those classes. This is not a complete picture, since it shows only a very few of the many items in each element. Finding Packages and Classpath © Ajjava package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, aw, javax, swing, net, fo, util, sql ete, ©The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment. The library is divided into packages and classes. Meaning you can cither import a single class (along with its ‘methods and attributes), or a whole package that cont all the classes that belong to the specified package. « Tousea class ora package from the library, you need to use the linport keyword, Syntax import package-name,Class: W class mport packagesname.*s i anport the whole package ‘import java.util Scanner; In the example above, java.util is a package, while Scanner fs class of the java.util package. Cano Scanned with CamScanner3 Principles of Programming Languages (SPPU)___28 Quick Read Consider the following scene of a movie : “Humphrey Bogart has just killed the German Commander in front of the Chief of Police. The Chief then calls his office and informs them that the Commander has been murdered, and that they should round up the usual suspects”. For Java, the CLASSPATH variable is alist of the usual suspects. When Java wants to find a class file, it looks in all the directories that are listed in the CLASSPATH. In order to have Java look in new places, just add more paths to the CLASSPATH variable. ("There are also system paths that are searched that are not liste What is a Package? the CLASSPATH) * The simplest definition of a package is a folder that contains java class files. However, packages do more than that. They also indicate where a java class can be found, Essentially, packages allow for an extension to the CLASSPATH list, without adding new paths to it If'a class file is in a package named sandy, then Java will look in all the paths in the CLASSPATH with sandy appended to them. For example, suppose the CLASSPATH contains : W— rayData HmyFiles ‘+ _ Java will then look for the class fie in, WM amyData/sandy I myFiles/sandy ‘As a more complicated example, suppose the package is skf.cg124.sk, then Java will look for the class file in, Ms myDatalskifegl24/ak M1 myFiles/skleg] 24/sk @.11 How is access protection provided for packages ? ‘Ans. : Access Prote * You can see, many levels of protection to allow well control over the visibility of variables dnd functi les an ions within classes, subclasses, and packages by Java platform, Packages act as containers for classes and other subordinate packages, Classes and packages are both means of ‘encapsulating and containing the name space and scope of variables and meth data and code. The class is Java's smallest unit of abstraction. Because of th packages, Java addresses four categories of visibility for class members : © Subclasses in the same package. ‘ods. Classes act as containers for interplay between classes and © Non-subclasses in the same package. © Subclasses in different package. (© Classes that are neither in the same package nor subclasses. The three access modifiers, private, public, and protected, provide a variety of way of access required by these categories. Table 4.2 sums up the interactions, © MPS Produce the many levels While Java's access control mechanism may seem complicated, we can sim public can be accessed from anywhere Le. in same class, outside of elass an ‘Anything declared private cannot be seen outside of its class, When specification, itis visible to subelasses as wi you want to allow an element to be s class directly, then declare that el lity it as follows. A lows. Anything declared id end method of program, d a member does ell as to other classes in the s en outside your current pack int protected. 's not have an explicit access backage. This is the default access: If but only to elas: 's that childelass your ene @s GMM Scanned with CamScanner~. & Pringples otProgramming Languages (SPP) __29 Quick Read + Table 4.2 relates only to members of classes. class has only two possible access levels: default and public. When a class is declared as public, itis accessible by any other code. Ifa class has default access, then it can only be accessed by other code within its same package. Table 4.2: Access Modifi YE Public | Private | Protected | No Modifier No: | Same dass ~ |= v | | Same package subclass v |= v_ lo Same package non-subclass allan vl : Different package subclass v x al x Ditferen package nonsubcass| _~ |» x | * Q. 12 What s an Interface in Java? How is this diferent than a class? Give example of interface. EEA 1y 19 6 Marks Ans.: * Definition : In Java, interface is a reserved word with an additional, technical meaning. An “interface” in this, ‘sense consists of a set of instance method interfaces, without any associated implementations. It is similar to class. Itis a collection of abstract methods. Exampl access_specifier interface interface_name { zeturn_type method_namel (parameters); return _type method_name2(parameter_list: type final_variable_name! ‘ype final _variable-name2- [After JDK 8, java permits interface to have default implementation for any method, But itis still infrequent in programming and original purpose of interface has remained same. Variables are not instance variable. They serve as constants and cannot be changes by any implementing class. ‘They can be defined inside interface but they are implicitly final and static. ‘© Allvariables methods and are implicitly public in interface. Implementation : ‘A class can implement an interface by providing an implementation for each of the methods specified by the interface. Here is an example of avery simple Java interface : Public interface Shapes { public void draw(Graphies 2) @s GSES Scanned with CamScannerQuick Read hod is omitted. A class - draw() met defnition, except thatthe implementation of the an eo, the class can also ‘« This looks much like a class “de an implementation for this method. that implements the interface Shapes must provi include other methods and. variables. For example: . ; public class Circle implements Shapes f Con Ses public void draw(Graphics e) ‘ Paes «fl do somelling, dra a Circle Epcos = y = a : sll other methods and variables. <= a Jeter hes iH : Note that to implement an interface, a class must do more than simply provide an implementation for each method in the interface; it must also state that it implements the interface, using the reserved word implements asin this example “public dass Cirele implements Shapes". + Any lass that implements the Shapes interface defines a draw() instance method. Any object created from such a class includes a draw0 method, Nested Interface Java permits to write nested interfaces. One interface can be member of another interface or class. ‘Annested interface is also called member interface and can be declared as public private or protected, Note that the top level interface must be declared as public or default. ‘+ Ifanested interface is used outside the enclo with dot operator (.). scope, it must be specified with name of outer class or interface It enable us to logically group classes that are only used in one place, write more readable and maintainable code and increase encapsulation. Program 1. . imterfuce Callable { void displayMsp(String mse): public interface Callablelnt n publi void display Num(int num); : ) x ee : } ‘ class Seren implements Cla Callblelnt ( void display Nurn(int n) System.out.printIn(’Numbee i "en a ree Scanned with CamScannerW principles of Programming Languages (SPPU) 31. Quick Read + lass InterfaceController public static void { Callable.Callablefnt e: n(String ares) new Sereen()s edisplayNum(10); } } Output: Number is $10 * Inthe above example outer interface is Callable and inner interface is CallableInt. Applying Interface : + An application of interface can be understood by considering and extracts of an abstract java application where Animal interface will define the must have methods for implementing classes. ¢Letus call the interface as MotionAnimal. Example: interface Motion Animal { public void run; z public void walks public void jumpQs } 4 © Hence this interface define that any class which will implement Motion Animal must provide the implementation ofthese three inethods. Itreal world translation, all animals should be able to run, walk and jump. sn be interacted and what the capabilities of animal object. It also ‘one can get a clear idea of capabilities of animal object and the * Interface specifies how an animal object ca serves an objective. By just sighted the Interface, ways to interact with it. Program 2 inter { printable void prints , class 6 implesments print { public void print() { <<< Scanned with CamScanner3 exinciples of Programming Languages (SPPU)__32 Quick Read cemoat println( Welcome”): public static void main(String args{)) Welcome, : . In the above example, the Printable interface has only one method, and its implementation is provided In the A6 dass @.13 Stzte two major ciferences in class and interface. “Interface gives multiple inheritance facility just as in C++" justify. Eons [eT Ans.: (Cass and Interface both are used to create new reference types. A class is a collection of fields and functions that ‘operate on fields. An interface has fully abstract methods Le. methods with no body. An interface is syntactically similar to the class but there is a major difference between class and interface that is a class can be instantiated, but an interface can never be instantiated. Some difference between a class and interface is given as in Table 4.6.2. Table 4.3 : Difference between a class and interface | comparison Class - Interface | Basie ‘Aclass is instantiated tocreate objects. | An interface can never be instantiated as the methods are unable to perform any action on invoking. | Keyword Class Interface ‘Access Modifiers | The members of a class can be private, | The members of an interface are always public or protected. public. Methods The methods of a class are defined to| The methods in an interface are purely perform a specific action. abstract. cee nese ert ‘An interface can extend multiple interfaces | interface and can extend only one class. but can not implement any interface. | Constructor A class can have constructors to initialize ‘An interface can never have a constructor i the variables. as there is hardly any variable to initialize. Yea: Interface gives multiple inheritance facility just as in C++ because when one class extends more than one sees then this is called multiple inheritance. For example: Class Z extends class X and ¥ then this ype Of feheritance is known as multiple inheritance ava doesnt allow multiple inheritance, as Scanned with CamScannerW principles of Programming Languages (SPPU) 33 Quick Read ® As we have explained in the inheritance, multiple inheritance is not supported in the case of class because of ambiguity. However, it fs supported in case of an interface because there is no ambiguity. It Is because its implementation is provided by the implementation class. + Yes, we can implement more than on example, interfaces in our program because that does not cause any ambiguity for Program terface X 4 public void myFune() } interface ¥ { publie void myFune(); yClass iniplements X, Y public void myFune() ‘ System.out.printhiCMore than one imerfaes implements); + publie static void main(Stcingares)) t MyClassobj-newhlyClass0; abj.nyFunes + Output : More than on nterfaces implements 1G. 14 Define the term exception and advantages of Exception Handling. ‘Ans. : Exceptior + Exceptions are nothing but the runtime errors. It generally alters the low of program execution. When exception occurs, program execution stops and terminates the program abnormally. Program execution does not continue. In this situation we get system generated error on screen. +The statement after the instructions which causes exceptions does not get executed. It is not always acceptable to terminate program abnormally. In safety critical applications it not acceptable to terminate program abnormally. Exceptions occur due to so many reasons. Some of the reasons are as follows © Invalid input © File notavailable mAeasy-solutions) Scanned with CamScannerBF Principles of Programming Languages (SPPU)__34 Quick Read © Network error © Insufficient memory © Improper use of array Some of the real time ‘exceptions are © Weare trying to divide the number! ‘by zero. Weare trying to open ile whichis not existing. Weare storing incompatible value in array. RAM is not enough to load your program, ‘We are trying to access address which is pointing to null, Improper type conversion SQL errors . 00000 Advantages of Exception Handling ‘+ The core advantage of exception handlin %@ 15 to maintain the normal flow of the application, An exception ‘normally distupts the normal flow ofthe application that is why we use exception handling. + Lot's takea scenari statement 1; statement 2; ° © statement 3; © statement 4; © statement 5; //exception occurs (© statement 6; (© statement 7; © statement 8; © statement 9; statement 10; n exception at stateme re to 10 will not be executed. If arent S, the rest of the We Perform exception handling, the rest of the statement willbe executed Thats why we use exception handling in reat SrOup together errors ‘enable us to handle related handler. When an enna 3°e Felated. This wil of one of the exception classes is "eption is thrown, an object Inheritance hi tions. Thus, an excepti an exception OF can catch ex classes, ‘ceptions of any of its sub- ‘The ability to propagate errors up the call stack and another! important advanta oriented programming isthe abilty to propagate errors up the eal stack, 48° Of €Ceptlon handling in object Exception handling allows contextual Information to be ea Propagate it toa point where it can be effectively handled, ured at the point where the error occurs and to Scanned with CamScannerWF Principles of Programming Languages (SPPU) 35, Quick Read Q.15 What is an exception in Java ? What do you mean by handling an exception ? Give example to show the use of try(), Catch ) methods, SA Aaa Ans. * A lava exception is an object that describes an exceptional (that fs, error) condition that has occurred in a piece ‘of code, When an exceptional condition arises, an object representing that exception is created and throw in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller ofa method. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally, Briefly, here is how they work, Program statements that you want to monitor for exceptions are contained within a try block. if an exception occurs within the try bloc, itis thrown. Your code can catch this exception (using catch) and handle it in some rational manner, System-generated exceptions are automatically thrown by the Java runtime system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is putin a finally block. * The general form of an exception-handling block is as follows : ty { / block of code to monitor for errors } catch(Exeeption'Typel exOb) { M1 exception handle for ExeeptionTypel } ‘atch(ExceptionType2 exOb) { exception handler for BxceptionType2 } W. finally { I block of eade to be executed before try block ends } Here, Exception ‘Type is the type of exception that has occurred. Exception Types, + All exception types are subclasses of the builtin class Throwable, Thus, Throwable Is atthe top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exce distinct branches. One branch is headed by Exception is eas used for exceptional conditions that user Programs should eat, This aso the clas that you wl sub as wo ereate Your own custom exception types. There is an important subclass of Fxceptlon, called RuntimeException, txceptions of thie wpe en a ann ptions into two te Scanned with CamScannerSF vrinciples of Programming Languages (SPPU) __36 Quick Read automatically defined for the programs that you write and include things such as division by zero and invalid array indexing, * The other branch is topped by Error, which defines exceptions that are not: ‘expected to be caught under normal Lrcumstances by your program. Exceptions of type Error are used by the Java rin-time system to indicate errors having to do with the run-time ‘environment itself. Stack overfiow is an example of such an error. These typeof Errors aré typically created in response to catastrophic failures that cannot usually be handled by your program. ‘The top-level exception hierarchy is shown in Fig.7, Throwable Exception Error RunTimeException Fig. 4.7 : Top-tevel exception hierarchy Uncaught Exceptions * Before you learn how to handle exceptions in your program, {t's useful to see what happens when you don't ‘handle them. This small program includes an expression that in . n ‘entionally causes a divide-by-zero error. class DivByZero { pblic statie void args{)) { int mum =30, natput= num ums y ) * When the Java run-time system detects the attempt to divide by zero, it constn » it constructs a new e n object an {hen throws this exception. This causes the execution of DivByzero to stop, eee atowntion abject and Ppecause once an exception has been ‘hrown iemust be caught by an exception handler and dele with immediately,” One 3” €xCePton has b Try and Catch Blocks 7 * lava provides exception handling mechanism in the form of ry and eatch black, Using rc ) two advantages: ' try-catch block provid First exception will not cause program to end abruptly if successflly caught, Second, user can specify ts ow operation to recover from exception In cateh block, + Any code that can generate the exception is enclosed In try block. So we simply put inside try bo code that we want to monitor. try block, the entire Scanned with CamScanner© Principles of Programming Languages (SPPU) 37 Quick Read ‘+ eatech block immediately follows the try block and it contains the code that will only execute if exception is generated and caught successfully. So any recovery code, alternate code or message to user can be encapsulated incatch, catch specifies the exception type that we wish to catch. Ifthe generated exception type is matched with the one specified in catch, exception is considered to be successfully caught. {et us consider a simple example demonstrating try and catch block operation as shown in the following example, Program lass DivByZero. ( Public static void matnString arg{)) t int num, num try, s t sum =05 sum? =62/ num System.out-priptla(num2}; + entoh(AritlimeticException ¢) { System.out println("You should not divide a number by zero"): + ceateh(Exeeption o) { ‘System.out.printla("Exeeption occurred); Systeme printn("Ym out of ty-cateh block in Java.”); You should not divide a number by zer0 1m out of try-cateh block in Java. * Notice that the call to printin() inside the try block is never executed. Once an exception is throw control transfers out ofthe try block into the catch block, Put differently, catch is not “cal “returns” to the try block from a catch, Thus the line "You should not dividea number by Once the catch statement has executed, program control continues with the next line in the entire try / catch mechanism. Program led,” so execution never Zero." is not displayed, the program following @s EEO ‘Scanned with CamScanneruick Rea W Principles of Programming Languages (SPPU) 38 a rm a unit. The scope of the catch clause is restricted to those statements specified nt A catch statement cannot catch an exception thrown by another try scribed shortly), The statements that are protected by use try on a single ‘© Atryand its catch statement fo by the immediately preceding try stateme statement (except in the case of nested try statements, de try must be surrounded by curly braces. (That is, they must be within a block, You cannot statement, G16 How does Java manage Input / Quiput using Streams ? Diferentiate Byte Stream, Character Steam and Prodchined Stream ? SRE Ans, : Managing YO Java provides 1/0 Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, 1/0 devise, other program etc. Based on the data they handle there are two types of streams 1, Byte Streams : These handle data in bytes (8 bits) Le, the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc. Byte Stream. Byte streams process data byte by byte (8 bits). For example FilelnputStream is used to read from source and FileOutputStream to write tothe destination. 2. Character Streams ; These handle data in 16 bit Unicode. Using these you can read and write text data only. ‘The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Whereas the InputStream and OutputStream classes (abstract) are the super classes of all the input/output ‘stream classes: classes that are used to read/write a stream of bytes. When to use Character Stream over Byte Stream ? In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files, These text files can be processed character by character. A character size is typically 16 bits. ‘When to use Byte Stream over Character Stream? Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files. ‘+The main difference between Byte Stream and Character Stream in Java is that the Byte Stream helps to perform input and output operations of 8-bit bytes while the Character Stream helps to perform input and ‘output operations of 16-bit Unicode. A stream is a sequence of data that is available over time a + Fileis important medium for permanent data storage. Along with le, 1/0 is also one ofthe important concept java programming. Many time programs need input and need to store output: Java provides many classes f yo system. Data source can be keyboard, file, network connections, array, etc, Wy classes for 1/0 + Data destination can be console output with monitors, output to file, out ¢ e, output to network connection data from keyboard, fle and network connections. Concépts of streams are provided to handle d image data, Data storage medium can be different but it can be manipulated using streams onl i eee ee will see in greater details concept of 1/0 streams. ly. In subsequent topic we @.17 Define the Streams. ‘Ans. : Streams ‘© stream is nothing but sequence of data. Its nothing but flow of data for reading and wrth index is not supported in stream All nput output is supported using stream concept. = '6 Purpose. Concept of ee Scanned with CamScannerPrinciples of Programming Languages (SPPU)____39 Quick Read ‘+ all the streams can be divided into input and output stream, Data input that is reading is possible with input stream whereas data storage that is writing is possible with output stream. Stream supports many kind of data including byte, characters, objects, etc. * OutputStream : Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. + InputStream : Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket. * Input / output stream is shown in Fig, 48 File Console Socket File Console Socket . InputStream OutputStream ava Source TOTOTOIOI }} gp sreton [L1010101010 }] Destination Fad 5 write Fig, 4.8: Input output streams ‘+ Input and output streams are again divided into byte and character stream, Its decided by type of data flow from stream. If we pass byte data then itis byte stream. If we pass character data, then it character stream © ByteStreams © CharacterStreams <
‘Stream ‘
> -
> InputStream OutputStream, ak ByleOulputStream Bytelnputstroam | [CharacterOurputStrean| { [Praratornpatsiear 9: Stream types 18 Whatis Byto Streams ? State any two examples of each Byte Stream classes for VO in Java SESSA + ByteStream + Itprovides easy way to handle input and output of bytes. Itis used while reading or writing binary data, Byte streams are implemented by two main classes for input and output purposes naniely InputStream a4 OutputStream. + They are called byte-oriented because they read or write 8-bit (byte). These classes are generally used to read and write non-character or binary data. @ SED Scanned with CamScanner. nick Read [ByteArrayOutputStreany eae [ObjectOutputSteam PipedOuputSteam ByleArrayinputStream ButiereainputStream FileInputStream [ObjectinputStream InpuiStream [LineNumberinputStean] ByteStroam [PushbackinputSteam PipedinputStream [SequenceinputStream [StingButternputStrea ig. 4.11 : ByteStream classes InputStream OutputStream Fig. 4.10 : ByteStream Table 4.4 Stream class Description Bufferedinputstream | Used for Buffered Input Stream. BufferedOutputstream | Used for Buffered Output Stream, DatainputStream Contains method for reading java standard datatype DasgOurputStream _| An output stream that contain method for writing java standard daw type. FilelnputStream Input stream that reads from a file FileOutputStream Output stream that write toa file. Inputstream Abstract class that describe stream input, OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print) and + Inthis section impo: it byte class will be Program 1 {import java.io. 5 Public class FilelnpuStreamnbxumple { void main(String! args) { System.out print! his is example of Scanned with CamScanner& Prints of romramming Languages (SPPU) At ae uy { FielnputStreami £= now FileInputStream(*Filelnput.ts"); int =05 System.out.println “Available data:"+fayailable(); wwhile((i=fxead)!==1) F : * System.out.prit (chars } ; System.out.printla("Available ‘datas"+ available); } si catch(Exeeption ©) | { fl $System.out.printla(Specifed file not found’); i 2 } } Output : ‘This is example of File input Stream Available data:44. ‘This is example of file input steam in java Available date:0 0 write data in file. Data can be written in byte format only. It also throws FileOutputStream : It is used t handled otherwise program will not get compiled. FileNotFoundException which should be Program 2 import javaio.*s public class FileOutputStreamExample { publie state void main(String args) { uy ‘ 3 1 = new FileOutputStream("examplectst"); FileQutputStream fou wil be written in fle example.tat" +") fou can cheek out by oper ng sting into byte array Byteb{|=s.petByte four.write()s Four.closeOs Scanned with CamScannerick Rea 3 Pinciples of Programming Languages (SPPU)_42 ~ Quik Read y Se ceatch(Exeeption ¢) i q neat creed Gia Seat et System.out.printin(e}; 3 uae here SRG + 3 a output : Data Successfully witén in file! Contents of example.tat sega ieee ous ‘This string willbe written in file example.tet you can check out by’ ByteArrayinputStream : In this option byte aray will be act as‘input to program instead of fils. It means data France Gn be Me array, Keyboard, network connections etc. Constructors of class will take argument as byte array. ‘We can get specified bytes from byt array also, Program 493 shows the construction of BytearrayinputStream. Program3 opening file from current directory ior capac public 4 { byteb[) ste getBytes(); ‘ned to extract byes from string on ; ByteArraylnputStram banew ByteAraylnpitSiream(b); i System.out prinln(Suecesfully read data from ara") saya ge a imtamba-eal)s piace while(al=-t) : : outst t i ) ‘ : ) i } Output : ‘This is example of byte array as input stream Successfully ead data fron array S ‘This is string for byte array ByteArrayOutputStream : It is use ByteArrayOutputStream, Scanned with CamScannerprinciples of Programming Languages (SPPU)___43 warn Program 4 import javajo.ByteArayOutputStream; import java.io JOException; public class ByteArray uypuiStreamESample ( public static void main(String] args) t System.outy Hln( This is example of byte aray as output stream): BytedrrayOutputSizeam be vew ByteArrayOutputStream()s String ste his is string for writing in byte areay" Muced to extract bytes from string uy 4 Da. ite(b): ) ceatch(IOException e) { ystem.out.println( Error in writing data’); ) S)stem.out.printin(*Reading data from output stream"); System.out print((char)eli)); } Output : This is example of byte array as output stream Reading data from output stream Thins string for writing in byte array Bufferedtnputstream = I is used to read information fTom stream. It provides buffering to input stream for Performance purposes. It attaches memory buffer to stream. Java's BufferedinputStream class allows ‘YoU to “wrap ‘ay Input Stream into a buffered stream and achieve this performance improvement. &E oo, Scanned with CamScanner eeeiM Quick Read W Principles of Programming Languages (SPU) ___44 Program 5 import java.i.BufTeredluputStream; pot jovaoFilelnpuStream; public class Buffered nputExample ( ble sai void main(String age) { : Z ‘System.out.printin("Buffered input stream ‘example\n" e ty t FlelnpuSteam fin = new FiletnputStceam(‘exsimplen BufferedInputStream bin = new ‘BufferedInputStream(fin); o ints while((bin. read)! =1) i : ‘System. out.print((char)i); 3 = } bincloseg; fin.close(); e } cateh( Exception «) ‘ Me ‘System.out.print!n(c); ) ) ) Output: Buffered input stream exemple ‘Tis string ie for realing by buffered input stream example Buffered Output Stream : Java But ‘more efficiency than to write data direct Program 6 lass Hulfered Output Example { public staie void main(String arg (I) throws Exception ee Scanned with CamScannerF principles of Programming Languages (SPPU) 45 Quick Read t FileOutputStream fout = new FileOutputStream("example.txt"); BulferedOutputStream bout = new BufferedOutputStream(fout); Strings="This string byte bf]=s.getBytes(); Doutawtite(b); Dout-lush ill be written file by buffering"; bout.close()s fout.closeDs System.out.printhn(’Suecessfully written in file.") } ‘Output : Successfully written in file. Contents of example.txt This ing will be written in file by buffering @.19 What is Character Streams ? State any two examples of each Character Stream classes for V/O in Java. ‘SPPU : May 17, May 1 Dec. 8, May 19, 7 Marks Ans. : Character Stream «© Ttis one of the important addition in java. It is made as counterpart of byte oriented stream. All the classes are made by comparing with byte oriented stream. Super class of character oriented stream are Reader and Writer ‘more like InputStream and OutputStream in byte stream, «© Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer. For input purpose Reader class is used whereas for outpuit or writi ig purpose Writer class is used. Character streams are added specifically to work with character data(character, character array, string). «The character stream classes differ from the byte streams classes in that they operate on buffered input and output and properly convert each character from the encoding scheme of the native operating system to the Unicode character set used by the Java platform. «© Onthe other hand, InputStream and OutputStream, and their subclasses operate on bytes and arrays of bytes. ‘The byte-oriented streams can read characters, but they only correctly handle 7-bit ASCII characters. * Character stream classes are added to replace byte stream classes. CharacterStream Reador Waiter Fig. 4.12 : CharacterStream Some important Character Stream classes. amon Scanned with CamScannerW Principles of Programming Languages (SPPU) _46 Table 45 Read Character Stream class BufferedReader BufleredWriter FileReader FileWriter InputStreamReader OutputStreamReader Description Handles buffered input stream. Handles buffered output stream. Input stream that reads from fi Output stream that writes to file. S Input stream that translate byte to character. Output stream that translate character to byte. PrimWriter Output Stream that contain print() and printInQ) method, Reader Abstract class that define character stream input, Writer Abstract class that define character stream output. Although byte stream classes offer us a lot of efficiency and flexibility when dealing with bytes and binaty data, they are not the best way to handle character input and output. Character streams operate directly on Unicode character internationalization character streams are. 8 and so for storing and retrieval of Unicode text for better alternative to byte streams. For this reason the character stream classes were introduced to the language in JDK 1.1 to offer a more efficient and easier way of dealing character-based 1/0. ButleroaWter Charkraytae Fiterviar Wier Outputsueamnter Lf Flowiter PipedWrter Pritt object SuteresReader — |{ Urenmbernonae ] CharArayReader Reader FitrReoder Perscteacer | meee HE eee] Pipedeader Scanned with CamScannerW Principles of Programming Languages (SPPU). AT Quick Read wpe Reader itis abstract class which defines character input stream. It handles UNICODE characters. It implements closeable ‘and Readable interfaces. All methods inthis class throws 10 Exception. Different Reader classes are Buffered Reader, ‘Char Array Reader, Filter Reader, Input Stream Reader, Piped Reader, String Reader, etc. Writer Ie is abstract class which defines character output stream. It implements Closeable, Flushable and Appendable interfaces. All methods throw 10 Exception. It contains different classes like Buffered Writer, Char Array Writer, Filter Writer, Output Stream Writer, Piped Writer, Print Writer, String Writer, etc. CharacterArrayReader(): «The Java ChardrrayReader class (Java.io.CharArrayReader) enables you to read the contents of char array as a character stream. © The Java CharArrayReader is handy when you have data in a char array, but need to pass that data to some component which can only read from a Reader. Example : harf) chars = "123" toCharArray(; CharArrayReadercharAreayReader = new CharArrayReader(chars); ind while(dat { sharArrayReader.read(); 1) {do something, with d data = charArrayReader.read(s } charArrayReader.close()s CharacterArrayWriterO : ‘The CharArrayWriter class can be used to write common data to multiple files. This class inherits Writer class. Its buffer automatically grows when data is writen in this stream. Calling the closeQ) method on this object has no effect. Example: CharArrayWrivercharArrayWriter = new CharArray Writer) chatArrayWriver write har{) charel = ehuarArrayWriteroCharArrays charArrayWeitersclose(): @ THEI Scanned with CamScannerPrineiples of Programming Languages (SPPU) Quick Read .20 What are predefined VO classes ? Ans, Predefined Streams + There are some predefined streams already available for out java programs. They are available through a class tem. System class is defined in java, lang which is implicitly imported all our java programs. calle ‘+ The System class contains three stream variables in, out, ert. * The three stream variables are declared with System class as public, static and final, So need to create object of System class to access these three. Name of System class is enough. © System.out refers to standard output stream, © System.In refers to standard input stream and © Systemerr refers to standard error stream. * Standard input stream is connected to Keyboard by default. Standard output stream and standard error stream is ‘connected to console by default. * System.in is an object of Input Stream class, Similarly System.out and System.err are both objects of PrintStream class. * These are byte streams, even though they are typically used to read and write characters from and to the console. As you will see, you can wrap these within character-based streams, if desired, 000 Scanned with CamScanner| a rencptesot Programming tangapes (S000) 49 Quick Re Ua | rece BET] @.1 Compare and contrast between thread based and process based multitasking. ans. : (4 Marks) ‘There are two distinct types of multitasking : Process based and thread-based. Sr.No Process-based multitasking ‘Thread-based multitasking _ 1. | A process is, in core, a program that is executing ‘Thus, process-based multitasking is the feature that allows your computer to run two or more programs ‘concurrently. ‘The thread is the smallest unit of code capable of, dispatch. A process is, at its core, a program that is being ‘implemented. Thus, the feature that enables your computer to run two or more progeams simultaneously is process-based multitasking. This implies that two or more tasks may be carried out concurrently by a single program. 3. | Process-based multitasking, for instance, allows you to run the Java compiler at the same time as Using a text editor, A text editor, for example, can format text at the same time as it is being printed, as long as two different threads perform these two acts. 4, | Multitasking based on processes deals with the "l picture", Multitasking based on thread manages the details, Multithreading enables you to write very powerful programs that allow : Full use of the CPU, since it is possible to reserve idle time to a minimum, This is especially important because idle time is shared in the collaborative, Java operates. 0.2 Explain in detail Java thread model Ans. : Java Thread Model Java uses threads to enable the complete setting to be asynchronous, This benefit red Preventing the waste of CPU cycles. networked environment in which (6 Marks) luces inefficiency by The value of a multithreaded environment is best understood in contrast to its counterpart. Single-threaded systems use a method called an event loop with polling, In this model, one thread of management runs in Associate inattention infinite loop, make a decision what to try and do next. Once this polling mechanism returns with, file scan (is prepared) to be read, then the event loop notices management to the suitable Until this event handler returns, nothing else wil happen within the system, This wastes mainframe can lead to one a part of a program dominating the system and preventing the other Processed, polling one event queue to say, a proof that a network eventhandler. e. It also events from being The advantage of Java's multithreading is thatthe most oop polling mechanism is removed, ‘Threads exist in several states. Aeasy-so oA Scanned with CamScannerQuick Read wes 9 pinto Prgeanming Langage SPPU) 5 New Leaving non-runnable state cal meaore p—! | [S06] promeroe TT tii ner Notification Fig. 5.1: Thread States ‘© Asshown in Fig 6.1, the method has many states, equally a thread exists in many states. A thread may be within the following states, © Athread may be running ‘© It may be able to run as presently as it gets CPU time. A running thread may be suspended, that quickly suspends its activity. © Adelayed thread will then be resumed, permitting it to choose up wherever it left off. ‘© Athread may be blocked once looking ahead toa resource. (© Atany time, thread may be terminated, that stops its execution instantly. * Once terminated, a thread can't be resumed. ‘Types of Java Thread Model Java thread model can be defined in the following three models: a) Thread Priorities b) Synchronization Messaging (@) Thread Priorities Each thread has its own priority in Java, Thread priority is an absolute integer value. Thread priority decides only when a thread switches from one running thread to next, called context switching, Priority does increase the running time of the thread or gives faster execution, (6) Synchronization * Java supports an asynchronous multithreading, any number of thread can run simultaneously without disturbing other to acess individual resources at diferent instant of time or shareable resources, * Butsome time it may be possible that shareable resources are used by at least two threads or more than two threads, onehas to write atthe same tne, or one has to write and other thread is inthe middle of reading it. For such type of situations and circumstances Java implements synchronization mode! called monitor, * Asa thread enter In monitor, all other threads have to walt until that thread exits from the monitor, * In such a way, a monitor protects the share: it being manipulated by other waiting le resources used by threads at the same instant of time synchronization, ee _ @s EERE Scanned with CamScannerPrinciples of Programming Languages (SPPU) 51 Quick Read (© Messaging ‘+ Aprogram isa collection of more than one thread. ‘+ Threads can communicate with each other. Java supports messaging between the threads with lost-cost. + Itprovides methods to all objects for inter-thread communication. + Asathread exits from synchronization state, it notifies all the waiting threads. @.3 Explain Main Thread in Java, (2 Marks) Ans. : The Main Thread Java offers worked in help for multithreaded programming, ‘A multi-strung program contains at least two sections that can run simultaneously. Each a piece of such a program is known as a thread and each thread characterizes a different way of execution. When a Java program fires up, one thread starts running right away. This is generally called the fundamental thread of our program, since the one is executed when our program starts, ‘A thread can be made by applying the Runnable interface and abrogating the runQ) technique. ‘The Main thread in Java is the one that starts executing when the program begins. All the youngster threads are produced from the Main thread. Likewise, it is the last thread to complete execution as different shut-down activities are performed by it. @.4 Write a simple main thread program. (4 Marks) Ans. public class Demo { public static void main(Thread args{)) { ‘Thread t = Thread.currentThread(); System.out.printin(’Main thread: "+ tsetName(‘eurrent"); System.out.printin(*Current thread: " + t); attempt { for (iti = Vsi<= 5514+) { stem. out prints ‘Thread steep( 10); ) , £4 (nteerupted Exception €) { Systemout,printhn(°Muin tra interrupted’) Main treat’) iH oasy-solutions Scanned with CamScanner& Principles of Programming Languages (SPPU) __52 Quick Read Output : Primary thread: Threadfmain,5 main) Current thread: Thread[eurrent,5, in] Leaving the Main thread JVM Thread : vm 1§ stan stat For each program ‘Othor Daemon Threads Main Thee mead (e9.Garoage collector) gat ant chia ‘chia Threasa, Tease staf Chile Thread Fig. 5.2: 1VM Thread + Asshown in Fig 5.2, fundamental VM thea is made consequently when g Ur Program is be not Roe should geta reference to it This should be Possible by calling the strategy currenreng eur: TO control it wt Thread class, This technique current Thre is available in restores a relerence tothe thread on wing Tae ach avaiable thread is Sand forall excess client called. The default need o reads need will be acquired from Parent to child, enemies 2.5 Write Program to create a Thread, Ans. : (4 Marks) Creating a Thread * As shown In Fig. 53, create a thread by staring up an object of type Th read. Java el which this can be refined : Pe Thread. Java characterizes two manners by © Youcan execute the Runnable interface. © You can broaden the Thread class, itself, Scanned with CamScannernape of Progamming Languages (SPU) _—_53 vik ond ‘+ The accompanying two segments take a gander at every strategy, thus. ‘The Thread class cute ma oe Sane Fig, 5.3: Create a Thread Executing Runnable ‘©The casual method to make a thread is to make a class that executes the Runnable interface. Runnable modified works a unit of executable code. You can build a thread on any article that actualizes Runnable. To ac Runnable, a class need just execute a solitary technique called run{ ), which is announced this way : public void run) Inside run}, you will characterize the code that comprises the new thread. Understand that run{ ) ean call different techniques, utilize different classes, and pronounce factors, much the same as the principle thread can. ‘The solitary contrast is that run) sets up the section point for another, simultaneous thread of execution inside your program. This thread will end when run{ ) returns. The subsequent method to make a thread is to make another class that expands Thread, and afterward to make an occasion of that class. The broadening class should supersede the run( ) strategy, which is the section point for the new thread, It should likewise call start( ) to start execution of the new thread, Here is the former program revised to expand Thread. Program to create a subsequent thread by expanding thread. MCrvate a subsequent thread by expanding Thsea class New Thread expands Threat { Nev ( Create anothe wad) seconel thread super("Demo Thread": ld threads" + this) System.out printh start()f/Start the thread {this isthe passage pont forthe subsequent thread publi void run) { attempt shri Scanned with CamScannerW Principles of Programming Languages (SPPU)__54 Quick Read i>; for(int { ‘System.out.prntIn(Child Thread: " + 1) i ‘Thread.sleep(500); } set (InterruptedException 0) : ‘ : : os System.out printn( ‘Child interupted ‘Systetn-out;println(*Exiting youngster thread." ? Eee > class Extend Thread { eee 2 ies bli state void main(Thread segs) {| i new NewThread(); ene attempt : 4 { E s caste for(int i = 53 i> 0;I-=),{ Z 5 : ‘System.oui-printin(’Main Thread: "+ 1); : 5 ‘Thread.sleep(1000); mi ue 3 Teabttae é ) ¥ s ae {get (InterruptedException e) { : ‘System.out.printIn("Main thread interrupted,");, ) System.out-printn(’Main thread exiting"); Youngster thread : read|Demo Thread Smain} Principle Thread: 5 Youngster Thread: 5 Youngster‘Thread: 4 Principle Thread: 4 Youngster Thread: 3 Youngster Thread: 2 Principle Theead: 3 Scanned with CamScanner‘W Principles of Programming Languages (SPPU) 55 Youngster Thread: 1 Leaving youngster thread. Principle Thread: 2 Principle Thread: 1 Principle thread leaving. Q.6 Write a program to create multiple threads. Ans. Creating Multiple Threads Quick Read (6 Marks) ‘So far, you have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. Program to create multiple threads. UECreste multiple threads class MyThread implements Runnable { String name; Thread MyThread (String thread) { ame = threadnames 1 = new Thread(this, name); System.out.prinln("New thread: " +05 tstarts } public void run { ty ( forfint i = 554 > 0: System.out.prntin(name + "=" +95 “Thread.sleep(1000); } } catch (InterruptedException ©) { System.outprintln(name + “Interrupte y @s GSE Scanned with CamScanner& Principles of Programming Languages (SPPU) 56 Systemout } Inframe + * exiting." clase MultThivad { public state void main Sting args{)) { new My Thread(’ Apple new MyThread\(Ball"); now NewThread( Cat"); iy q ‘Thread.sleep(10000); } catch (InterrupledExeeption ¢) t System.out.prinln(Main thread Interrupted’); Output: ‘The output from this program is shown here : ‘New thread: Thread[Apple,5,main] New thread: Thread Ball main} New thread: Thread[Cat5,main] Apple: 5 Ball: 5 Apples 4 Ball: Cats 4 Apples 3 Ga Read Scanned with CamScannerW Principles of Programming Languages (SPPU) 57 Quick Read Ball: 2 Apples 1 C Ball 1 Apple exiting: Ball exit Cat exiting. Main thread exit + This strategy is characterized by Thread and its overall structure is appeared here : o() «The isAlive( ) technique returns valid if the string whereupon it is called is as yet running. It returns false final boolean is Ali otherwise. While isAlive( ) is infrequently helpful, the technique that you will all the more generally use to trust that a string will complete is called join( ), appeared here: last void join( ) tosses InterruptedException This technique holds up until the string on which itis called ends. Its name comes from the idea of the calling string holding up until the predefined string goes along with it. Extra types ofjoin( ) permit you to determine a most extreme measure of time that you need to trust that the predetermined string will end. ¢ Heres an improved form ofthe previous model that utilizations join() to guarantee thatthe fundamental string is the last to stop. It additionally shows the isAlive() strategy. 03 = Oe Cryeasy-solutions, Scanned with CamScanneruick Read 58. les of Programming Lang ee co ah na (6 Marks) .1. What are the characteristic of functional programing ? Ans. Functional Programming - Characteristics ‘The most prominent characteristics of functional programming are as follows : ‘+ Functional programming languages are intended on the idea of mathematical functions expressions and recursion to achieve computation. Functional programming languages do not provision flow Controls like loop declarations and conditional declarations like IF Else and Switch Statements. They directly use the functions and functional calls. + Like OOP, functional programming languages provision general notions such as Abstraction, Encapsulation, Inheritance, and Polymorphism. that use provisional Feature of Functional Paradigm 1. Functional Programming is based on Lambda Calculus : + Lambda calculus is system created by Alonzo Church to contemplate calculations with capacities. ‘+ Itcan be called as the itlest programming language of the world, It gives the meaning of what is calculable. ‘+ Anything that can be registered by lambda math is process able. It is identical to Turing machine in its capacity to process. + Itgives a hypothetical system to portraying capacities and their assessment. + Itshapes the premise of practically all current utilitarian programming languages, 2. Pure functions : + These functions have two main properties. First they always produce the same output for same arguments Invespective of anything else. Secondly, they have no side-effects i. they do m variables or output something. © Later property is called immutability. The pure functions onl deterministic. * Programs done using functional programming are easy to debu; orhidden Input/Output. jodify any argument or global ly result is the value it returns. They are 'g because pure functions have no side effect + Pure function also make easier to writ parallel concurrent applications 3. Recursion: * There are no “for” or “while” loop in functional language. . 8. Iteration in through recursion Recursive factions repeatedly cll themselves, na ree eee is implemented until it reaches the base case, cursive function : Example of the iba) it(v<=1) return Vy else return fib(a = 1) + bln~ 2), te Scanned with CamScanner© principles of Programming Languages (SPPU) 59 Quick Read 7. Referential transparency = + Inuseful projects factors once characterized do not change their incentive all through the program. Functional programs don't have task statements. On the off chance that we need to supply some esteem, we characterize new factors all things being equal. «This disposes of any odds of results on the grounds that any factor can be supplanted with its genuine incentive anytime of execution. Condition of any factor is steady at any moment. Example: ¥2x41 > ULThis progressions the worth appointed tothe variable x. 1 So the expression isnt referentally straightforward 5. Functions are First-Class and can be Higher-Order © First-class functions are preserved as first-class variable. The first class variables can be passed to functions as limitation, can be returned from functions or stored in data structures. © Higher order functions are the functions that gross other functions as opinions and they can also return functions. Example : show_output(f) [function show_output is declared taking argument f which are avother function 105, if calling passed function printf 1/ declaring another funetion print(hello efi"): show_output(print_sfs) 1 passing function in another funetion 6. Vaiiables are Immutable +. ® thfunctional programming, we can not adjust a variable after it's been prepared. © We can create new variables - but we can't alter usual variables, and this actually benefits to preserve state throughout the runtime of a program. + once we generate a variable and set its value, we can have full sel-assurance meaningful that the values of that variable will not ever alteration 0.2 What are the advantages and disadvantages of functional programming ? (mana) Ans. ‘Advantages of Functional Programming 1. Pure functions are more obvious on the grounds that they do not change any states and rely just upon the information given to them. Whatever yield they produce isthe return esteem they give. Their eapacity signatu fives all the data about them for example their return type and their contentions. me The capacity of functional programming languages to regard capacities as qualities and pass # ies and pass them to capacities ‘as boundaries make the code more lucid and effectively reasonable. be "m to capacities ulterated capacities take 2. they don’t create any progressions don't take information or produce some concealed yield, at si Scanned with CamScannerwick Read 3 Principles of Programming Lany (serv) $$$ at rerated capacities don't 4. It is utilized to actualize simultancousness/parallelism on the grounds that unadulte change factors or some other information outside off. the worth is assessed Itembraces apathetic assessment which evades rehashed assessment on the grounds that ‘and put away just when it is required. Disadvantages of Functional Programming 1, Sometimes writing pure functions can decrease the comprehensibility of code. . 2. Writing programs in recursive style as opposed to utilizing circles can be bit scaring, 2 Wating pure functions are simple however consolidating them with rest of utilization and 1/0 activities is the troublesome assignment. Immutable qualities and recursion can prompt diminishing in execution, Programming Languages that support functional programming : Haskell JavaScript, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket. 2.3. Describe Lisp uses Prefix Notation Ans: (8 Marks) USP Uses Prefix Notation * You might have noted that LISP uses prefix notation, Inthe above program the + symbol works as the function ‘ame for the process of summation of the numbers 'm prefix notation, operators are written before their operands, For example, the expression, ar(bre)/d will be written as: UCatba)a) \4tustake another example, let us write code for converting Fahrenheit temp of 60° F to the centigrade scale ‘The mathematical expression for this conversion will be : (60"9/5) +32 Create a source code fle named mainlisp and type the followin (writels (+ (/ 9 5) 60) 32)) When you click the Execute button, 140 18 code in it Ortype Cul+E, LISP executes i Immediately and the result returned is Basic Building Blocks in LSP. LSP progran tade up of three basic buildin blocks ; oat ‘An atom is a number oF string of contiguous chatacters | eludes numbers Alistis a sequence of atoms and/or oth {ists enclosed in par and spe, theses, ial characters. @ommmmn5 Scanned with CamScannerwr inciples of Programming Languages (SPPU D 61 _Quick Read + Following are examples of some valid lists : (iamalist) (e(abo)defeh) (Gather arvind ( araddhana deshmukk)) {one two three four five six) 0 ¢ Astring isa group of characters enclosed in double quotation marks, © Following are examples of some valid strings : Lam a string” aha def #85681" ‘Adding Comments 5 ‘The semicolon symbol (: is used for indicating a comment line. For Example: (writesine "Araddhana”) ; : When you click the Execute button, or type Ctrl#£, LISP executes it immediately and the result returned is: ‘Avaddhana Following are some of the important points : ‘The basic numeric processes in LISP are ¢,,* and /. LISP signifies a function call f(x) as (Fx), for example cos(45) is written as cos 45. LISP terminologies are case-insensitive, cos 45 or COS 45 are same, LISP attempts to appraise all, including the arguments of function. Only three types of elements are constants and always return their own value. © Numbers © Thelettert, that stands for logical true. © The value nil, that stands for logical false, as well as an empty list, USP code takes the following steps : © ‘Thereader translates the strings of characters to LISP objects or s-expressions, ©The evaluator describes syntax of Lisp forms that are constructed from s-expressions. This second level of assessment describes a syntax that controls which s-expressions are LISP forms. Now, a LISP forms could be. 1. An Atom 2 Anempty or nom-list 3. Anylistthat has a symbol as its first element. +The evaluator everything asa function that takes a legal LISP form as an argument and returns a value, his g the mative why we put the LISP expression In parenthesis, because we are conveyance the ma +. expression/form tothe evaluator as arguments. Naming Conventions in LSP "Name or images can comprise of quite a few alphanumeric characte other than whites brackets, twofold and single statements, oblique punctuation line, comma, colon, Utilize these characters in a name, you need to utilize get away from character (\). pace, open and shutting semicolon and vertical bar. To EVeasy-solutions Scanned with CamScanner
You might also like
Java Unit-1
PDF
No ratings yet
Java Unit-1
62 pages
Core Java Notes
PDF
No ratings yet
Core Java Notes
136 pages
Java Unit-1 Chapter2
PDF
No ratings yet
Java Unit-1 Chapter2
51 pages
II B.SC IV SEM JAVA
PDF
No ratings yet
II B.SC IV SEM JAVA
135 pages
Unit 1
PDF
No ratings yet
Unit 1
160 pages
Ch1 JPR
PDF
No ratings yet
Ch1 JPR
93 pages
Java Unit 1
PDF
No ratings yet
Java Unit 1
159 pages
Java Tutorial: Prerequisites
PDF
No ratings yet
Java Tutorial: Prerequisites
176 pages
Java Imp 1st Unit
PDF
No ratings yet
Java Imp 1st Unit
20 pages
Core Java-2
PDF
No ratings yet
Core Java-2
216 pages
Java (Model 1)
PDF
No ratings yet
Java (Model 1)
33 pages
Java Prograaming (22412) - Notes (Unit-1)
PDF
No ratings yet
Java Prograaming (22412) - Notes (Unit-1)
16 pages
CJ Soln PDF
PDF
100% (1)
CJ Soln PDF
21 pages
UNIT-1 Java
PDF
No ratings yet
UNIT-1 Java
161 pages
BSC Final All Units Notes PDF
PDF
50% (4)
BSC Final All Units Notes PDF
74 pages
Introduction To Java Programming: Ashwinth.J Anna University Chennai
PDF
No ratings yet
Introduction To Java Programming: Ashwinth.J Anna University Chennai
79 pages
Java First Unit
PDF
No ratings yet
Java First Unit
42 pages
Java 1st Lesson Notes
PDF
No ratings yet
Java 1st Lesson Notes
25 pages
Core Java
PDF
No ratings yet
Core Java
176 pages
Core Java 061306
PDF
No ratings yet
Core Java 061306
8 pages
02-JAVA Programming Basic
PDF
No ratings yet
02-JAVA Programming Basic
23 pages
Unit 1-Java Final
PDF
No ratings yet
Unit 1-Java Final
100 pages
Hja1) Java
PDF
No ratings yet
Hja1) Java
68 pages
Chap 1
PDF
100% (1)
Chap 1
38 pages
Java
PDF
No ratings yet
Java
122 pages
Java Mid-1 Imp Queans
PDF
No ratings yet
Java Mid-1 Imp Queans
50 pages
Core Java
PDF
No ratings yet
Core Java
163 pages
Java 23
PDF
No ratings yet
Java 23
45 pages
Java Notes
PDF
No ratings yet
Java Notes
391 pages
UNIT 1.1 Java Fundamentals
PDF
No ratings yet
UNIT 1.1 Java Fundamentals
41 pages
Java Interview Questions Part - 1
PDF
No ratings yet
Java Interview Questions Part - 1
5 pages
Lab Mannual of SDTL
PDF
No ratings yet
Lab Mannual of SDTL
54 pages
Java
PDF
No ratings yet
Java
62 pages
JAVA Notes
PDF
No ratings yet
JAVA Notes
12 pages
Datatypes
PDF
No ratings yet
Datatypes
11 pages
Java Programming
PDF
No ratings yet
Java Programming
118 pages
Java Unit - I Notes
PDF
No ratings yet
Java Unit - I Notes
21 pages
6d9878f5-a386-4833-923e-66ee94691e6d
PDF
100% (1)
6d9878f5-a386-4833-923e-66ee94691e6d
167 pages
PPL June
PDF
No ratings yet
PPL June
26 pages
Java Is A Strongly Typed Language
PDF
No ratings yet
Java Is A Strongly Typed Language
19 pages
Java (AutoRecovered)
PDF
No ratings yet
Java (AutoRecovered)
33 pages
Java Tutorial
PDF
75% (4)
Java Tutorial
493 pages
Java Unit-1 Notes
PDF
No ratings yet
Java Unit-1 Notes
53 pages
L2 - Java Basics
PDF
No ratings yet
L2 - Java Basics
58 pages
Java Programming Full Notes
PDF
No ratings yet
Java Programming Full Notes
108 pages
All in One Java
PDF
No ratings yet
All in One Java
57 pages
Unit-1 in Simple Way
PDF
No ratings yet
Unit-1 in Simple Way
15 pages
Java Unit 1
PDF
No ratings yet
Java Unit 1
56 pages
Java Pyq
PDF
No ratings yet
Java Pyq
47 pages
Java Notes Introduction
PDF
No ratings yet
Java Notes Introduction
24 pages
Java Tutorial Part 1
PDF
No ratings yet
Java Tutorial Part 1
366 pages
Java Unit-1 Assignment Answers
PDF
No ratings yet
Java Unit-1 Assignment Answers
7 pages
The Genesis of Java / History of Java: Unit I - Introduction To Java
PDF
No ratings yet
The Genesis of Java / History of Java: Unit I - Introduction To Java
24 pages
Chapter 1.1 - 1.3 - 1.4 - 1.5
PDF
No ratings yet
Chapter 1.1 - 1.3 - 1.4 - 1.5
126 pages
Introduction
PDF
No ratings yet
Introduction
67 pages
Unit 1
PDF
No ratings yet
Unit 1
42 pages
OOP Java - Reference - Student
PDF
No ratings yet
OOP Java - Reference - Student
167 pages