0% found this document useful (0 votes)
51 views79 pages

Java

Java Programming

Uploaded by

Shubham Aher
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
0% found this document useful (0 votes)
51 views79 pages

Java

Java Programming

Uploaded by

Shubham Aher
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
You are on page 1/ 79
Practical Number: 1 & 2 Set up a Java Programming development environment and test using small program Exercis L.Write the options provided by the following JDK tools along with their use Ljava 2Javae 3.javadoe Ans: 1. Java: The loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader. 2.javac It specifies the Java compiler, which converts source code into Java bytecode. 3.javadoc The documentation generator, which automatically generates documentation from source code comments 2. List different versions of jdk JDK 1.0, JDK 1.1 J2SE 1.2. RSE 13, PSE 14, J2SE 5.0, Java SE 6 Java SE 8 3.Test the setup using similar program. class HelloWorld { public static void main(string[] args) { System.out.printIn("Hello, World!"); } Practical Related Questions: 1. Write installation directory path of your directory ‘Ans: C:\Program filesUavadk 1.8.0\bin 2.Write value path environment variables ‘Ans: C:\Program files\Java\Jak 1.8.0\bin 3.List folders created after installation Ans: C:\Program files\ava\Jdk 1.8.0\bin 4.Main method is declared as static Justify Ans: Java main() method is always static, so that compiler can call it without the creation ofan object ‘or before the creation of an object of the class. In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method 5.Program is named with class containing main method Justify ‘Ans: All Java programs must have an entry point, which is always the main() method. Whenever the program is called, it automatically executes the main() method first... The main class ean have ‘any name, although typically it will just be called "Main" Conclusion: ‘We have set up a Java Programming development environment and tested a small program Practical Number: 3 different Develop programs to demonstrate use of if statements and it forms Exerci L.Write a program to use simple if statement to check condition Ans: class [fDemo { public static void main(String args|]) { im i=10, if(i< 15) System.out.printin("10 is less than 15"); / This statement will be executed //as if considers one statement by default System.out printin("Outside if-block"); 2. Write a program to use different forms of if statement to cheek multiple con: import java.util. Scanner; public class EvenOdd { public static void main(String[} args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a number: int num = reader.nextIn(); iffnum % 2 == 0) System.out printIn(num +" is even"): else System_out printin(num +" is odd"); 3. Write a program to check multiple conditions using if statement import java.util Scanner; public class Biggest_Number { public static void main(String{| args) ( int x,y. 2: Scanner new Scanner(System in System.out print("Enter the first number:"); s.nextint); System.out print("Enter the second number:"); snextInt(); System.out print("Enter the third number: z= smnextint(): iftx>y && x>7) t System out printin( "Largest number is:"*+x): else ifly > 2) System.out printIn("Largest number is:"+y); else System.out printhn("Largest number is:"*z), Practical Related Questions: 1. List operators used in if conditional statement Ans: Arithmetic operators Logical operators, relational operators 2. Inf else construct which part will be executed if condition is true. Ans: if block will be executed if condition is rue 3. State the condi n when the else part will be executed with example, Ans: When the if condition false then else part will be executed public class example { public static void main(String|| args) { int 0: 1 specified condition inside if statement iftasesyt ‘System out printin( "a is less than $") else System.out printin('a is greater than 5"); Conelusion: ‘We have developed programs to demonstrate use of if statements and its different forms Practical No. 4: Develop programs to demonstrate use of switeh statement and conditional if ( Exercis L.Write a program using switch case statement Ans: import java.util. Scanner; public class Arithmetic_Operators t public static void main(String args(]) t Scanner § = new Scanner(System.in); while(true) 4 System.out.printin("™); ‘System.out.printin(Enter the two numbers to perform operations " System.out.print("Enter the first number : "); int x = s.nextInt(); System.out.print("Enter the second number : "); int y = s.nextInt(); ‘System.out.printin("Choose the operation you want to perform "); System.out.printin("Choose 1 for ADDITION"); System.out.printin("Choose 2 for SUBTRACTION"); System.out.printin("Choose 3 for MULTIPLICATION"); System.out.printin("Choose 4 for DIVISION"); System.out.printin("Choose 5 for MODULUS"); System.out.printin("Choose 6 for EXIT"); int n = s.nextint(); switch(n) case 1: int add; add = x+y; System.out.printin("Result : "+add); break; case 2: int sub; sub =x-y; System.out. printin(*Resul break; case 3: int mul; mul = x* y; System.out.printin("Result : +mul); break; case 4: float div; div = (float) x / yj System.out.print("Result : "+div); break; case 5: int mod; mod = x % y; System.out.printin("Result : "+mod); break; case 6: ‘System.exit(0); 2.Write a program to check switch case statement using character datatype public class SwitchCaseExample2 { public static void main(String args| ){ char chr switeh(ch) case System. out println(”Case break; case" System. out println("Case2 "), break; case's System. out println("Case3 "), break; case 'y: System out printin("Case$ "); break; default: System. out printin("Default ") 3..Write a program to check the given number using ternary operator class TernaryOp { public static void main(String[] args) { int number = 24; String result = (number > 0) ? "Positive Number" : "Negative Number"; ‘System.out printin(result); } Practical Related Questions: 1. what will happen if break is not written for a case in switch case? ‘Ans: we don’t have break statement after the case that caused the flow to pass to the subsequent cases till the end, The solution to this problem is break statement, Break statements are used when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the execution, flow would directly come out of the switch, ignoring rest of the cases. 2., When default case is executed? Ans: Itis executed when the expression doesn't match any of the cases. The default case can be used for performing a task when none of the cases is true, No break is needed in the default case. 3. List datatypes allowed in switch expression, Ans: byte, short, char, int- primitive data type, enumerated types(Enums in java), the String class and ‘Wrapper classes Conclusion: ‘We have studied the use of switeh case and ternary operator. Practical Number — 5 Develop programs to demonstrate use of looping statement ‘ for” Exercise: L.Write a program to print command line arguments using for loop Ans; class A public static void main(String args[]){ for(int i=0;i= 0) { // add only positive numbers sum += number, System.out printin("Enter a number"); ‘number = inputnextInt(; } ‘System. out.printin("Sum =" + sum); input.close(); 3 Practical Related Questions: 1. Write difference between while and do while loop Ans while do-while Condition is checked first then statement(s) is Statement(s) is executed atleast once, thereafter executed, condition is checked, I might occur statement(s) is executed zero times, If condition is false. At least once the statement(s) is executed. No semicolon at the end of while. ‘Semicolon at the end of while while(condition) while(condition); It'there is a single statement, brackets are not required, Brackets are always required Variable in condition is initialized before the variable may be initialized before or execution of loop. within the loop. while loop is entry controlled loop. do-while loop is exit controlled loop. 2. How many times do while loop will be execute if condition is false? Ans: do-while loop is executed at least once because condition is checked afier loop body. Conelusion: We have studied the use of while and do while loop. Practical Number: 09 Develop programs for implementation of explicit type conversion in java Exercise: 1.Develope a program to show the use of explicit type casting Ans: public class NarrowingTypeCastingExample ‘ public static void main(String args{]) double d = 166.66; //converting double data type into long data type ong I= (long); //onverting long data type into int data type int i= Cint)l, System.out printin("Before conversion: "+d); /ifcactional part lost System out printin("A fter conversion into long type: "+1): “ifractional part lost System.out printIn("A fter conversion into int type: "+i); 3 2. Write a program for implementation of explicit type conversion. Ans public cass Main { public static void main(String] args) { double myDouble = 9.78 int mylnt = (int) myDouble: // Manual casting: double to int System.out println(myDouble);_ // Outputs 9.78 System.outprintin(mylnt); —(/ Outputs 9 } Practical Related Questions: 1, What is casting? Ans: ‘Type casting is a method or process that converts a data type into another data type in both ways ‘manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. 2. What is the difference between implicit and explicit type casting? Ans: Widening Type Conversion(implicit) can happen if both types are compatible and the target type is larger than source type. Widening Casting takes place when two types are compatible and the target type is larger than the source type.. ‘When we are assigning larger type to a smaller type, then we nced to explicitly typecast it, 3. What is narrowing? Ans Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error. Conetusion: Hence we have studied the implementation of explicit type conversion. Practical Number: 10 Develop programs for implementation of constructor and multiple constructor Exercise: L.Develope a program to show the use of parameterized constructor. Ans class Student{ String names reating a parameterized constructor Student(nt string n)| ) ‘method to display the values void display( {System out.printinGid+" "+name)s) public static void main(String args{I){ fereating objects and passing values Student sl = new Student(25,"Ankita") Student s2 = new Studemt(2 ikita ‘calling method to display the values of object st.displ S2.isplay()s 2. Write a program for implementation of single constructor in Java. class Main { private String name: ¥ constructor Maing { System.out prin ‘Constructor Called”) ‘name = "Tava Prosraminy public static void main(String} ares) { 1 constructor is invoked while ing an object of the Main class Main obj ~ new Main(); System. out printin("This is" + obj name); 3.. Write a program for implementation of multiple constructor in Java. ‘Ans: class Main { String language; ! constructor with no parameter Main() { this.language = "Java", } constructor ith a single parameter Main(String language) { this. language = language; } public void getName() { System.out.printin("Programming Langauage: " + this.language); 4 public static void main(String[] args) { //call constructor with no parameter Main obj! = new Main(); //call constructor with a single parameter Main obj2 = new Main("Python"); obj getName(); obj2.getName(); u Practical Related Questions: 1. Does Constructor return a value? Ans: No, constructor does not return any value. ‘© While declaring a constructor you will not have anything like return type. ‘+ Ingeneral, Constructor is implicitly called at the time of instantiation + And it is not a method, its sole purpose is to initialize the instance variables 2.Specify the situation when default constructor is provided by the system Ans:If you don’t implement any constructor in your class, the Java compiler inserts deftult constructor into your code on your behalf. You will not see the default constructor in your source code(the ,java file) as it is inserted during compilation and present in the bytecode(.class file). 3.Specify the situation when default constructor is explicitly define in. the class Ifconstructors are explicitly defined for a class, but they are all non-default, the compiler will not implicitly define a default constructor, leading to a situation where the class does not have a default constructor. Conclu We studied the implementation single Constructor and multiple constructor. Practical Number: 13 Develop programs for implementation of Arrays in Java Exercise: 1 Develope a program to perform various operation using array. Ans: class Main [ public static void main(String] args) { 5, 22,9, 8, 12} int{] numbers = (2, -9, 0,5, 12, int sum=0; Double average; / access all elements using for each Loop / add each element in sum for(int number: numbers) { sum + number; 1 got the total number of elements in arayLength = numbers length; calculate the average 1" convert the average from int to double average = ((double)sum / (double)arrayLength) System. out printin("Sum =" + sum). System. out printin( "Average = "+ average); 2. Write a program for implementation of multidimention array clays Testarray public static void main(String arastD /ideclaring and initializing 2D amay int a] 1,2,3},42.4,5},44,5}} ‘printing 2D array for(int iH0i<3i+4)4 fin HOSE System. out print(arti]}+" )s ) System out printing), } n Practical Related Questions: 1, What is the use of new operator in defining an array? Ans: When we create a object of a classtype the new operator allocates the memory at the run time, The new operator creates the array on the heap and returns the reference to the newly created array object which is then assigned to arrayName. 2. In 2D array which dimension is optional at the declaration of array? Ans: Second dimension in array is optional in Java. You can create a two dimensional array without specifying both dimension e.g. int{4][] is valid array declaration, 3. Isit possible to change size of array once allocated? Ans: If'you create an array by initializing its values directly, the size will be the number of elements in it, Thus the size of the array is determined at the time of its ereation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated Conclusion: Hence we studies the implementation of arrays and types of arrays in java, Practical Number: 14 Develop a programs for implementation of Vectors in Java Exercise: L.Develope a program to perform various operat n on vector using different method Ans: import java.io.*; import java.util; class VectorExample { public static void main(String| J args) J/ Size of the W Nector // Declaring the Vector with ‘Vinitial size n Vector v = new Vector(n); 1! Appending new elements at /the end of the vector for (int i= 1; i=; i++) vadd(i); / Printing elements System.out printin(v); Remove element at index 3 v.remove(3); / Displaying the vector after deletion ‘System.outprintIn(v); 1/ Printing elements one by one for (int 1= 0; 1 v2 = new Vector(); v2.add(1); y2.add(2); y2.add(3); System out printin("Vector v2 is" + v2); Practical Related Questions: |. Difference between array and vector. Ans ArrayList Vector 1) ArrayList is not synchronized. Vector is synchronized, 2) ArrayList increments 50% of current Vector increments 100% means doubles the array size array size if the number of elements if the total number of elements exceeds than its capacity. exceeds from its capacity 3) ArrayList is not a legacy class. It is Vector is a legaey class. introduced in JDK 1.2. 4) ArrayList is fast because itis non- Vector is slow because itis synchronized, ie. ina synchronized, multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object 5) ArrayList uses the Iterator interface A Vector can use the Iterator interface or Enumeration interface to traverse the elements. to traverse the elements, 2.State the difference between size() and capacity() method of vector class. Ans: The size of a vector represents the number of components in the vector. The capacity of a vector represents the maximum number of elements the vector can hol. 3. State the difference between addElement() and insertElement() method of veetor class Ans: ‘The add() methods inserts an element at a given position of the vector. - The addElement () method adds an object at the end of the vector and increases the size of the vector by one. Conclusion: We studied the implementation of vector and various method in vector class. Practical Number: 15 Develop a programs for implementation of Wrapper class to convert primitive into object Exercise: L.Develope a program to create object of primitive data types and use them Ans: class ConstructorsDemo { public static void mai ‘String|] args) Byte b = new Byte((byte) 5); // LINE A Byte b_str = new Byte("S" + 1); System out printin('Value of b : "+ b+" Value of b str" + b_str); Short s = new Short((short) 10); // LINE B Short 5_str = new Shori("10" + 2); Systemout.printin("Value ofs :"+s+" Value of b_str "+s. str); Integer i= new Integer(15); // LINE C Integer i_str = new Integer("15" + 3) System.out.printin("Value of i:"+ i+" Value of b_str" + i str); Long |= new Long(20); // LINE D Long |_str = new Long("20" +4): ‘System.out.printin("Value of i:"+ 1+" Value of b_str" + | str); 2. Develop a programs for implementation of Wrapper class to convert primitive into object Ans: class Main { public static void main(String[] args) { int var double var2 = 5.65; boolean var3 = true: /iconverts into wrapper objects Integer objl = Integer.valueORvarl); Double obj2 = Double.valueOfvar2) Boolean obj3 = Boolean. valueOf(var3); (/ checks if obj are objects of (/ corresponding wrapper class iflobjl instanceof Integer) { System.out.printin("An object of Integer is created."); iflobj2 instanceof Double) { System.out.printin("An object of Double is created.” } iffobj3 instanceof Boolean) { System.outprintin(""An object of Boolean is created"); Practical Related Questions: 1. Write a different ways to create object of any prirmitive data type Ans: can be created by- 1. Using new keyword. 2. Using Class.forName() method 3. Using clone method. 4, Using ConstructoObjects r.forName() method 5. Using Deserialization 2.Write methods of number class to convert object of primitive data type. Ans: + xxxValue() - Converts an Integer object into its corresponding primitive data types. xxx represent primitive data types. + parselnt() - Converts String into the primitive data type. 3. Write a program fo convert string value into integer wrapper class object Ans: class Wrap { public static void main(String argsf]) t String s="20"; Integer i=Integer.parseInt(s); _/Converting String into Integer System.out printin("String Value : "+s ); System.out printin("“Integer object Value : "+ i); } } 4.Write a program to make use of character wrapper class method Ans: class WrapChar t public static void main(String argsf]) i Character charobj= new Character (''); System.out printin(""Value of Character object : " + charobj); char ¢ = charobj.charValue(); System.out println("Value of char datatype : " + ¢); int i = Integer.valueOf{charobj); System.out printIn("Value of int datatype : " +i); double d= Double.valueOf{charobj); System.out printIn(""Value in double datatype : " + d); } } Conclusion: We studied the implementation of wrapper class to convert primitive i Practical Number: 16 Develop a programs for implementation of Wrapper class to convert object into primitive Exercise: 1, Develop a programs for implementation of Wrapper class to convert object into primitive Ans: public class WrapperExample{ public static void main(String args{)){ Converting Integer to i Integer a=new Integer(3);, int i-a.intValue()://converting Integer to int explicitly ‘unboxing, now compiler will write a,intValue() internally 2. Write a program to show the use of integer wrapper class method Ans: To convert objects into the primitive types, we can use the corresponding value methods (intValue(), doubleValue(), ete) present in each wrapper class. class Main { public static void main(Stringf] args) { (/ oreates objects of wrapper class Integer objl = Integer.valueON23); Double obj2 = Double.valueORS.55);, Boolean obj3 = Boolean.valueOf(true) // converts into primitive types int varl = objl.intValue(); double var2 = obj2.doubleValue(): boolean var3 = obj3.booleanValue(); // print the primitive values System.out printin("The value of int variable: " + varl); System,out.printin("The value of double variable: " + var2); System.out.printIn("The value of boolean variable: " + var3); } 3 Practical Related Questions: 1 List all wrapper classes in java Ans ‘Wrapper Classes in Java- + Byte + Short + Integer + Long + Float + Double + Character + Boolean 3. Write a program to convert integer object value into pri byte,short and double value, Ans: class Wrap { public static void main(String args[]) { Integer intobj = new Integer(10), byte b= intobj.byteValue(); short s= intobj shortValue(); double d=intobj.doubleValue(); System.out.printin("Integer object value : " + intobj); System.out printIn("Integer to byte value :" +b); System.out printIn("Integer to short value : " +s); System.out printin("Integer to double value :" + d); } Conelusion: Hence ,We studied the implementation of wrapper class to convert object into primitive. Practical Number: 17 Develop programs which implements the concept of overri Exercise: L.Develope a program using super and sub class to override the methods. Ans: class Bank t void interest() 1 System.out printin("Interest of Banks"); } } class SBI extends Bank fi t void interest() t System. out printin("Interest Rate of SBI Bank : " + 7. } class BOI extends Bank fi ( void interest() { System.out printIn("Interest Rate of BOI Bank : " + 8.0); } } class HDFC extends Bank f t void interest() { System.out printin("Interest Rate of HDFC Bank : " + 9.0); public class MainInterest { public static void main(String args{]) { SBI s = new SBI (); s.interest(); BOI b = new BOI (); b.interest(); HDFC h= new HDFC (); h.interest(): i } Output: Child class method 2.Develope a program using super keyword to override the methods to achieve the runtime polymorphism. class Animal t void move() t System.out.printin(""Animals can move"): } class Dog extends Animal { void move() t Super.move(): System. out printIn("Dogs can walk and run"); } } public class MainDog public static void main(String args[]) { Dog d= new Dog(): d.move(); } } 3, Demonstrate the use of overriding display method using super and sub classes. class Animal { public void display() { System.out.printin("T am an animal.”); class Dog extends Animal { @Override public void display() { System.out.printin("I am a dog."); class Main { public static void main(String{| args) { Dog di = new Doz(): di.display() Practical Related Questions: Qu No Method Overloading Method Overriding Method overloading is used to increase )) Ihe readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |») |Method overloading is performed within Method overriding occurs in inheritance to change the parameter. class. 5) |i method overloading, parameter must be| In method overriding, parameter must be different, same. [j) [Method overloading is the example of /Method overriding isthe example of run ‘compile time polymorphism, time polymorphism. Return type can be same or different in : 5) |imethod overloading, But you must have | Retum type must be same or covariant in imethod overriding. Q.2 Method Overriding is an example of. Ans : Run Time Polymorphism Q.3 Write the rules of Method Overriding Rules for Java Method Overriding 1. The method must have the same name , same parameter and same return type as in the super class Only inherited methods can be overridden. Constructors cannot be overridden. ween private in the super class public or protected in the super class A method declared final or static cannot be overridden. A subclass within same package can override method that is not declared as A subclass in a different package can override method that is declared as 4.Write the use of super keyword in Method Overriding 1, super can be used to refer immediate parent class instance variable, 2. super can be used to invoke immediate parent class method. 3. super() can be used to invoke immediate parent class constructor, Conclusion: ‘We have developed programs which implements the concept of overriding Practical Number — 18 Develop program for implementation of single and multilevel inheritance. Exerc 1.Write a program to implement single and multilevel inheritance Ans: class Animal{ void eat(){System.out.printin("eating...");} } class Dog extends Animal{ void bark(){System.out. printin(*barking...");} } class TestInheritance¢ public static void main(String args{])¢ Dog d=new Dog(); d.bark(); d.eat(); » Output: eating. barking Multilevel class Animal{ void eat(){System.out.printin("eating + class Dog extends Animal{ void bark(){System.out.printin("barking...");} + class BabyDog extends Dog{ iheritance:s void weep(){System.out.printin(*weeping...");} , class TestInheritance2{ public static void main(String args[)< BabyDog d=new BabyDoa\); d.weep)j dibark(); dveat(); 4 Output: weeping... 2, Develop a program to calculate the room area and volume to illustrate the concept of single inheritance class Room t int length,width; Room(int a,int b) « length width } void area() { int area = length*width; ‘System.out.printin("The area of the room is " +area); + + class roomvol extends Room t int height; roomvol(int a,int b,int c) { super(a,b); height = c; } void volume() java ThreadTest Even Thread i=2 Even Thread i=4 Even Thread i=6 Even Thread i=8 Odd Thread j=1 Odd Thread j= (Odd Thread Odd Thread j=7 Odd Thread j=9 Exit from Odd Even Thread i=10 Exit from Even Practical Related Questions: 1. Ist possible to start thread twice. ‘Ans: No, After starting a thread, it can never be started again. In such case, thread will run once but for second time, it will throw exception an //legal/hreadStateException. 2.Can we call the run method instead of start Ans Yes, we can call run() method instead of start(), but the rum() method goes into the current call stack instead of creating a new call stack where as the start() method starts a new thread of execution by creating a new call stack for the thread. 3.Diffrentiate between notify and notifyAll Ans: notify() method is used to give notification for only one Thread which is waiting for particular object. notifyAN( method is used to give notification to all waiting Threads of particular object 4.Explain the keyword synchronized Ans: Use of keyword Synchronized- In a multi-threaded environment, a race condition occurs when two or more threads attempt to update mutable shared data at the same time, Java provides synchronized keyword to avoid race condition. Java synchronized keyword marks a block or method as critical section. A critical section is where one and only one thread is executing at a time and locks the synchronized section so that all other threads wait till executing thread finishes its execution and releases lock Conclusion: We have implemented of multithreading operation Part-I and Part-II Practical Number — 23, 24, 25 Develop program for implementation of try, catch and finally block Exerc 1, //Program to demonstrate exception handling using try, catch, import java.lang.*; import java.util; class MyException extends Exception { My€xception(String msg) { super(mse); } } class demoexception { public static void main(String args{]) { try { Scanner sc=new Scanner(System.in); System.out.printin("Enter Number:"); int System.out.printin("Number is Even"); } else { ‘throw new MyException("Number is Not Even Number"); } } catch(MyException e) { System.out.printin( "Caught my exception"); ‘System.out.printin(e.getMessage()}; } finally { System.out.printin("End"); } } } Output: Java demoexception Enter Number: 25 Caught my exception Number is Not Even Number End 2. Program to throw an exception if password is incorrect. importjava.lang.Exception; importjava.util.*; classMyException extends Exception { My€xception(String msg) { super(msg); } } classpwdexception { public static void main(String args{]) { ty { Scanner sc=new Scanner(System.in); String password="mmp"; System. out.printin("Enter password: String s=sc.nextl); if{password.equals(s)) { System.out.printin("Authenticated”); } else { throw new MyException("Authentication Failure"); } } catch(MyException e) { System.out.printin("Caught my exception"); System.out.printin(e.getMessage()); } finally { System.out.printin("End"); } } } Java pwdexception Enter password poly ‘Caught my exception Authentication Failure End Practical Related Questions: 1, How Exception is thrown by main method? Ans When an exception is declared using throws in the main() method, it means that exception is thrown by main method() and the caller has to handle it. In this case, the caller will be the JVM so JVM will terminate main() method and removes corresponding entry from a stack, and hand over exception object to default exception handler which may simply print the exception message to standard output. For Example class TryCatch { public static void main(String[] args) throws Exception, { String str=null; System.out printIn(str.length()); } } 2.Diffrentiate between error and Exception in java Ans: Error Exception error is semantically and syntactical errors in java Exception means unwanted and unexpected exception in java An error is irrecoverable. An exception is recoverable. compiler checks errors at compile time compiler checks exception at run time Errors cannot be handled by programmer Exception can be handled by programmer using try, catch, throw keyword "java lang. Error" package is used to define an error "java lang. Exception” package is used to define an exception For Example OutOfMemory, StackOverFlow. For Example: ‘NullPointer, IndexOutOfBounds. 3.Can we throw exception manually? Illustrate with sample program Ans: ‘Yes, we can throw our own exception explicitly using throw keyword. For example: public class MyThrow t void validate(int age) a iflage<18) throw new ArithmeticException("Age is not Valid"); else System. out printin("Welcome to Vote"); i public static void main(String args(]) { MyThrow t= new MyThrow(); tvalidate(13); 4 } 4.Explain the use of finally block Ans Use of final block- © finally block is a block that is used fo execute important code such as closing connection, stream etc. * finally block is used to execute block whether exception is handled or not. Conclusion: In this experiment we have implemented try, catch and finally block Practical Number — 26-27 Develop a program for implementation of throw and throws clause Exercise: 1, Demonstrate the use of throw and throws clause. class ThowThrows void divide() throws ArithmeticException t int ans = 10/0; throw new ArithmeticException ("Math Error- Divide By Zero is Not Possible"); } public static void main(String argsf]) ThowThrows t = new ThowThrows(): try tdivided: ; catch(ArithmeticException e) t System out printin("Exception Catched in Main"); } } } Practical Related Questions: 1. Differentiate between throw and throws clause Ans throw clause throw keyword is used to explicitly throw an exception. ‘Throw is used within the method. multiple exceptions cannot be declare through throw 2. In which situation the throws clause is used Ans throws clause throws keyword is used to declare an exception Throws is used with the method signature. multiple exceptions can be declared through throws. throws clause is used in the function signature when the function has some statements that might throw some exceptions 3. Write the simple program for throwing our own exceptions. Ans import java.util.*; import java.io.*; class InsufficientBalanceException extends Exception { InsufficientBalanceException (String n) t System.out.println(n): } } class MyThrowOwn void withdraw() t long availablebalance=1000000; Scanner obj=new Scanner(System.in); System.out printin("Enter Amount to be withdrawn "); Jong amount= obj.nextLong(); if(balance>=1000) { availablebalance= balance; System. out printin(""Available Balance is : "+ availablebalance); } else throw new InsufficientBalanceException ("Sorry... Insufficient Balance..."); } catch (InsufficientBalanceException e) t ‘System.out printIn(""Minimum Balance Should be 1000/- "); } } publie static void main(String args[]) { MyThrowOwn t = new MyThrowOwn(); t.withdraw(); } 3 Conclusion: In this experiment we have implemented throw and throws clause Practical Number — 28 Develop minimum two basic applets. Display output with applet viewer and browser. a) Develop a program using basic applet b) Develop a program using control loops in applet Exercise: 1. Program to create an applet in different ways, //Program to create applet in different ways. //First.java import java.applet.Applet; import java.awt.Graphics; public class First extends Applet { public void paint(Graphics g) { 9.drawString("welcome",150,150); + + /* irst.class" width="300" height Ga. - GO x Practical Related Questions: 1. Develop a basic applet to display “Welcome to the world of Applet” Ans: import java.applet.*; import java.awt.*; public class WelcomeToApplet extends Applet { public void paint (Graphies g) { g.drawString ("Welcome to the World of Applet", 25, 50); 3 3 /* */ Wi Applet ViewrW. — O xX 2. Develop a program to implement all methods of an applet Ans: import java.awt.*; import java applet.*; /**/ public class AppletMethods extends Applet { public void init() 1 System.out println( "Initializing an applet"); 3 public void start() 1 System.out println("Starting an applet"); 3 public void stop() { System.out println("Stopping an applet"); 3 public void destroy() { ‘System.out println("Destroying an applet"); 3 } /*Output D:\PR\28>javac AppletMethods java D:\PR\28>appletviewer AppletMethods.java Initializing an applet Starting an applet Stopping an applet Destroying an applet */ 3. Develop a program using control loops in applet Ans: import java.awt.Graphies; import java.applet. Applet; import java. awt.Color, public class ChessBoard1 extends Applet public void paint(Graphies g) { int boxWidth = 0; boolean blackSquare = true; for (int y=0; y<8; y++) t for (int x=0; x<8; x++) t if (blackSquare) t g.setColor(Color-black); else t g.setColor(Color. white); } blackSquare = !blackSquare; 2 fillRect((x*box Width), (y*boxWidth),boxWidth,boxWidth); } blackSquare = !blackSquare; /* (E] Applet Viewer: ChessBoardt.class Conclusion: In this experiment we have implemented basic applet programming Practical Number — 29 Write a program to create animated shape using graphics and applets. You may use following shapes: a) Lines and rectangles b) Circles and Ellipses ©) Ares 4) Polygon with fill polygon method Exercise: 1, Write a program to implement an applet to draw basic animated shapes. import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Shapes extends Applet { Public void paint(Graphics 9) { int 2=250,b=250,c=10,d=10; for(int i=0;i<15;i++) t g.setColor(Color.red); try £ Thread.sleep(500); + catch(InterruptedException ex){} g.drawOval(a, b, c, d); a-=10; c+=10; d+=10; g.setColor(Color.green); g.drawRect(a,b,c,d); + + + /**/ [BlApplet Viewer Shapesdass — — Practical Related Questions: 1. Differentiate between executing the applet with applet viewer and in HTML file Ans: The first method of executing an applet in a Java-compatible web browser © Itrequires an HTML file that embeds the applet created in java file. + Through this method the entire web page can be shown containing the applet. © Torun this file, run the HTML file in the web browser ‘The Second method for executing an applet in an appletviewer tool © Itnot necessarily requires an HTML file that embeds the applet created in java file * Through this method only applet output can be shown instead of entire web page. © Torun this file, appletviewer HTMLfilename htm! or appletviewer javafilename java commands can be used 2. Explain methods required to draw different shapes with different colors Ans: Following two methods can be used to set different colors- 1, The setForeground() method is used to set the foreground color to for the object by specified color. 2, The Graphics.setColor() method is used to set the color for the object by specified color. 3. Differentiate between setforeground () and setColor() method Ans The setForeground() method is used to set the foreground color to for the object by specified color Syntax: void setForeground(Color.color_name) The Graphies.setColor() method is used to set the color for the object by specified color. Syntax:g.setColor(Color.color_name); 4.Differentiate between applets and applications Ans Java Application Applet Java applicationcontains a main method —_| An applet does not contain a main method Does not requireinternet connectionto | Requiresinternet connection to execute execute Isstand alone application Isa part of web page Can be run without a browser Requires a Java compatible browser anaes Use GUI interface provided by AWT or ‘Swings Entry point is init method Generally used for console programs Generally used for GUI interfaces Conclusion: In this experiment we have created animated shape using graphics and applets Practical Number — 30 Develop a program to draw following shapes, graphics and applets. a) Cone b) Cylinders ©) Cube d) Square inside a circle €)Cirele Inside a Square Exercise: 1. Program to draw cube, cylinder, cone in applet. import java.awt.*; import java.applet.*; // public class Shapes extends Applet { public void paint(Graphics g) ( g.drawOval(30,60,250,100); //For Cylinder g.drawLine(30,100,30,300); g.drawLine(280,100,280,300); g.drawOval(30,230,250,150);, g.drawOval(300,60,280,60); // For Cone g.drawLine(300,90,430,280); g.drawtine(230,280,580,90); g-drawRect(600,100,200,200); // Cube g.drawRect(700,200,200,200); g.drawLine(600,100,700,200); g.drawLine(800,100,900,200); g.drawLine(600,300,700,400); g.drawLine(800,300,900,400); Output: 2. Program to draw polygon in applet import java.awt.*; import java.applet.*; /sapplet code="Shapesi.class" height=300 width=500> public class Shapes extends Applet { ‘public void paint(Graphics e) { gsetColor(Color.red); g.fillRect(50,50,200,200); / Circle inside the Square esetColor(Color.green); eg illoval(55,55,190,190); gsetColor(Color.yellow); @ fillOval(300,50,190,190); // Square inside the Circle g.setColor(Color.blue); ae fillRect(340,90,110,110); Output: |.) Applet Viewer: ShapesL.class Applet Applet started Practical Related Questions: 1. Which of these methods is a part of Abstract window Toolkit(AWT)? a)displayQ) b)paint() c)drawstring)) d)none of the above Ans: paint() method 2. Enlist the methods to draw cylinder/cone Ans: To draw cylinder/cone following two methods are required: g.drawOval(int X, int Y, int width, int height); g.drawLine(int X1, int Y1, int X2, int ¥2); 3. Explain the method with syntax to draw circle Ans: The drawOval () method is used to draw a circle or an oval that fits within the rectangle specified by the X, Y, width and height arguments 4.Differentiate between applet and application Ans: Java Application Applet Java application contains a main method ‘An applet does not contain a main method Does not require internet connection to execute Requires internet connection to execute Is stand alone application Isa part of web page Can be run without a browser Requiresa Java compatible browser Uses stream I/O classes Use GUI interface provided by AWT or ‘Swings Entry point is main method Entry pointis init method Generally used for console programs Generally used for GUI interfaces Conclusion: In this experiment we have drawn mentioned shapes, graphics and applets Practical Number — 31 & 32 Develop a program for implementation of I/O stream and file stream classes Exercise: 1. Demonstrate the use of stream classes for reading and writing bytes/characters ‘+ Program to write bytes to a file. import java.io.*; public class ByteWriteToFile { public static void main(Strin[] ares) { FileOutputStream op=null; 'Writting byte contents to a file"; str.getBytes(); File f= new File("e:/MyTestFile.txt"); if (HRexists()) { ficreateNewFile(); ) op = new FileOutputstream(t); op.write(b); op.flush(}; op.close(); catch (IOException e) { System.out.printin(e); + Program to copy one file to another file using character stream. import java.io.*; public class CopyFile { public static void main(String args{)) throws IOException { FileReader in = null; FileWriter out= null; try { in = new FileReader("input.txt"); ‘out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { ‘out.write(c); } } finally { in.close(); out.close(); Practical Related Questions: 1, Enlist java stream classes, file operations Ans: InputStream and OutputStream are the basic stream classes in Java InPutStream: The InputStream is used to read data from a source OutPutStream: The OutputStream is used for writing data to a destination 2. Explain InputStream and OutputStream classes along with methods Ans: The most it portant methods used by InputStream and OutputStream classes are- Useful methods of OutputStream class: 1) public void write(int)throws IOException: It is used to write data to the current output stream. 2) public void flush()throws IOException: It flushes the current output stream. 3) public void close()throws IOException: It is used to close the current output stream, Useful methods of InputStream class: 1) public abstract int read()throws IOException: It reads the next byte of data from the input stream. It returns -1 at the end of the file. 2) public int available()throws IOException: It returns an estimate of the number of bytes that can be read from the current input stream. 3) public void close()throws IOException: It is used to close the current input stream 3. Explain Reader and Writer Stream classes Ans: Java readers and writers stream classes are used by character-based streams. + Reader Classes - These classes are subclasses of an abstract class, Reader and they are used to read characters from a source. + Writer Classes - These classes are subclasses of an abstract class, Writer and they used to write characters to a destination. Conclusion: In this experiment we have implemented of /O stream and file stream classes

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy