0% found this document useful (0 votes)
29 views

Cs 5 Sem

Uploaded by

lavanyaa0322
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
29 views

Cs 5 Sem

Uploaded by

lavanyaa0322
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 40
; ‘3 Branching/Jump State For answer refer Unit-1, Page No. 20, Q.No. 22. ——Fotanswer refer Unit-1, Page No. 20, Q.No. 22, G20. Explain the Conditional Statements in Java with examples. Answer MayiJune-19, 24a) (MGU] Various types of conditional statements in java are as follows, 1. if Statement In Java, the if statement can be used in the following forms, (@) Simple if ©) ifelse (©) Nested if else (@) if-else-if ladder. ) Simple if ‘The “if statement (or simple ‘if’ statement) is used for decision making. It allows the computer to first valuate the condition and depending on its resultant value it transfers the control to the corresponding ‘Statement in the program. This statement performs an action if the condition is true, otherwise it skips that ‘action and executes the other statement, Figure: Flow-chart of Simple if Statement ifelse This statement is an extension of simple ‘ statement. Syntax if (condition) { statement-1; } else { statement-2; } statement-next; ) Inthe above syntax, statement-1 will be executed followed by statement-next when the condition is true Otherwise, statement-2 will be executed followed by statement-next, False True [Statement [Statement-> Statementnext }<—] Figure: Flowchart of if-else Statement Program import java.util Scanner; class EvenOrOdd { Public static void main(String args[]) { int x; Scanner sc = new Seanner{System in) IBUTORS PVT. Li ft output (0) Nested if else ‘A nested if'statement is an if statement which is defined inside another if statement. The nested if's are essential in programming since they yield a follow-up selection depending on the result of previous selection. Syntax ifleondition-1) { iffcondition-2) { statement-1; } else { statement-2; , J else { : statement-3;, +1{Sendition- i true, then condition-2is executed Statement-3 will be executed followed by Pt If condtion-2is evaluated to true then ps {xecuted or statement-2 is executed public class NestedExample . public static void main(String[ ] args) System out printin(“a is greater”); 3d else { System.out, In(“c is greater”); iff >) { System.out printin(“b is great ” else system.out.printin(“c is greater”); (@)— if-else-if Ladder The if-else-if ladder can be defined as a sequence of if-else statements, Syntax iffcondition-1) statement-1; else iffcondition-2) statement-2; else iffcondition-3) statement-3;, else if{condition-k) statement-k; else statement-k+1; statement-next; The conditions are evaluated sequentially (i.c., from top to bottom). If a particular condition is false then the next following conditions are evaluated. If a condition is satisfied, then its corresponding statement is executed. Figure: Flowchart of else-if Ladder Program import java.io, import java.uiil.*; lass LadderExample i t om zak ec void main(String } args) ‘System.out.printin(““The value of x is: else if(x==0) ‘System.out.printin(““The value of x is zero”); else if(x==1) System.out.printin("“The value of x is one”); else if(x==2) ‘System.out.printin(““The value of x is two”); else System.out.printin(“The value of x is greater than two"), 6 . Whe ) I 2. switch-case Statement “switch” statement can be called as multi_way branching statement, The statement provides multiple alternatives and the user can select the required option Syntax switch(expression) { case constant]: statement-1; break; case constant2: statement-2; break; case constantn: statement: break; default: default-statement; bres } statement next; Here, the expression is a valid expression aa! ‘constant is the result of the expression. When the co stant value is a character, it has to be enclosed with single quotes ‘The value of the expression is evaluated and! is compared with constant case values, When match? found, the conesponding: ‘statement block associated wi? the case is executed, Figure: Flowchart of switch Statement Program import java.io.*; import java.uti.*; class SwitchExample { public static void main(String{ ] args) { int x; for(x = 0; x <7; x++) switch(x) { case 0: System.out printin(“Sunday”); break; case 1: System.out printin(“Monday”); break; case 2: ‘System out printin(“Tuesda break; case 3: System out prntin(” Wednesday"), break; case 4; ‘System out printin(“Thursday”), Generally, the break statement is not mandatory. It terminates the switch block after execution of particular case. Thereby, it prevents the execution of, successive cases including default case. O21. Explai the Loops in Java with examples. Nov/Dec.-18, Q4fa) [MGU] OR executing action or series locks of code infinitely. It is Joop as soon as the required condition is used to control xecution of every block of tem.out.printin(“a is :"+a); /system.out printin(“y is greater than x"); tatype tatypes are also called as datatypes include classes terface Reference Declaratid ‘The syntax for declaratit of an interface reference is given as follows, Interface_identifierreferet 1.3 TPE castine Q18. Explain about the type casting and type conversion, Answer ‘Type Casting “Type casting’ is an explicit conversion ofa value ‘fone type into another type. And simply, the data type {is stated using parenthesis before the value, Type casting {in Java must follow the given rules, identifier data, ‘Type casting of floating point types into float types or integer type is possible, but loss of data, ‘Type casting of char type into integer types ig possible, But, ths also results in loss of data, since char holds 16-bits the casting of it into byte that results in loss of data or mixup characters, Syntax (target-type) expression; Here, target-type is the specification to convert the expression into required type. Example float a, b; int c = (int) (a + b); ‘The result of float type variables can be converted in to integer type explicitly. The parentheses for the expression a + b is necessary. Otherwise, the variable can be converted into int but not the result of a + b. The casting of double to int is necessary since, they are not ‘compatible. Furthermore, Java performs assignment of value of one type to a variable of another type without performing type casting. Here the conversion is performed automatically which is referred to as automatic type conversion. It can take place when destination type hold sufficient precedence to store source value. Example byte b=50; } valid statement int a=b; ‘The assignment of smaller datatype to larger data type is referred to as widening or promotion and the assignment larger type value to smaller is referred to as narrowing (it results in data loss). While performing the conversion between two incompatible type, the use of word cast is necessary. It isan explicit type conversion Syntax (target_type) value target type. Its a desired type to convert the given value ‘While casting the types, it is necessary to prevent the narrowing conversion which causes data lost. Ifthe ong value is converted to short then there may be @ chance to loss of data, Similarly, when a floating-point value 3.25 is casted to an int value, then the value will be converted to 3 and remaining data 0.25 will be lost. It is better to avoid narrowing conversions to prevent loss of data, int j-655 byte; double Ps char 4: short 6 floats; be (byte): system out print Byte of Integer" ++ * is” +b}, | float) ystem.outprintin (“Float of Integer” 4j+ * is” +3); | achat) j; ystemoutprintin("Char of Integer" “ is” +); ‘s=(float)12.889775; p-(double)s; ‘System out printin(“Double of Float” +s* “ is” +p); be(byte)s; ‘System out printin(‘Byte of Float” s+ is” +b); Frinds; System.out printin(“Int of Float” +s“ is” +); P-Gouble)q; System out printin(‘Double of Char"+q+* “ is” +P): bribyte)a; System out printin(“Byte of Char"+q* “is” +b); Rlint)g; System.out printin(“Int of Char"+q+ “is” +): ‘converting the data of one ty ‘ofthe major concept of Java. Proper ‘while type conversion is used by the they are likely to commit errors). When the data ‘are compatible, the type conversion is ‘automatically. This is called automatic type It can even occur when value of smaller data type is assigned to the bigger data type Byte —> shor, int -> long —> float -> double Rules for Type Conversion ‘There are certain basic rules that are to be followed while type conversion. 1. Unsigned char and unsigned short can be converted into unsigned integer. Character and short can be converted into integer. 2 3. Float can be converted into double. Example import java.io.*; class conversion { “public static void main(String argst J) { float sum,x; int k; fork =1; k <=5; k++) { x= I/(float)k; sum = sum +x; System outprintin( “Value of x.” +x), , System out printin(“sum:” + sum); Q12, Define java. Write about Java essentials and JVM. Answer: Java Java is an object-oriented and platform independent language. Its object model is simple and can be easily extended. It provides Java Development Kit (JDK) that contains tools for developing and executing Java programs. Itprovides a Java Virtual Machine (JVM) which is a Java interpreter that executes bytecode. Java has two types of ‘constants and eight types of basic data types. Java provides a feature called type casting that explicitly converts a value of one type into another type. It provides symbolic constants that may appear very frequently in a number of places within the same program. Java Essentials ‘The essentials of Java programming language are as follows, (High-level Language Java is known to be high-level language that supports unique features. It is quite similar to C and C++. (ii) Bytecode of Java ‘A bytecode is nothing but intermediate code that the compiler generates. This code is executed by JVM. i) Java Virtual Machine (JVM) ‘A bytecode consists of optimized set of instructions which are usually executed by Java runtime system on ‘a special machine called Java Virtual Machine. A JVM is a bytecode interpreter. It performs line by line execution of bytecode. Java has a neutral-architecture since it allows programs to run on different platforms. The java compiler ‘generates the bytecode that are neutral-architecture in order to achieve the capabilities of cross-architecture. These instructions can be interpreted easily on any platform translated into machine code. Java Runtime Environment ORE) contains JVM, class libraries and different supporting files. ‘There are many versions of JDK and differ in case of platforms like Windows and Linux. JVM belongs to IRE, that differs incase of OS and computer architecture. Java cannot be run if JVM is not available for the particular environment. [fava source code -—>[ Java byte code >{ vm Figure: Java Runtime Environment Java source code contains the simple code that is easy to develop and understand. The bytecode can be run on any platform, therefore, it is Write Once Run Anywhere (WORA). JVM allows to convert the bytecode into machine code. Java Development Kit (JDK) contains the tools like javac java etc. They are of various versions used on different platforms. Java Virtual Machine (JVM) is a Java interpreter that executes bytecode. The interpreter reads and translates: the entire code into machine code. This translated code is then executed by the machine. This machine perform ail the functions of a computer. The type of Java interpreter to be ported on the machine must be compatible with the machine and its operating system. The virtual machine code is different for different computers and acts as an intermediate between the virtual machine and the actual machine SUN provides virtual machine implementations for Microsoft Windows 95, 98, NT or Solaris operating system. ‘The process of translation of a Java program into bytecode simplifies the execution of program in various platforms, Due to this, Java is said to be platform ‘independent. Execution of a Java JVM . os program by JVM makes the program more secure and portable. JVM also solves of inheritar Write types of In} noe a program to demonstrate multiple inheritance in java. | } ‘answer: June/July-19, @9(b) (OU) Inheritance ( Inheritance can be defined as al ism in which one class inherits { the features of another class. The class sehich aoquires the features is called the Jpild class or derived class and the class ‘whose features are acquired is called parent class or base ‘The parent class contains only its own features, | } ‘where as the child class contains the features of both and child classes. Moreover, an object created for parent class can access only parent class members i! However, child class object can access members of both sfild class and as well as parent class. The child class can { acquire the properties of parent class using the keyword ‘Types of Inheritance ) “There are five types of inheritance in Java, They ae, 1. Single level inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance, 1. Single Level Inheritance _ The process of deriving a class from 8 single base class js called single inheritance. It has only one base ‘ass and one derived class. a 3. Multiple inheritance 4 s. a for some public int side = 10; class Square extends Shape j ‘The process derived class is called: of inheritance, “other derived class. void areat ) int area = side* side; ‘System.out printin(“Area of square 2” +area); class InheritanceDemo public static void main(String{] args) ‘Square s=new Square( ); saarea()s ‘Multilevel Inheritance of deriving a class from another ‘multilevel inheritance. In this tyPe derived class can act as the base class Q23. What is a class? How it is defined? How are the member variables of a class declared? Answer: Class A class can be defined as a template that groups data and its associated functions. A class contains the instances such as variables and methods. It is responsible for describing the behavior and data of these associated instances. An object will be created when the class is instantiated. The behavior of the objects or class will be implemented using the methods. And, the data of them will be stored in the variables. Class Declaration The class contains two parts namely, (a) Declaration of data variables (b) Declaration of member functions. is LIABLE to face LEGAL Proceedings. itself. Program Instance Variables Instance variables are the variables that are declared inside the class but outside of the methods. (ii) Class Varial Class variables are the variables that are declared the class with static modifier and they reside outside of the method. General Form of a Class A class is declared using ‘class’ keyword followed by the name of the class. The syntax of a class } is as follows, | Syntax class Sum ‘ public static void main(String args{}) { int x=5, y= int res=x+y; System. out printIn(res); } class name_of the class eee { (declaration of Instance variables type data_variablel; type data_variable2; /declaration of functions type function_namel (arg_list) { Also) body of function } ! type function_name2(arg_list) { body of functic ; ty of function which is used 4 ) Declaration Itis better to maintain information of one logical anobiect inal entity in a class Syntax Example name_of the clas’ ject ume Consider the below code that defines a class, | eke apes | Example { int stdid; jet nadine; ‘objStudent is the re! represen! ae a the object. A refer loko si; the object. pl alll ate Program import java.io.*; class CmdLineArgs { public static void main(String args[ ]) { System.out.printIn(“The command ine arguments are:”); for(int c = 0; c each of which inherits the interface from the ys ‘class in a unique way. 4, An inner elass is an independent entity with, maintaining any “is a” relationship. Program import java.io.*; class Outer { int n; private class Inner { public void print( ) System. out printin(“This is an inner class" void display() { Inner i = new Inner( ); print; } public class My_class { public static void main(String args{ }) " Outer o = new Outer(); o.display( ); Output rel ith the outer class object. Geen sd PUBLISHERS AND DISTRIBUTORS PVT. LTD. PROGRAMMING IN Jay, Q41. Write about abstract class. Answer: Abstract Class Java defines abstract classes and methods using the keyword “abst is called abstract class, Whereas the method that does not have body is called can contain subclasses in addition to abstract methods, Ifthe method containing the methods of the baseclass then they will be considered as abstract classes. So, implementation forall the base class's abstract methods. Abstract classes cannot be instantis ‘A method is declared abstract when it has to be overridden in its subclasses. For example, an abstract meth Phone(" can be defined in “Network” class as there can be various phones with various networks. Hence eg subclass of Network class can overridden and implement the The elas that does not have by abstract method. An abstract cy the subclasses does not oven I the subelass must provide ed 4 abstract method phone ). Syntax for Abstract Class abstract class classname{ } intax for Abstract Method abstract type methodname( Program import java.io." import java.util"; abstract class Baseclass2 abstract void display(): ) class Derivedclass extends Baseclass ( void display( ) System,out.printin(“Derivedelass”); } class Baseclass publie static void main(String args{ }) Derivedelass de = new Derivedelass(); de. display( ); ) STRIBUTORS PVT. LTD. . [Abstract class can contain all concrete methods ‘or abstract methods or a mixture, The methods can have any access specifier except ‘private’. The variables can have any access specifier except i. | Multiple inheritance is impossible. §. | Inheritance goes with ‘extends’ keyword. ‘abstract’ keyword should be included in method ‘declaration. ). {It contains constructors. 8. |Ithas a main( ) method. . | Example For answer refer Unit-II, Page No. 62, Qo. 41, Interface must contain only abstract methods. It should have only ‘public’ access specifier. Variables should be ‘public’, ‘static’ and ‘final’, Multiple inheritance is possible. Inheritance goes with ‘implements’ keyword. It does not contain constructors. It does not have main( ) method. Example For answer refer Unit-II, Page No. 63, Q.No. 42, Topic: Program. __ Package is a mechanism that organizes classes and interfaces. It groups them based on their Hey! fastionaity. I ats as a container for the classes, Packages are of two types namely Java API escape PaABE and user-defined packages, Java API consists of various packages which contain classes. “from Pisees involves access control mechanism of lava, A class which is define ina package will be me ee package only. it cannot be accessed by a code which is beyond the package, Creating a Package enor kage is created or defined using ‘package’ keyword. The name of the package should be preceded with Syntax Package’ in its declaration, These packages are called user-defined packages. Package pack]; In the above example, ‘Ex’ is the class name added to an existing package ‘pack1’. Program Package mypack1; import java.io.*; public class Student { Public static void main(String args[ ]) { System.out.printIn(“Welcome to package program”); Uses of Package The various uses of package are as follows, 1 It is used for the classification of classes and in- terfaces in order to have easy maintenance. 2 It offers access protection. 3. It eliminates naming collision. 4 It can easily allow the programs to use common classfiles. s Mt can be compiled independently and imported into the desired program. the multithreading in java, can be defined as a set of executable instructi : ions executed independently. {nto multiple subprograms and each subprogram is eiet steal Piety indi thereby decreasing the execution time of a program. ade 4 ding in Java 5 ‘The Java run-time system and its class libraries are designed in such a it i s way that it depends on multi-threading Java offers asynchronous thread environment which helps in efficient utilization of CPU cycles. In Java, multithreading is preferred more than the single threaded system. Single threaded system make use afamethod named event loop along with polling. According to this method, a single thread present in the system ite number of times (i.e, infinite loop), The polling mechanism is responsible for selecting an fret fom the queue which decides the next action to be performed while the selection of this event, the event loop syesthe control to the required event handler. The CPU will be idle until the event handler returns the response due ‘psbich the CPU time is wasted. So, a single event dominates the other events and restricts them to be processed. Ina single-threaded model, a single thread is responsible for blocking the execution of other threads unless ‘acomplete its execution. Hence, the resources are wasted. Incontrast to single-threaded model, multithreading in Java offers the following benefits. @ _Itremoves the loop and polling mechanism. @ _Asingle thread can be stopped without affecting the execution of other parts of the program. Java thread model can be defined into the following three parts. |. Thread priorities 2. Synchronization Se Messing. 1 Thread Priorities For answer refer Unit-III, Page No. 104, Q.No. 27. 2 Synchronization For answer refer Unit-III, Page No. 106, Q.No. 28. Messaging ta, co be divided into a number of threads where Supports this messaging service with low-cost for oe inter-thread communication. Jin every individual thread can communicate with the threads to communicate. It provides a set of i exception be handled in Java, ‘What is and error? Explain how an exception can 18 Tet the benef of exception handling. OR Explain how Exception can be handled In Java with an example program, Dee-18, apy OR Define Exception. Explain the Handling of Exceptions in Java. Answer : (ayidune-19, 82) (MUI | Nov,/Dec.-18, (0) MAU) Error Itis a known fact that human beings are prone to errors. Obviously, users (the Java professionals) are not ay exception to this. Errors occur due to mistakes in the design and coding of an application. Errors result due to ag ‘coding these are nothing but syntax errors. Exception ‘An exception can be defined as an error that can be occurred at run-time or at execution time. Exception Handling Exception handling can be defined as a mechanism of handling exceptions that can be occurred at run-time This mechanism is commonly used to prevent the malfunctions such as computer deadlock or computer hanging Some examples of run-time exception are divide by zero, array out of bounds exceptions. The run-time exception can be handled by using five keywords namely try, caich, throw, throws and finaly. ‘The code that can generate exception is usually placed in try block. If an exception is occurred, execution flow finds the similar catch block and leaves the try block. The catch block handles the exception and generates a message specifying the type of exception. Some of these exception types are as follows, () ArithmeticException (ii) ArrayIndexOutOfBoundsException. However, there is no rule that the try block must contain corresponding catch block. Each try block may contain zero or multiple catch blocks. When an exception is thrown and if it is matched with any of the catch block, then the corresponding catch block can be executed. Otherwise, the catch block can be skipped and the next to the catch block will be executed. The finally block is declared after all the catch blocks executed inrespective to the occurrence of exception, Note that, the finally block is optional statements of statements present whose code canbe Ifa method throw an exception, then it can be handled by catch block. This ool y exception can be thrown using throws’ clause. ee a leaves the throws block, then it cannot return back to the ‘throws’ clause. If the throw ‘exception cannot be handled by any catch block, then it can be handled by default handler o. “Termination pa pateth led by default handler called as *Terminati ‘Syntax for Exception Handling try if MBlock of code to check exception , has a lifecycle, which consists of fol (©) Dead state. ‘Athread can be present in any one of these states at an instance. It can switch from one state to another state rious methods. The following figure depicts the life cycle of thread, Killed Thread [ P sing Active Thread “Cedaee) yield() Figure: Life Cycle of a Thread {) Born State Tn this state, anew thread can be bor by creating a thread object. This new thread can be used to perform following task, the ( ttcan be scheduled to running state using start( ) method, thereby changing its state from born to tunnable. hei Gi) ttcan be killed by using stop( ) method, thereby changing its state from born to dead. ‘Tfmultiple threads in the queue have equal priority, then ‘the threads can be scheduled (allocating time stots) using round-robin algorithm (first-come, first-serve manner), ‘However in runnable state, there is a facility ‘of executing, 4 thread before its tum using yield ) method, a Running thread | | yield) aa Ruma Figure: Block Diagram of Rolinquish Control Using Method (©) Running State In this state, the execution ofa thread starts. The executing thread can leave the control by its own or by Preempting with the thread that have highest priority. ‘The running thread can leave (relinquish) the control in following situations. Casel: If running thread is suspended by using suspend ) method, A thread can be suspended whenever there is a requirement to keep the thread idle for sometime due to which the running thread moves to block state. This suspended thread can be resumed to its execution using resume( ) method. state Figure: Block Dispram of Relinquish Control Using resume) Method ‘Case 2: If running thread is made to sleep for specified time using sleep (time) method then the thread will into the state, IC resides out of the queue is completed. After the mn Case 3: 1f running is made to wait thread using yay method then the thread must wait until an eyey occurred, The waiting thread ean be resumed iy, execution using notify( ) method. wait() runnable} im of Relinquish Control Using wait!) Method @) Blocked State Inthis state, the thread can be blocked until itgets testumed. A thread which is suspended can be prevented from runnable state and running state. Any thread canbe spend( ), sleep() and wait( ) methods Various needs. ‘The blocked thr non-runnable mode (ice. in idle mode) in suspended thread can be resumed to execution using resume( ) and notify() methods (©) Dead State In this state, the thread can be killed. After the successful completion of execution, thread will undergo natural death. However ifa thread i killed in bom sta Tunable state, running state and suspended state using stop( ) method then this sort of death is be called & remature death, Explain thread priority with sultabl examples, Ksigned a priority value. This: is responsi thread should switch to process of switching th ‘another thread is cal 0 The two: decision of cony 8 thread is to create a class which edie p inrespective of object which i implements the ‘Runnable’ ‘ito Pecutable code. The implementavon of cg tect which implements ‘Runnable’. This interface et an) which contains the creation code similar fo mais eed Thee ere neta classes and also to declare variables. |. The run( ) method can be used pe voi un) rating a class which implements ‘Runnable’, an object of type ‘Thread! is instantiated from withi iso the important constructors defined by ‘Threads, Oe ee ‘Thread(Runnable thObj, String tName) Here, thObj — Instance ofa class which implements the runnable interface. {Name —Name of the new thread. ‘Once the new thread is created, execution of it can be initiated using its start( ) method. ‘sample impor java. class TreadDemo implements Runnable t public void run( ) { System.out.printin(“The thread is created using runnable interface”); } public static void main(String args{ ]) { ‘ThreadDemo di=new ThreadDemot ); Thread thi =new Thread(d1); thi start();, 1 Thread Class another way for creating a thread. Here a new class which extends “Thread! is created. Later on an class is created. The class which is derived should override the run( ) method to switch the thread. isan entry point for a new thread). In order to start execution, it should invoke start( ) | When a method is declared as synchronized then the provides ito the threads object created forthe thread class. A mo i ‘mutual exclusive lock. The thread which enters the ‘other thread to access the method. Once, the execution of initial thread is, {han tne next waiting thread can ener into the monitor. While the execution of thread is under proces an Shuther tread attempts to enter the monitor then it can be suspended until the exceution ofthe thread in mogse } ‘gets completed synchronization can be achieved in two ways, @ Synchronized Method ‘The synchronized keyword is used for declaring/defining the method called synchronized method. (ii) Synchronized Statement ‘The synchronized keyword is used for synchronizing the block of statements called synchronieg statements. | import java.util.*; class First ( synchronized void call(String str) r ‘System.out.printin(“[” +str); ty | r Thread sleep(1000); } ) catch(InterruptedException ie) ( ‘System.out.printin(“Interrupted’ ) System.out printin(“J"); : id . public void run( ) : { fcall(str);, } ) class SynchDemo { public static void main(String args{ ]) { First f= new First( ); Second s1= new Second(f, “SIA"); Second s2= new Second(f, “GROUP”); Second s3= new Second(f, “COMPANY”); ty { s1.tjoin(); s2.,join( ); s3.t,join(); catch(InterruptedException ie) { System. out printin(“Interrupted”);

You might also like