Pages

Sunday, 15 May 2022

JAVA LAB (2020) PROGRAMS

Introduction to Java:
        Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991. The target of Java is to write a program once and then run this program on multiple operating systems. The first publicly available version of Java (Java 1.0) was released in 1995. Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the seamanship for Java. In 2006 Sun started to make Java available under the GNU General Public License (GPL). Oracle continues this project called OpenJDK. 
        Over time new enhanced versions of Java have been released. Major versions were released after every 2 years, however the Java SE 7 took 5 years to be available after its predecessor Java SE 6, and 3 years for Java SE 8 to be available to public afterward. Since Java SE 10, new versions will be released very six months. 
        From the first version released in 1996 to the latest version 15 released in 2020, the Java platform has been actively being developed for about nearly 26 years. Many changes and improvements have been made to the technology over the years. The current version of Java is Java 15 or JDK 15 released on September, 15th 2020.
 
1. Write a program to perform all arithmetic Operations using command line arguments.
class Arithmatic
{
public static void main(String args[])
{
int x,y,z; // variable declaration 
x=Integer.parseInt(args[0]); // variable initialization y=Integer.parseInt(args[1]);
z=x+y;
System.out.println("Sum Of Two Numbers Is: "+z); 
z=x-y;
System.out.println("Difference Of Two Numbers Is: "+z); 
z=x*y;
System.out.println("Product Of Two Numbers Is: "+z);
z=x/y;
System.out.println("Quotient Of Two Numbers Is: "+z); 
z=x%y;
System.out.println("Remainder Of Two Numbers Is: "+z);
}
}
 
Command to compile: javac Arithmatic.java
Command to execute: java Arithmatic 12 15 
Output:
Sum Of Two Numbrs Is: 27 
Difference Of Two Numbrs Is: -3 
Product Of Two Numbrs Is: 180 
Quotient Of Two Numbrs Is: 0 
Remainder Of Two Numbrs Is: 12
 
2. Write a java program to calculate Compound Interest.
import java.util.*;
class CompoundInterest
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in); 
int p,t,r;
double ci=0.0,a=0.0; 
System.out.println("Enter Principal:"); 
p=s.nextInt(); 
System.out.println("Enter Time:");
t=s.nextInt(); 
System.out.println("Enter Rate:"); 
r=s.nextInt(); 
ci=p*(Math.pow(1+0.01*r,t));
System.out.println("Compound Interest : "+ci); 
a=p+ci;
System.out.println("Amount:"+a);
}
}
 
Command to compile: javac CompoundInterest.java
Command to execute: java CompoundInterest 
Output:
Enter Principal:
6700
Enter Time:
3
Enter Rate:
5
Compound Interest : 7756.087500000001 Amount:14456.087500000001
 
Control structures in Java
Java provides Control structures that can change the path of execution and control the execution of instructions. There are three kinds of control structures in Java.

1.Control statements/Conditional Branches
if statement: It is a simple decision-making statement. It is used to decide whether the statement or block of statements will be executed or not. Block of statements will be executed if the given condition is true otherwise the block of the statement will be skipped.
Syntax:
if(condition)
{
//Block of java statements
}

if-else statement: An if-else statement, there are two blocks one is if block and another is else blocked. If a certain condition is true, then if block will be executed otherwise else block will be executed.
Syntax:
if(condition)
{
//code for true
}
else
{
//code for false
}

Nested if statement: Nested if statements mean an if statement inside an if statement. The inner block of if statement will be executed only if the outer block condition is true.
Syntax: 
if(condition)
{
//statement if(condition)
{
//statement
}
}

if-else if statement/ ladder if statements: If we want to execute the different codes based on different conditions then we can use if-else-if. It is also known as if-else if ladder. This statement is always be executed from the top down. During the execution of conditions if any condition founds true, then the statement associated with that if is executed, and the rest of the code will be skipped. If none of the conditions is true, then the final else statement will be executed.
Syntax: 
if(condition1)
{
//code for if condition1 is true
}
else if(condition2)
{
//code for if condition2 is true
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions
}

Switch statement: The switch statement is like the if-else-if ladder statement. To reduce the code complexity of the if-else-if ladder switch statement is used. In a switch, the statement executes one statement from multiple statements based on condition. In the switch statements, we have a number of choices and we can perform a different task for each choice.
Syntax: 
switch(expression)
{
case value1:
//code for execution; break; //optional
case value2:
// code for execution break; //optional
......
......
......
......
Case value n:
// code for execution break; //optional
default:
code for execution when none of the case is true;
}

2.Loops in Java
while loop: A while loop allows code to be executed repeatedly until a condition is satisfied. If the number of iterations is not fixed, it is recommended to use a while loop. It is also known as an entry check conditional loop.
Syntax: 
while(condition)
{
//loop code here
}

do-while loop: It is like while loop with the only difference that it checks for the condition after the execution of the body of the loop. It is also known as Exit check Control Loop.
Syntax:
do
{
//code for execution
}while(condition);

for loop: If a user wants to execute the block of code several times. It means the number of iterations is fixed. JAVA provides a concise way of writing the loop structure.
Syntax:
for(initialization; condition ; increment/decrement)
{
statement(s);
}

3.Branching Statements in Java
These are used to alter the flow of control in loops.
break: If a break statement is encountered inside a loop, the loop is immediately terminated, and the control of the program goes to the next statement following the loop. It is used along with if statement in loops. If the condition is true, then the break statement terminates the loop immediately.
Syntax:
break;

continue: The continue statement is used in a loop control structure. If you want to skip some code and need to jump to the next iteration of the loop immediately. Then you can use a continue statement. It can be used for loop or while loop.
Syntax:
continue;
 
3.Write a program to check given number is zero or positive(Even/Odd) or negative(Even /Odd) Using nested if.
import java.util.Scanner;
class CheckEvenOdd
{
public static void main(String args[])
{
int n;
System.out.println("Enter an Integer number:"); 
Scanner s=new Scanner(System.in); n=s.nextInt();
if(n<=0)
{
if(n==0)
System.out.println("Given Number is Zero.."); 
else
{
if(n%2==0)
System.out.println("Entered number is Negative Even.."); 
else
System.out.println("Entered number is Negative Odd..");
}
}
else
{ if(n%2==0)
System.out.println("Entered number is even.."); 
else
System.out.println("Entered number is odd..");
}
}
}
 
Command to compile:javac Message.java
Command to compile:java CheckEvenOdd
Enter an Integer number: 0
Given Number is Zero..
java CheckEvenOdd 
Enter an Integer number:
-24
Entered number is Negative Even..
java CheckEvenOdd 
Enter an Integer number:
-57
Entered number is Negative Odd..
java CheckEvenOdd 
Enter an Integer number: 4789
Entered number is odd.. 
java CheckEvenOdd 
Enter an Integer number: 43568
Entered number is even..
 
4.Write a program to demonstrate arithmetic operations using switch..case.
import java.util.Scanner; 
class SwitchDemo
{
public static void main(String[] args)
{
double n1, n2,res;
Scanner s=new Scanner(System.in); 
System.out.print("Enter First Number:"); 
n1=s.nextDouble(); 
System.out.print("Enter Second Number:"); 
n2=s.nextDouble();
System.out.print("Enter an operator (+, -, *, /): "); 
char op=s.next().charAt(0);
switch(op)
{
case '+':res=n1+n2; break;
case '-':res=n1-n2;break;
case '*':res=n1*n2; break;
case '/':res= n1/n2;break;
default:
System.out.printf("You have entered wrong operator"); 
return;
}
System.out.println(n1+" "+op+" "+n2+": "+res);
}
}
 
Command to compile: javac SwitchDemo.java
Command to execute: java SwitchDemo 
Enter First Number:34
Enter Second Number:6
Enter an operator (+, -, *, /): + 
34.0 + 6.0: 40.0

java SwitchDemo 
Enter First Number:34
Enter Second Number:6 
Enter an operator (+, -, *, /): - 
34.0 - 6.0: 28.0

java SwitchDemo 
Enter First Number:34
Enter Second Number:6
Enter an operator (+, -, *, /): * 
34.0 * 6.0: 204.0

java SwitchDemo 
Enter First Number:34
Enter Second Number:6 
Enter an operator (+, -, *, /): /
34.0 / 6.0: 5.666666666666667

java SwitchDemo 
Enter First Number:34
Enter Second Number:6 
Enter an operator (+, -, *, /): a
You have entered wrong operator

5.Write a program to accept student number, student name and 5 subject’s (English, Telugu, Mathematics, Computers, Electronics) marks and calculate total marks and average marks. Display Total marks and average, iff student pass in all subjects, if student fails in any one subject just give only one message “FAIL”. Display student’s information based on the following conditions.

If totalmarks >= 460 Grade is A++
If totalmarks < 460 and totalmarks >=400 Grade is Distinction If totalmarks < 400 and totalmarks >=360 Grade is First Class If totalmarks < 360 and totalmarks >=250 Grade is Second
If totall marks < 250 and totalmarks >=200 Grade is Third Class
Note: Minimum marks should be 40 in each subject to be declared as PASS.
Solution: ( Using Nested if) 
import java.util.Scanner; class Student
{
public static void main(String x[])
{
Scanner s=new Scanner(System.in); 
int n,e,t,m,c,el,tot=0;
float av=0.0f;
String nam,res="FAIL",grd=""; 
System.out.println("Enter Student Number :"); 
n=s.nextInt();
System.out.println("Enter Student Name :"); 
nam=s.next();
System.out.println("Enter 5 Subject's marks :"); System.out.println("Enter English Marks:"); 
e=s.nextInt();
System.out.println("Enter Telugu Marks:"); 
t=s.nextInt();
System.out.println("Enter Mathematics Marks:"); 
m=s.nextInt();
System.out.println("Enter Computer Science Marks: "); 
c=s.nextInt();
System.out.println("Enter Electronics Marks: "); 
el=s.nextInt();
tot=e+t+m+c+el; av=tot/5.0f;
if(e>=40&&t>=40&&m>=40&&c>=40&&el>=40)
{
res="PASS";
if(tot>=460) grd="A++";
else if(tot>=400 && tot<460) grd="DISTINCTION";
else if(tot>=360 && tot<400) grd="FIRST CLASS";
else if(tot>=250 && tot<360) grd="SECOND CLASS";
else if(tot>=200 && tot<250) grd="THIRD CLASS";
System.out.println("Student Number : "+n); System.out.println("Student Name : "+nam); 
System.out.println("Total Marks: "+tot); 
System.out.println("Average Marks: "+Math.round(av)); System.out.println("Grade: "+grd); 
System.out.println("Result: "+res);
}
else
{
System.out.println("Result: "+res);
}
}
}
 
Command to Compile: javac Student.java 
Command to execute: java Student 
Output:
Enter Student Number : 124
Enter Student Name : Suresh
Enter 5 Subject's marks : 
Enter English Marks:
67
Enter Telugu Marks:
89
Enter Mathematics Marks: 98
Enter Computer Science Marks: 99
Enter Electronics Marks: 78
Student Number : 124 
Student Name : Suresh 
Total Marks: 431
Average Marks: 86 
Grade: DISTINCTION
Result: PASS
javac Student.java 
java Student
Enter Student Number : 162
Enter Student Name : Vijay
Enter 5 Subject's marks : 
Enter English Marks:
34
Enter Telugu Marks:
67
Enter Mathematics Marks: 76
Enter Computer Science Marks: 78
Enter Electronics Marks: 98
Result: FAIL
 
6.Write a program to find largest number of 3 numbers using if..else..if (if else ladder).
class IfElseLadder
{
public static void main(String x[])
{
int a,b,c; 
a=Integer.parseInt(x[0]); 
b=Integer.parseInt(x[1]); 
c=Integer.parseInt(x[2]); 
if(a>b && a>c)
{
System.out.println("A - it is "+a+" is the largest Number");
}
else if(b>a && b>c)
{
System.out.println("B - it is "+b+" is the largest Number");
}
else
{
System.out.println("C - it is "+c+" is the largest Number");
}
}
}
 
Command to compile: javac IfElseLadder.java
Command to execute: java IfElseLadder 23 56 9 
Output:
B - it is 56 is the largest Number Command to execute:
I:\>java IfElseLadder 23 6 9 
Output:
A - it is 23 is the largest Number 
Command to execute:java IfElseLadder 23 6 99 
Output:
C - it is 99 is the largest Number
 
7.Write a program to Generate prime numbers from 2, to the given number.
class GenPrime
{
public static void main(String a[])
{
int x=Integer.parseInt(a[0]); 
for(int n=2;n<=x;n++)
{
int c=0;
for(int i=1;i<=n;i++)
{
if((n%i)==0) 
c++;
}
if(c==2) 
System.out.println(n);
}
}
}
 
Command to compile: javac GenPrime.java 
Command to execute: java GenPrime 50
Output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
 
Object Oriented programming(OOP)
Object Oriented programming is a programming paradigm that relies on the concept of classes and objects. It is used to structure a software program into simple, reusable pieces of code blueprints (usually called classes), which are used to create individual instances of objects. There are many object-oriented programming languages including JavaScript, C++, Java, and Python.

Class:
It is a user defined data type. A class can be considered as a blueprint using which you can create as many objects as you require. A class is a static entity. Do not occupy memory in main memory until we create an object of it. A class is a group of objects that share common properties and behaviour.

Object:
Objects are instances of classes. Objects have attributes/states and methods/behaviours. Attributes are data associated with the object while methods are actions/functions that the object can perform. An object is a dynamic entity. It occupies space in main memory according to the members used in that class.

Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safe from outside interference and misuse. Encapsulation simply means binding object state(fields/variables) and behaviour(methods/functions) together.

Inheritance:
The process by which one class acquires the properties and functionalities of another class is called inheritance.

Polymorphism:
The ability to define more than one function with the same name is called polymorphism. It is the ability of an object to take on many forms. It gives us the ultimate flexibility in extensibility.  Polymorphism can be achieved in java in two ways. They are
Compile Time Polymorphism(Can be achieved through Method / Function Overloading)
Run Time Polymorphism(Can be achieved through Method / Function Overriding)

Abstraction
Abstraction can be defined as the process of hiding the unwanted details and exposing only the essential features of a particular object or concept. In java abstraction can be achieved with either abstract classes or interfaces.
 
8. Write a program to create a class, object and access the method of a class.
import java.util.Scanner; 
class ClsObjMed
{
int salary; 
String name; 
String dept; 
void show()
{
System.out.println("\nEmployee Name :"+name); System.out.println("Department Name :"+dept); System.out.println("Salary:Rs."+salary);
}
public static void main(String x[])
{
ClsObjMed ob=new ClsObjMed(); 
Scanner s=new Scanner(System.in);
System.out.println("Enter Employee Name :");
ob.name=s.nextLine(); // nextLine() is used to accept string(group of characters / words) 
System.out.println("Enter Department Name :");
ob.dept=s.nextLine(); 
System.out.println("Enter Salary:"); 
ob.salary=s.nextInt();
ob.show();
}
}
 
Command to compile: javac ClsObjMed.java 
Command to execute: java ClsObjMed 
Output:
Enter Employee Name : 
Vignesh
Enter Department Name : 
ADMIN
Enter Salary:
89654
Employee Name :Vignesh 
Department Name :ADMIN 
Salary:Rs.89654
 
9.Write a program to demonstrate Single Inheritance.
class Flower
{
void look()
{
System.out.println("Flowers are beautiful...");
}
}
class Rose extends Flower
{
void odor()
{
System.out.println("Rose milk is sweet & nice...");
}
}
class TestInheritance
{
public static void main(String args[])
{
//Rose r=new Rose(); //object declaration and creation 
Rose r; // declaration of object
r=new Rose(); // creation of object 
r.odor(); // calling the same class method 
r.look(); // calling inherited method
}
}
 
Command To Compile: javac TestInheritance.java 
Command To Execute: java TestInheritance 
Output:
Rose milk is sweet & nice... Flowers are beautiful...
 
10.Write a program to implement compile time polymorphism(method overloading).
class Overload
{
void demo (int a)
{
System.out.println ("Value Passed to Method with 1 Argument, It is:"+a);
}
void demo (int a, int b)
{
System.out.println ("Values Passed to Method with 2 Arguments, They are:"+a+" & "+ b);
}
double demo(double a)
{
System.out.println("Value Passed to Method with 1 Argument of double type, It is: "+a); 
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload ov=new Overload(); 
double res;
ov.demo(10);
ov.demo(10, 20); 
res=ov.demo(5.5);
System.out.println("Square of the Given double Value is: "+res);
}
}
 
Command to compile:javac MethodOverloading.java 
Command to execute:java MethodOverloading 
Output:
Value Passed to Method with 1 Argument, It is:10
Values Passed to Method with 2 Arguments, They are:10 & 20 
Value Passed to Method with 1 Argument of double type, It is: 5.5 Square of the Given double Value is: 30.25
 
11.Write a program to demonstrate constructor with argument and without argument.
class Employee
{
int id;
String name; 
float salary; 
Employee()
{
id=104;
name="Sweta"; 
salary=35000;
}
Employee(int x,String y,float z)
{
id=x; 
name=y; 
salary=z;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
class TestCons
{
public static void main(String[] args)
{
Employee e1=new Employee(); 
System.out.println("Constructor with out argument is called"); e1.display();
Employee e2=new Employee(105,"Swati",56000); System.out.println("Constructor with argument is called"); 
e2.display();
}
}
 
Command to compile: javac TestCons.java 
Command to execute:java TestCons 
Output:
Constructor with out argument is called 
104 Sweta 35000.0
Constructor with argument is called 
105 Swati 56000.0
 
INTERFACE
An Interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default.
Syntax:
interface <interface_name>
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1(); 
public void method2();
....
}

VECTOR
Vector is like the dynamic array(re-sizable array) which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. The Vector class implements a growable array of objects. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here.

12.Write a program to demonstrate a Vector.
import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
//Create an empty vector with initial capacity 4 
Vector<String> vec = new Vector<String>(4);
//Adding elements to a vector 
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog"); 
vec.add("Elephant");
//Check size and capacity 
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements 
System.out.println("Vector element is: "+vec); 
vec.addElement("Rat"); 
vec.addElement("Cat"); 
vec.addElement("Deer");
//Again check size and capacity after two insertions System.out.println("Size after addition: "+vec.size()); System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again 
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}
 
Command to compile:javac VectorExample.java 
Command to execute:java VectorExample 
Output:
Size Of Vector is: 4
Current capacity Of Vector is: 4
Elements of Vector are: [Tiger, Lion, Dog, Elephant] 
Size Of Vector after adding New Elements:7 
Capacity Of Vector adding New Elements: 8
Now Elements in Vector are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer] Tiger is present at the index 0
The first animal of the Vector is = Tiger 
The last animal of the Vector is = Deer
 
13.Write a program to demonstrate Interface concept.
interface Picture
{
public void birds();
public void animals(); 
public void men(); 
public void women(); 
public void nature();
}
class ShowPictures implements Picture
{
public void birds()
{
System.out.println("This is implementation of birds Method");
}
public void animals()
{
System.out.println("This is implementation of animals Method");
}
public void men()
{
System.out.println("This is implementation of men Method");
}
public void women()
{
System.out.println("This is implementation of women Method");
}
public void nature()
{
System.out.println("This is implementation of nature Method");
}
}
class UseShowPictures
{
public static void main(String arg[])
{
Picture p=new ShowPictures(); 
p.birds();
p.nature();
}
}
 
Command to compile:javac UseShowPictures.java 
Command to execute:java UseShowPictures 
Output:
This is implementation of birds Method 
This is implementation of nature Method

Exception Handling
Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions. If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. This message is not user friendly so a user will not be able to understand what went wrong. In order to let them know the reason in simple language, we handle exceptions. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user.

There are two types of exceptions in Java:
1)Checked exceptions 
2)Unchecked exceptions

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation.
Ex: SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time.
Ex:ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException etc.

About Try block.
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch block(s) or finally block or both.
Syntax: 
try
{
//statements that may cause an exception
}

About Catch block.
A catch block is where you handle the exceptions. This block must follow the try block. A single try block can have several catch blocks associated with it. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
Syntax:
catch (exception(type) e(object))
{
//error handling code
}

About Throw block.
We can define our own set of conditions or rules and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException when we divide number by 5, or any other numbers.
 
Syntax:
throw new exception_class("error message"); 
Ex:
throw new ArithmeticException("dividing a number by 5 is not allowed in this program");

Finally block.
A finally block contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.
Syntax:
finally
{
//Statements to be executed
}
 
14.Write a program to demonstrate Exception Handling using try and catch blocks.
import java.util.Scanner; 
class JavaException1
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in); 
System.out.println("Enter divisor :"); 
try
{
int d=s.nextInt(); 
int n = 20;
int fraction = n / d; 
int g[] = {1};
System.out.println("Enter index of array :"); 
g[s.nextInt()] = 100;
}
catch (ArithmeticException e)
{
System.out.println("In the catch block due to Exception = " + e);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("In the catch block due to Exception = " + e);
}
catch(Exception e)
{
System.out.println("In the catch block due to Exception = "+e);
}
System.out.println("End Of Main");
}
}
 
Command to compile:javac JavaException1.java 
Command to execute:java JavaException1 
Output1:
Enter divisor :
0
In the catch block due to Exception = java.lang.ArithmeticException: / by zero 
End Of Main
Output2:
I:\>java JavaException1 Enter divisor :
1
Enter index of array :
0
End Of Main
Output3:
java JavaException1 
Enter divisor :
1
Enter index of array :
5
In the catch block due to Exception = java.lang.ArrayIndexOutOfBoundsException: 5 
End Of Main
 
15.Write a program to demonstrate Exception Handling using try, catch, finally & throw.
import java.util.Scanner; 
class Excep
{
static void test(int testnum) throws Exception
{
System.out.println ("Start - test method"); 
if (testnum == 12)
throw new Exception(); 
System.out.println("End - test method");
return;
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in); 
System.out.println("Enter any number:"); 
int testnum = s.nextInt();
try
{
System.out.println("Entered into Try block - Passed First Statement"); test(testnum);
System.out.println(testnum/0); 
System.out.println("Exiting Try block - Last Statement");
}
catch ( ArithmeticException ex)
{
System.out.println("ArithmeticException - Division by zero is not defined...");
}
catch ( Exception ex)
{
System.out.println("An Exception");
}
finally
{
System. out. println( "Message from finally block") ;
}
System.out.println("Out of - Try, Catch, Finally - statements");
}
}
 
Command to compile :javac Excep.java 
Command to execute :java Excep Output:
Enter any number:
100
Entered into Try block - Passed First Statement 
Start - test method
End - test method
ArithmeticException - Division by zero is not defined... 
Message from finally block
Out of - Try, Catch, Finally - statements
Output:
java Excep 
Enter any number:
12
Entered into Try block - Passed First Statement 
Start - test method
An Exception
Message from finally block
Out of - Try, Catch, Finally - statements
 
Thread
A thread is basically a lightweight and the smallest unit of process or lightweight sub-process, Threads share the common memory space. Java uses threads by using a "Thread Class". There are two types of threads, they are user threads and daemon threads (daemon threads are used when we want to clean the application and are used in the background). When an application first begins, user thread is created. Post that, we can create many user threads and daemon threads.

Life Cycle Of a Thread
New: A thread that has not yet started will be in this state. In this phase, the thread is created using class "Thread class". It remains in this state till the program starts the thread. It is also known as born thread.

Runnable: A thread executing in the Java virtual machine is in this state. In this phase, the instance of the thread is invoked with a start() method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.

Running: Once the thread starts executing, then the state is changed to "running" state. The scheduler selects one thread from the thread pool, and it starts executing in the application.

Waiting: A thread that is waiting indefinitely for another thread to perform a particular action is in this state. As there multiple threads are running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread gets executed. Therefore, this state is referred as waiting state.

Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".
 
16.Write a program to demonstrate Multithreading.
class MulThread extends Thread
{
private int number;
//class constructor
public MulThread(int number)
{
this.number = number;
}
public void run()
{
int counter = 0; 
int numInt = 0;
//prints the number till specified number is reached, starting from 10
try
{
do
{
numInt = (int) (counter + 10); 
System.out.println(this.getName() + " printing " + numInt); Thread.sleep(1000);
counter++;
}while(numInt != number);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("**"+this.getName() + " Printed " + counter + " Times.**");
}
}
class UseMulThread
{
public static void main(String [] args)
{
System.out.println("Starting Thread1"); 
Thread t1 = new MulThread(15); 
t1.start();
System.out.println("Starting Thread2"); 
Thread t2 = new MulThread(20); 
t2.start();
}
}
 
Command to compile: javac Multhread.java 
Command to execute: java UseMulThread 
Output:
Starting Thread1 
Starting Thread2 
Thread-0 printing 10
Thread-1 printing 10
Thread-0 printing 11
Thread-1 printing 11
Thread-0 printing 12
Thread-1 printing 12
Thread-0 printing 13
Thread-1 printing 13
Thread-0 printing 14
Thread-1 printing 14
Thread-0 printing 15
Thread-1 printing 15
**Thread-0 Printed 6 Times.** 
Thread-1 printing 16
Thread-1 printing 17
Thread-1 printing 18
Thread-1 printing 19
Thread-1 printing 20
**Thread-1 Printed 11 Times.**
 
PACKAGE
A package is a group of classes, interfaces and other packages. In java we use packages to organize our classes and interfaces. A package is nothing but a physical folder structure (directories) that contains a group of related classes, interfaces, and sub-packages according to their functionality.

Types of Packages in Java
They can be divided into two categories:
1.Java API packages or built-in packages and 
2.User-defined packages.

1.Java API packages or built-in packages 
Ex:
java.lang: It contains classes for primitive types, strings, math functions, threads, and exceptions. 
java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.
java.io: It has stream classes for Input/Output.
java.awt: Classes for implementing Graphical User Interface – windows, buttons, menus, etc. 
java.net: Classes for networking
java. Applet: Classes for creating and implementing applets


2.User-defined packages
As the name suggests, these packages are defined by the user. We create a directory whose name should be the same as the name of the package. Then we create a class inside the directory.
 
17.Write a program to demonstrate Package concept.
Note: This record program contains two sections. In first section we need to create a Package containing class, here Package is "Calc" and class is "Mensuration" and save it in a separate file. In the second section create one more file that uses the above package and here it is " UseCalc" class, save this in a separate files. All together we need to create two separate files.

Filename1 : Mensuration.java
package Calc;
public class Mensuration
{
public double volume(double l,double b,double h)
{
return l*b*h;
}
public double tsa(double l,double b,double h)
{
return 2*(l*b+b*h+l*h);
}
public double lsa(double l,double b,double h)
{
return 2*h*(l+b);
}
public double diag(double l,double b,double h)
{
return Math.pow(l*l+b*b+h*h,0.5);
}
public double peri(double l,double b,double h)
{
return 4*(l+b+h);
}
}

File Name2 : UseCalc.java 
import Calc.Mensuration; 
import java.util.Scanner; 
class UseCalc
{
public static void main(String x[])
{
double l,b,h;
Scanner s=new Scanner(System.in); 
Mensuration m=new Mensuration();
System.out.println("Enter Length, Breadth & Height:"); l=s.nextDouble();
b=s.nextDouble(); 
h=s.nextDouble();
System.out.println("Volume Of Cuboid: "+m.volume(l,b,h));
System.out.println("Total Surface Area :"+m.tsa(l,b,h)); System.out.println("Lateral Surface Area: "+m.lsa(l,b,h));
System.out.println("Length of diagonal of the cuboid: "+Math.round(m.diag(l,b,h))); 
System.out.println("Perimeter of Cuboid: "+m.peri(l,b,h));
}
}

Command to compile and to create a package Calc
I:\>javac -d . Mensuration.java Command to compile 
I:\>javac UseCalc.java Command to execute
I:\>java UseCalc 
Output:
Enter Length, Breadth & Height: 
12
13
14
Volume Of Cuboid: 2184.0 
Total Surface Area :1012.0 
Lateral Surface Area: 700.0
Length of diagonal of the cuboid: 23 
Perimeter of Cuboid: 156.0
 
18.Write a program to implement Linear search.
import java.util.Scanner; 
class ls
{
public static void main(String x[])
{
int c, n, sv, a[];
Scanner s = new Scanner(System.in); 
System.out.println("Enter number of elements:"); 
n = s.nextInt();
a = new int[n]; //creating array 
System.out.println("Enter " + n + " integers"); 
for (c = 0; c < n; c++)
a[c] = s.nextInt(); 
System.out.println("Enter Search Value:"); 
sv = s.nextInt();
for (c = 0; c < n; c++)
{
if (a[c] == sv)
{
System.out.println(sv+" is present at location "+(c+1)); 
break;
}
}
if (c == n)
System.out.println(sv + " doesn't exist in array.");
}
}
 
Output: 
E:\>javac ls.java 
E:\>java ls
Enter number of elements: 4
Enter 4 integers
56
7
88
9
Enter Search Value: 7
7 is present at location 2
 
19.Write a program to implement Bubble Sort.
import java.util.Scanner; 
class bsrt
{
static public void main(String x[])
{
int n,i,j,t=0,a[];
System.out.println("Enter Size Of Array :"); 
Scanner s=new Scanner(System.in); 
n=s.nextInt();
a=new int[n];
System.out.println("\nEnter "+n+" Elements :"); 
for(i=0;i<n;i++)
a[i]=s.nextInt(); 
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j]; 
a[j]=a[j+1]; 
a[j+1]=t;
}
}
}
System.out.println("\nElements After Sorting :"); 
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
 
Output: 
E:\>javac bsrt.java 
E:\>java bsrt
Enter Size Of Array : 4
Enter 4 Elements : 
33
4
55
6
Elements After Sorting : 
4
6
33
55
 
INPUT / OUTPUT STREAMS
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical. Java encapsulates Stream under java.io package. Java defines two types of streams. They are, 
1.Byte Stream : It provides a convenient means for handling input and output of byte.
2.Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

Java Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.

Java Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.

Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard.
20.Write a program to demonstrate Input / Output Streams in Java.
Note : You need to write two programs(need to create two files), One to input the data and the other to read the data.

File Name : FileCreation.java
Note: The above file is used to input the data which in turn save the inputted data into a file named “data.txt” )
import java.io.*;
public class FileCreation
{
public static void main(String[] args)
{
try
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); 
String st=null,ct="";
char res='t';
Writer w = new FileWriter("gurudata.txt");
//String content = "This is to add a single line text..."; 
while(res!='x')
{
st=b.readLine(); 
res=st.charAt(0); 
if(res=='x') 
break;
ct=ct+st+"\r\n"; //here \r\n combination is to produce a new line
}
w.write(ct);
w.close();
System.out.println("File Is Saved!!!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
 
Command to compile: javac FileCreation.java
Command to execute: java FileCreation
Output:
Full many a gem of purest ray serene
the dark unfathomed caves of ocean bear 
Full many a flower is born to blush unseen 
and waste its fragrance in the desert air
x
File Is Saved!!!
 
File Name : FileRead.java
Note: The above file is used to read the data from the file named “gurudata.txt” ) 
import java.io.*;
public class FileRead
{
public static void main(String[] args)
{
BufferedReader br=null; 
try
{
String s;
br=new BufferedReader(new FileReader("I:\\gurudata.txt")); 
while ((s=br.readLine()) != null)
{
System.out.println(s);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br!=null) 
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
}
 
Command to compile: javac FileRead.java
Command to execute: java FileRead
Output:
Full many a gem of purest ray serene
the dark unfathomed caves of ocean bear 
Full many a flower is born to blush unseen 
and waste its fragrance in the desert air

No comments:

Post a Comment

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...