Professional Documents
Culture Documents
Class OOPs
Type Lab
Introduction to Java
1. Installation of Oracle JDK
1. Press Ctrl+Shift+T to open the terminal or click on the terminal icon in the applications menu.
Experiment - 1 1
3. Check the versions of java and javac in the terminal by typing java —version and javac —version, respectively.
The following are the most widely used Java IDEs in the world:
Eclipse: It is a Java-based open-source platform that enables the creation of highly customized IDEs using plug-in
components contributed by Eclipse members.
Experiment - 1 2
NetBeans: An integrated development environment (IDE) and basic application platform foundation based on Java.
IntelliJ IDEA: Commercial Java IDE that is both open source and free. It is available in a premium Ultimate edition
and a free, open-source community edition.
BlueJ: Java IDE that is frequently utilized by Java programmers worldwide. However, its primary goal was education,
which is also valuable for software development.
JCreator: Xerox Software has developed yet another lightweight Java integrated development environment. It features
a comparable graphical interface to Microsoft's Visual Studio.
Experiment - 1 3
Experiment - 2
Class OOPs
Type Lab
AIM:
1. Write and execute my first java program
2. Write a program to print the Fibonacci series using java loop ( up to 10 numbers)
class First
{
public static void main(String args[])
{
System.out.println("Hello Muditt Sharmma");
System.out.println("SAP ID: 50009175");
System.out.println("ROLL NO: R2142210506");
}
}
Experiment - 2 1
2) Write a program to print the Fibonacci series using java loop ( up to 10
numbers)
Algorithm:
1. Create a class FIrst2
class First2
{
public static void main(String args[])
{
System.out.println("NAME: Muditt Sharmma");
System.out.println("SAP:500091725,ROLL NO:R2142210506");
int a=0;
int b=1;
System.out.println(a);
System.out.println(b);
for(int i=0;i<10;i++){
int c = a+b;
a = b;
b =c;
System.out.println(c);
}
}
}
Experiment - 2 2
3. Print the contents required to be printed using print commands
class First3
{
public static void main(String args[])
{
System.out.println("NAME: Muditt Sharmma");
System.out.println("SAP:500091725,ROLL NO:R2142210506");
int i=49,j=53,k=64;
if(i>j&&i>k){
System.out.println("the biggest number is i");
}
else if(j>k&&j>i){
System.out.println("the biggest number is j");
}
else{
System.out.println("the biggest number is k");
}
}
}
5. Inside a for loop, set a condition for if i%5=0 then print the value of i and then add the value of i in sum. value of i
keeps increasing.
6. Print sum
class First5
{
Experiment - 2 3
public static void main(String args[])
{
System.out.println("Name: Muditt Sharmma");
System.out.println("SAP:500091725,ROLL NO:R2142210506");
int sum=0;
for (int i=41;i<250;i++){
if(i%5==0){
System.out.println(i);
sum=sum+i;
}
}
System.out.println(sum);
}
}
Experiment - 2 4
Experiment - 3
Class OOPs
Type Lab
AIM:
1. Write a program to take input (a number) of a month (1 - 12) and print its equivalent name of the month. ( e.g 1 to Jan,
2 to Feb. 12 to Dec.) Use Scanner class for user input( Hint-use switch case).
4. Write a program that takes students’ info from the user (using Scanner class) and displays output on a black screen.
Use appropriate mutator and accessor. setInfo(),getInfo().
1) Write a program to take input (a number) of a month (1 - 12) and print its
equivalent name of the month. ( e.g 1 to Jan, 2 to Feb. 12 to Dec.) Use
Scanner class for user input( Hint-use switch case).
import java.util.*;
class First4{
public static void main(String [] args){
System.out.println("Name: Muditt Sharmma,Sap ID : 500091725, Roll No.: R2142210506");
switch(i){
case 1:
System.out.println("January");
break;
case 2:
System.out.println("Febuary");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
Experiment - 3 1
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("There is an error with the user input");
}
}
}
Algorithm:
1) To use the Scanner class, import the java.util. * module.
2) In the main method, make the scanner object.
3) Using the scanner object, ask the user for inputs and store them in the variable “i”.
4) Use a "i" expression in a switch case statement.
5) Write cases 1 through 12 and statements to print the names of the months that go with them.
class Summision{
public static void main(String args[]){
System.out.println("Name: Muditt Sharmma,Sap ID : 500091725, Roll no. : R2142210506");
Double a=Double.parseDouble(args[0]);
Double b=Double.parseDouble(args[1]);
Double c=a+b;
System.out.println(c);
}
}
Algorithm:
1. Create a summary for your class
Experiment - 3 2
6. Print the output
class Calculator{
public static void main(String args[]){
System.out.println("Name: Muditt Sharmma, Sap ID : 500091725, Roll no. : R2142210506");
Double a,b,Sum,Dif,Prod,Quoet,Rem;
a=Double.parseDouble(args[0]);
b=Double.parseDouble(args[1]);
Sum=a+b;
Dif=a-b;
Prod=a*b;
Quoet=a/b;
Rem=a%b;
}
}
Algorithm:
1. Create a class calculator
5. Assign Sum=a+b
6. Assign Dif=a-b
7. Assign Prod=a*b
8. Assign Quoet=a/b
9. Assign Rem=a%b
Experiment - 3 3
4) Write a program that takes students’ info from the user (using Scanner
class) and displays output on a black screen. Use appropriate mutator and
accessor. setInfo(), getInfo().
import java.util.*;
class StudentRec{
static String Name;
static int Rollno;
static String Branch;
static Scanner input;
Algorithm:
1. Load the java.util.* module.
Experiment - 3 4
7. Create up with the main way
10. Make and use the setinfo() function to get the input.
11. Make the getinfo function and use it to print out the information from the setinfo() function.
Experiment - 3 5
Experiment - 4
Class OOPs
Type Lab
AIM:
1. Write a JAVA program to implement class mechanism. – Create a class, define datamembers, methods
(setData(args) ,getData()) and invoke them inside main method.
2. Write software to prepare the results of the student for school examination. The Roll no ofthe students and their marks
in subjects of Physics, Chemistry and Maths are suppliedthrough the Scanner class. The result of the subject is
prepared and displayed on the outputscreen by finding the students who fail and pass the exam. If the marks are
below 40% insubject, then the student has failed in the subject. If the student passes and the aggregatescore is above
75% then he scores Distinction. If the student passes and aggregate marksare 60%,50%, and 40% then he scores
First, Second, and Third Division. Mention all thecases in output.
import java.util.*;
class Sleep{
static String Sleptat;
static String Wokeupat;
static Scanner input;
Experiment - 4 1
Algorithm:
1. Import all the modules from java util library.
import java.util.*;
class StudentMarks{
static String Name;
static int Rollno;
static String Branch;
static Scanner input;
static int PhysicsPer;
static int ChemistryPer;
static int MathsPer;
static int Aggregate;
Experiment - 4 2
public static void main(String[] args){
System.out.println("Name: Muditt Sharmma,\n Sap ID : 500091725, \n Roll no. : R2142210506");
input = new Scanner(System.in);
setinfo();
getinfo();
sorted();
}
System.out.println("Chemistry Percentage:"+ChemistryPer);
if(ChemistryPer<100 && ChemistryPer<40){
System.out.println("You failed in Chemistry");
}
else if(ChemistryPer<100 && ChemistryPer>75){
System.out.println("You scored a distinction in Chemistry");
}
else if(ChemistryPer<100&& ChemistryPer>=40){
System.out.println("You passed");
}
else{
System.out.println("INVALID");
}
System.out.println("");
System.out.println("Maths Percentage:"+MathsPer);
if(MathsPer<100 && MathsPer<40){
System.out.println("You failed in Maths");
}
else if(MathsPer<100 && MathsPer>75){
System.out.println("You scored a distinction in Chemistry");
}
else if(MathsPer<100&& MathsPer>=40){
System.out.println("You passed");
}
else{
System.out.println("INVALID");
}
System.out.println("");
Aggregate=(PhysicsPer+MathsPer+ChemistryPer)/3;
System.out.println("Aggregate:"+Aggregate);
if(Aggregate<100 && Aggregate<40){
System.out.println("You have failed. You have to repeat a year");
}
else if(Aggregate<100 && Aggregate>75){
System.out.println("You have scored a distinction");
}
else if(Aggregate>=40 && Aggregate<50){
System.out.println("You passed Third Division");
}
else if(Aggregate>=50 && Aggregate<60){
Experiment - 4 3
System.out.println("You passed Second Division");
}
else if(Aggregate>=60 && Aggregate<75){
System.out.println("You passed First Division");
}
else{
System.out.println("INVALID");
}
}
Algorithm:
1. Import every module from java util library
3. create the required variables like Name, Roll no, Branch, and marks.
13. check the conditions for passing, distinction, first division, second division and third division and show the result
accordingly
Experiment - 4 4
{
System.out.println("Sum of the doubles: "+(a+b));
}
sum(1.2, 2.4);
}
}
Algorithm:
1. create a class called Polymorphism
Experiment - 4 5
Algorithm:
1. Create a class TypePromotion
2. Create a sum function with parameters as int num1 and int num2
5. return s
8. result = sum(10,20)
9. show result
class ConstructorOverloading
{
private int Rupee;
ConstructorOverloading()
{
Rupee =49;
}
ConstructorOverloading(int r)
{
this();
Rupee = Rupee+ r;
}
public int getRupee(){
return Rupee;
}
public void setRupee(int Rupee) {
this.Rupee = Rupee;
}
public static void main(String args[])
{
ConstructorOverloading obj = new ConstructorOverloading(12);
System.out.println(obj.getRupee());
}
}
Experiment - 4 6
Algorithm:
1. create a class ConstructorOverloading
5. set Rupee to 49
8. set Rupee=Rupee+r
14. create obj as the new instance for ConstructorOverloading() and pass 12 as the value of r in the parenthesis
Experiment - 4 7
Experiment-5
Class OOPs
Type Lab
AIM:
1. Write a Java program to show that private member of a super class cannot be accessed from derived classes.
2. Write a program in Java to create a Player class. Inherit the classes Cricket _Player, Football _Player and Hockey_
Player from Player class.
3. Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every worker has a name and a
salary rate. Write method ComPay (int hours) to compute the week pay of every worker. A Daily Worker is paid on the
basis of the number of days he/she works. The Salaried Worker gets paid the wage for 40 hours a week no matter
what the actual hours are. Test this program to calculate the pay of workers. You are expected to use the concept of
polymorphism to write this program.
4. Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent or lightning. The charges
depend on the duration and the type of the call. Write a program using the concept of polymorphism in Java to
calculate the charges.
1)Write a Java program to show that private member of a super class cannot
be accessed from derived classes.
class Student1{
String name;
private int age,rollno;
void setage(int age) {
this.age=age;
}
int getage() {
return age;
}
void setroll(int rollno) {
this.rollno=rollno;
}
int getroll() {
return rollno;
}
void print() {
System.out.println(name+" "+age+" "+rollno);
}
}
class derived extends Student1 {
public static void main(String[] args) {
Student1 obj= new Student1();
obj.name="Muditt";
obj.setage(17);
obj.setroll(9);
System.out.println(obj.name+" "+obj.getage()+" "+obj.getroll());
obj.print();
}
}
Algorithm:
1)Create a class Student1
Experiment-5 1
2)Make a String variable name
2) Write a program in Java to create a Player class. Inherit the classes Cricket
_Player, Football _Player and Hockey_ Player from Player class.
class Player {
String name;
int age;
Player(String n,int a) {
name=n; age=a;
}
void show() {
System.out.println("");
System.out.println("Player name : "+name);
System.out.println("Age : "+age);
}
}
class criket_player extends Player {
String type;
criket_player(String n,String t,int a) {
super(n,a);
type=t;
}
public void show() {
super.show();
System.out.println("Player type : "+type);
}
}
class football_player extends Player {
Experiment-5 2
String type;
football_player(String n,String t,int a) {
super(n,a);
type=t;
}
public void show() {
super.show();
System.out.println("Player type : "+type);
}
}
class hockey_player extends Player {
String type;
hockey_player(String n,String t,int a) {
super(n,a);
type=t;
}
public void show() {
super.show();
System.out.println("Player type : "+type);
}
}
class name {
public static void main(String args[]) {
criket_player c=new criket_player("Virat","Criket",36);
football_player f=new football_player("Ronaldo","Football",40);
hockey_player h=new hockey_player("Mandeep","Hockey",43);
c.show();
f.show();
h.show();
}
}
Algorithm:
1. Create a class Player
4. Create classes for cricket_player, football_player and hockey player and within them create functions that will show
the player type stored in the String variable type.
7. Create objects for cricket_player, football_player and hockey player classes and enter the values that will be displayed
Experiment-5 3
3) Write a class Worker and derive classes DailyWorker and SalariedWorker
from it. Every worker has a name and a salary rate. Write method ComPay
(int hours) to compute the week pay of every worker. A Daily Worker is paid
on the basis of the number of days he/she works. The Salaried Worker gets
paid the wage for 40 hours a week no matter what the actual hours are. Test
this program to calculate the pay of workers. You are expected to use the
concept of polymorphism to write this program.
class worker{
String empname;
worker (String s) {
empname=s;
}
void display() {
System.out.println("Employee name is:"+empname);
}
}
class dailyworker extends worker{
int salary_rate;
dailyworker(String name,int rate){
super(name);
salary_rate=rate;
}
void compay(int pay) {
super.display();
System.out.println( "Salary is:"+pay*salary_rate);
}
}
class salariedworker extends worker{
int salary_rate;
int pay=40;
salariedworker(String name,int rate){
super(name);
salary_rate=rate;
}
void compay() {
super.display();
System.out.println( "Salary is:"+pay*salary_rate);
}
}
class WorkerPay {
public static void main(String[] args) {
dailyworker obj1 = new dailyworker("amit",250);
salariedworker obj2 = new salariedworker("hari",300);
obj1.compay(60);
obj2.compay();
Algorithm:
1. Create a class worker
4. Create a class dailyworker and salariedworker and inherit the worker class
5. Create a parametrized constructor within those classes with parameters String name and int pay
6. Create a function compay with the first compay having parameter intpay, to calculate and display the salary
9. Create objects for dailyworker and salariedworker and input the values for their name and salary pay
Experiment-5 4
4) Consider the trunk calls of a telephone exchange. A trunk call can be
ordinary, urgent or lightning. The charges depend on the duration and the
type of the call. Write a program using the concept of polymorphism in Java
to calculate the charges.
class TrunkCall{
String type;
float duration;
TrunkCall( String type,float duration){
this.type=type;
this.duration=duration;
}
void display() {
System.out.println("Call type is "+type);
System.out.println("Call duration is "+duration);
}
}
class Normal extends TrunkCall{
float rate=2.0f;
Normal(String type,float duration){
super(type,duration);
}
float charges(){
return duration*rate;
}
void display() {
super.display();
System.out.println("total cost is:"+charges());
}
}
class Urgent extends TrunkCall{
float rate=3.5f;
Urgent(String type,float duration){
super(type,duration);
}
float charges(){
return duration*rate;
}
void display() {
super.display();
System.out.println("total cost is:"+charges());
} }
class Lightning extends TrunkCall{
float rate=4.5f;
Lightning(String type,float duration){
super(type,duration);
}
float charges(){
return duration*rate;
}
void display() {
super.display();
System.out.println("total cost is:"+charges());
}}
Experiment-5 5
class Call {
public static void main(String[] args) {
Normal obj1 =new Normal("normal",10.5f);
obj1.display();
Urgent obj2 =new Urgent("urgent",11.2f);
obj2.display();
Lightning obj3 =new Lightning("Lightning",8.4f);
obj3.display();
}
Algorithm:
1. Create a class TrunkCall
3. Create a function inside the variable to display the type and duration
4. Create a class Normal, Urgent and Lightning and inherit the properties of TrunkCall, set the value of the float variable
rate, create a float function chargest that returns duration * rate, create a function to display.
6. Create a main method and create objects for every class and display.
Experiment-5 6
Experiment-6
Class OOPs
Type Lab
AIM:
1. Write a program to create interface A, in this interface, we have two methods meth1 and meth2. Implements this interface in another class named MyClass.
3. Write a program to create an Interface having two methods divisions and modules. Create a class, which overrides these methods.
4. Write a program to create an interface named Test. In this interface, the member function is square. Implement this interface in the Arithmetic class. Create one new class called
ToTestInt. In this class use the object of Arithmetic class.
1) Write a program to create interface A, in this interface, we have two methods meth1 and meth2. Implements this
interface in another class named MyClass.
interface A
{
void meth1();
void meth2();
}
class Myclass implements A
{
public void meth1()
{
System.out.println("R2142210506");
}
Algorithm:
1) Make an interface A and declare meth1 and meth2 methods.
2) Create a class Myclass and implement interface A.
3) Add functionalities to methods meth1 and meth2
4) Create a class duointeface
5) Create main method
6) Create object obj and execute meth1 and meth2 with respect to obj.
Experiment-6 1
2) Implement Multiple and multilevel Inheritance using Interface.
interface A
{
public void sleep();
}
interface B
{
public void sleep();
public void wake_up();
}
Algorithm:
1. Create a interfaces A and B and declare method sleep in A and method sleep and method wake_up in B.
3. Describe the functionalities of both sleep and wake_up to be to print “ I slept” and “I woke up” respectively.
Experiment-6 2
3) Write a program to create an Interface having two methods divisions and modules. Create a class, which
overrides these methods.
interface modulus
{
void division(int a, int b);
void modulus(int x, int y);
}
class Interface_over
{
public static void main(String... args)
{
doub obj = new doub();
obj.division(5,20);
obj.modulus(30,4);
}
}
Algorithm:
1. Create an interface modulus and create the modulus and division method in it with parameters being x and y and a and b respectively.
3. Add the functionalities for the previously made method to find the modulus and division.
5. Create new obj for doub and then execute the modulus and division method.
Experiment-6 3
4) Write a program to create an interface named Test. In this interface, the member function is square. Implement
this interface in the Arithmetic class. Create one new class called ToTestInt. In this class use the object of
Arithmetic class.
interface test
{
public void square(int side);
class ToTestInt
{
public static void main(String... args)
{
Arithmetic square1= new Arithmetic();
square1.square(6);
}
}
Algorithm:
1. Create an interface test
2. Create a square function method with perimeters being the side of the square
3. Create an Arithmetic class and describe the functionalities of run method to be to print area and perimeter of square.
5. Create a new object for Arithmetic class and execute the method with side being 6.
Experiment-6 4
Experiment-6 5
Experiment-7
Class OOPs
Type Lab
AIM:
1. Write a Java program to implement the concept of importing classes from user-defined packages.
3. Write a java program that creates a package calculation. Add the following classes to it:
a. Addition
b. Subtraction
c. Multiplication
d. Division
Write another Test class, import, and use the above package.
package pkgOne;
public class pkg1
{
public void m1()
{
System.out.println("M1 in pkgOne");
}
}
import pkgOne.pkg1;
class pact
{
public static void main(String... args)
{
pkg1 obj = new pkg1();
obj.m1();
}
}
Algorithm:
1) Create a package named pkgOne, keep the file name pkg1.java & inside it create a public class pkg1.
2) Write a program to make a package Balance. This has an Account class with the Display_ Balance method. Import the
Balance package in another program to access the Display_ Balance method of the Account class.
3) Create another test class that would contain the main method, then import the package and call method m1( ).
Experiment-7 1
2) Write a program to make a package Balance. This has an Account class with the Display_ Balance method. Import the
Balance package in another program to access the Display_ Balance method of the Account class.
package Balance;
Experiment-7 2
public class Account
{
public void Display_Balance(){
System.out.println("Display Balance Method");
}
}
import Balance.Account;
class Show_acc
{
public static void main(String ...args)
{
Account obj = new Account();
obj.Display_Balance();
}
}
Algorithm:
1. Create a package balance, inside it create a file Account.java, inside that file create a public class Account and
method Display_Balance().
2. import Account class in another test java program and use Display_Balance function by creating an object of Account
class.
Experiment-7 3
3) Write a java program that creates a package calculation. Add the following
classes to it: Addition, Subtraction, Multiplication and Division. Write another
Test class, import, and use the above package.
import Calculation.calc;
import java.util.Scanner;
class calk
{
public static void main( String... args)
{
double a,b;
Scanner input = new Scanner(System.in);
Experiment-7 4
System.out.println("Subtraction : " +obj.Subtraction(a,b));
System.out.println("Multiplication : " +obj.Multiplication(a,b));
System.out.println("Division : " +obj.Division(a,b));
}
}
package Calculation;
public class calc
{
public double Addition(double a, double b)
{
return a + b;
}
Algorithm:
1. Create a package Calculation, inside that package create a public class calc, Inside calc class create 4 methods for
addition, division, subtraction and multiplication. Each method should take two arguments and return one value by
performing operation on those two arguments.
2. import the package in another file while also importing Scanner class and then create a class calk
4. take input and then for output use obj.addition, obj.subtraction, obj.multiplication & obj.division functions respectively
Experiment-7 5
Experiment-7 6
Experiment-7
Class OOPs
Type Lab
AIM:
1. Write a Java program to implement the concept of importing classes from user-defined packages.
3. Write a java program that creates a package calculation. Add the following classes to it:
a. Addition
b. Subtraction
c. Multiplication
d. Division
Write another Test class, import, and use the above package.
package pkgOne;
public class pkg1
{
public void m1()
{
System.out.println("M1 in pkgOne");
}
}
import pkgOne.pkg1;
class pact
{
public static void main(String... args)
{
pkg1 obj = new pkg1();
obj.m1();
}
}
Algorithm:
1) Create a package named pkgOne, keep the file name pkg1.java & inside it create a public class pkg1.
2) Write a program to make a package Balance. This has an Account class with the Display_ Balance method. Import the
Balance package in another program to access the Display_ Balance method of the Account class.
3) Create another test class that would contain the main method, then import the package and call method m1( ).
Experiment-7 1
2) Write a program to make a package Balance. This has an Account class with the Display_ Balance method. Import the
Balance package in another program to access the Display_ Balance method of the Account class.
package Balance;
Experiment-7 2
public class Account
{
public void Display_Balance(){
System.out.println("Display Balance Method");
}
}
import Balance.Account;
class Show_acc
{
public static void main(String ...args)
{
Account obj = new Account();
obj.Display_Balance();
}
}
Algorithm:
1. Create a package balance, inside it create a file Account.java, inside that file create a public class Account and
method Display_Balance().
2. import Account class in another test java program and use Display_Balance function by creating an object of Account
class.
Experiment-7 3
3) Write a java program that creates a package calculation. Add the following
classes to it: Addition, Subtraction, Multiplication and Division. Write another
Test class, import, and use the above package.
import Calculation.calc;
import java.util.Scanner;
class calk
{
public static void main( String... args)
{
double a,b;
Scanner input = new Scanner(System.in);
Experiment-7 4
System.out.println("Subtraction : " +obj.Subtraction(a,b));
System.out.println("Multiplication : " +obj.Multiplication(a,b));
System.out.println("Division : " +obj.Division(a,b));
}
}
package Calculation;
public class calc
{
public double Addition(double a, double b)
{
return a + b;
}
Algorithm:
1. Create a package Calculation, inside that package create a public class calc, Inside calc class create 4 methods for
addition, division, subtraction and multiplication. Each method should take two arguments and return one value by
performing operation on those two arguments.
2. import the package in another file while also importing Scanner class and then create a class calk
4. take input and then for output use obj.addition, obj.subtraction, obj.multiplication & obj.division functions respectively
Experiment-7 5
Experiment-7 6
Experiment-8
Class OOPs
Type Lab
AIM:
1. Write a program in Java to display the names and roll numbers of students. Initialize respective array variables for 10
students. Handle ArrayIndexOutOfBoundsExeption, so that any such problem doesn’t cause illegal termination of the
program.
2. Write a Java program to enable the user to handle any chance of dividing by zero exception.
3. Create an exception class, which throws an exception if the operand is non-numeric in calculating modules. (Use
command line arguments).
import java.util.*;
class ecepr{
public static void main(String [] args){
Student arr[] = new Student[5];
Scanner input = new Scanner(System.in);
try{
for(int i = 0 ;i<arr.length+1;i++){
input.nextLine();
System.out.print("\nName : ");
String name = input.nextLine();
System.out.print("Rollno : ");
int rollno = input.nextInt();
class Student{
String name;
int rollno;
Experiment-8 1
}
}
Algorithm:
1) Create a class student with 2 variables name and roll number and a constructor that initialize these variables.
2) create a class Q2 this class would contain the main driver method, create an array of length 10 of student class type.
3) use scanner object and a for loop to take input for the username and rollno. And store the details in the array.
4)put a try catch block around the for block and catch any exception that occurs and then execute the remaining code.
5) Print the stored students details on the console.
2) Write a Java program to enable the user to handle any chance of dividing
by zero exception.
import java.util.Scanner;
class bzer{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("a = ");
int a = input.nextInt();
System.out.print("b = ");
int b = input.nextInt();
int c=-1;
try{
c = a/b;
}catch(ArithmeticException e){
System.out.println("Exception caught : " + e.getClass().getName());
}finally{
System.out.println("a/c = "+c);
}
}
}
Algorithm:
1. Create a scanner object inside the main method to receive user input (2 numbers) and store it in variables a and b.
3. Include a try block around the division statement to handle the ArithmeticException by zero if b is zero.
Experiment-8 2
3) Create an exception class, which throws an exception if the operand is
non-numeric in calculating modules. (Use command line arguments).
class nncm{
public static void main(String [] args){
int a=-1,b=-1,c=-1;
if(args.length < 2){
System.out.println("Usage : nncm <numeric-operand1> <numeric-operand2>");
System.exit(0);
}
try{
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
}catch(NumberFormatException e){
System.out.println("Exception caught : " + e.getClass().getName());
System.out.println("Using default values : -1 ");
}
c = a % b;
System.out.println(" a % b = " + c);
}
}
Algorithm:
1. Take input from the user through the command line.
3. Place the aforementioned statement inside a try block and catch any exceptions that may arise.
Experiment-8 3
4) Write a java program to throw an exception for employee details. -: If an
employee’s name is a number, a name exception must be thrown. If an
employee’s age is greater than 50, an age exception must be thrown.
import java.util.Scanner;
class emexc{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Type employee name : " );
String emp_name = input.nextLine();
try{
for ( int c : emp_name.toCharArray()){
if ( c >= 48 && c<=57){
throw new Exception(" Numbers inside name not allowed ");
}
}}catch(Exception e){
System.out.println(e);
}
try{
if(age > 50)
throw new Exception(" Age greater than 50. ");
}catch(Exception e){
System.out.println(e);
}
}
}
Algorithm:
1. Request the user's input for the employee's name and age.
2. Convert the employee name into a char array, loop through the items, and throw an exception with the message that
numbers are not permitted inside the employee name if the character's ascii value is (c >= 48 && c=57).
3. Verify that the age of the employee, given by their name, is not greater than 50. If it is, throw an exception noting as
much.
Experiment-8 4
Experiment-8 5
Experiment-9
Class OOPs
Type Lab
AIM:
1. Write a program to implement the concept of multithreading by extending the Thread class.
3. Write a program for generating 2 threads, one for printing even numbers and the other forprinting odd numbers.
4. Write a Java program that implements multithreading among 3 threads. Use sleep() and join()methods and show
appropriate output.
5. Write a Java program that shows multithreading between three threads. Set differentpriorities for each thread and
show output.
Write a Java program that shows multithreading between three threads. Set differentpriorities for each thread and show
output.
Algorithm:
1)Create a class Mythread and extend it with Thread class.
2) Create a String called name
3) Create a method MyThread and add the string as an attribute
4) Create a method run with a for loop that will print the string name 10 times
5) Create the main method.
6) create 2 new objects for thread t1 and t2 and set the string name as First Thread and Second Thread respectively.
Experiment-9 1
2) Write a program to implement the concept of multithreading by
implementing a Runnableinterface.
Algorithm:
1. Create a class HelloRunnable and implement the Runnable Interface
Experiment-9 2
2. Create run method that will print Hello from Runnable 10 times.
4. Create a run method that will print Hello from a thread 10 times
6. Create new object for HelloThread class and use start function
7. Create new object for HelloRunnable class and use start function
8. Exit
3) Write a program for generating 2 threads, one for printing even numbers
and the other forprinting odd numbers.
Experiment-9 3
if(i%2 == 0)
System.out.println(t.getName() + " : " + i);
}else{
if(i%2 != 0)
System.out.println(t.getName() + " : " + i);
}
}
}
}
class q3{
public static void main(String [] args){
evenThread.t.start();
oddThread.t.start();
}
}
Algorithm:
1. Create a class threadGenerator and implement it with runnable interface
2. Create a thread t
5. Set t = new Thread and give the parameters as this and name
7. Create run method such that it will print odd thread if i is odd and even thread if i is even
9. Create the main method and create odd and even threads.
11. Exit
Experiment-9 4
4) Write a Java program that implements multithreading among 3 threads.
Use sleep() and join()methods and show appropriate output.
threadCreator(String name){
t = new Thread(this,name);
System.out.println(t.getName() + " created.");
}
class q4{
public static void main(String [] args){
System.out.println("thread created.");
Experiment-9 5
threadCreator T3 = new threadCreator("Thread-3");
T1.t.start();
try{
T1.t.join();
}catch(InterruptedException e){
System.out.println("interrupted.");
}
T2.t.start();
try{
T2.t.join();
}catch(InterruptedException e){
System.out.println("interrupted.");
}
T3.t.start();
try{
T3.t.join();
}catch(InterruptedException e){
System.out.println("interrupted.");
}
System.out.println("Exiting.");
Algorithm:
1. Create a class threadCreator and implement Runnable interface
2. Create a thread t
3. Create a constructor and set t = new thread with parameters this and name and write the print function to print (thread
name) created
4. Create a run function and use exception handling for interruptedexception e for a for loop that prints thread name with
i 3 times.
5. Create a class q4
6. Create main method and create 3 threads, thread 1, thread 2 and thread 3.
7. .start and use the exception handling for interruptedexception e for joining the thread.
8. exit
Experiment-9 6
5) Write a Java program that shows multithreading between
three threads. Set differentpriorities for each thread and show
output.
class threadCreator implements Runnable{
Thread t;
threadCreator(String name){
t = new Thread(this,name);
System.out.println(t.getName() + " created.");
}
Experiment-9 7
class q5{
public static void main(String [] args){
System.out.println("Setting priority");
T1.t.setPriority(1);
T2.t.setPriority(5);
T3.t.setPriority(8);
System.out.println(T1.t.getName() + " priority("+T1.t.getPriority()+")");
System.out.println(T2.t.getName() + " priority("+T2.t.getPriority()+")");
System.out.println(T3.t.getName() + " priority("+T3.t.getPriority()+")");
T1.t.start();
T2.t.start();
T3.t.start();
try{
T1.t.join();
T2.t.join();
T3.t.join();
}catch(InterruptedException e){
System.out.println("interrupted.");
}
System.out.println("Exiting.");
}
}
Algorithm:
1. Create a class threadCreator and implement Runnable interface with it
2. create a thread t
3. create a constructor threadCreator with Stringname as a perimeter and set t as new thread with this and name as
perimeters, also use the print function to print (thread name) created.
4. Create run method and use extension handling for interruptedexception e for a for loop that prints (thread name):i for
3 times
5. create class q5
9. use the start function to start the threads and use exception handling again while joining the threads for
interruptedexception e
Experiment-9 8
Experiment-9 9
Experiment - 10
Class OOPs
Type Lab
AIM:
1. Write a Java program using the following string methods:
String toUpperCase()
int hashCode()
String trim()
String intern()
int length()
3. Write a Java code that converts int to Integer, Integer to String, String to int, int to String, String to Integer, and Integer
to int.
4. Write a Java code that converts a float to Float, converts Float to String, converts String to Float converts Float to
float.
class Stiboo{
public static void main(String [] args){
String s1 = "void";
String s2 = s1.concat(" walker");
boolean r1 = s1.equals("Void");
boolean r2 = s2.equalsIgnoreCase("Void Walker");
System.out.println(s2.toUpperCase());
Experiment - 10 1
String sr1 = "Kgf";
String sr2 = "dbz";
String sr3 = "op";
System.out.println("Char at index[2] \"Kgf\" : " + sr1.charAt(2) );
System.out.println(sr1.compareTo(sr1));
System.out.println(sr1.compareTo(sr2));
System.out.println(sr1.compareTo(sr3));
Algorithm:
1) Create a string s1 and s2 then call concat method using s1 and store the result in s2.
2)Create two boolean variables r1 and r2 then use equals() and equalsIgnoreCase() to match two strings.
3) Print the value of s1, s2 and r1 and r2.
4) Call the toUpperCase method using s2 string object and print the value using println() method.
5) Create three new strings and compare the first with itself then with the second one and then with the third one using the
String.compareTo() method and then print the result.
2) Write a Java program using the following string methods: int hashCode(),
String trim(), String intern(), int length(), String replace(char oldChar, char
newChar) String substring(int beginIndex, int endIndex)
}
}
Algorithm:
1. Create an object of the current class obj1 , and Integer object obj2 and a String object obj3 then call
Object.hashCode() function on all these objects to print their hash codes/values.
2. Create a string with leading and trailing whitespaces and use String.trim() method to remove that whitespace.
Experiment - 10 2
3. Create a string object s1 then create string s2 and use s1.intern() method to initialize the s2 String
4. Use the println() method to print the values of the strings and then
5. Use the .length() and .replace() and .substring() method on the previously created strings and print the values.
3) Write a Java code that converts int to Integer, Integer to String, String to
int, int to String, String to Integer, and Integer to int.
class Stint{
public static void main(String [] args){
}
}
Algorithm:
1. use the Integer.valueOf(int) to convert from int to Integer
4) Write a Java code that converts a float to Float, converts Float to String,
converts String to Float converts Float to float.
Experiment - 10 3
import java.util.Scanner;
class Flint{
public static void main(String [] args){
float j = input.nextFloat();
Float k = j;
String l = String.valueOf(k);
Float m = Float.parseFloat(l);
float n = m;
Algorithm:
1. use String.valueOf(k) to convert Float k to String l.
3. for converting Float m to float n simply assign the Float data to float
variable
Experiment - 10 4
Experiment - 11
Class OOPs
Type Lab
AIM:
1. Show the steps of MYSQL Installation and start the MYSQL Server and MYSQL client.
2. Create a database table to store company employees’ records. Use the getConnection function to connect the
database. The statement object uses the executeUpdate function to create a table.
3. Create a database of company employees in MySQL and then use the java program to access the database to insert
information about employees. The SQL statement can be used to view the details of the data of employees in the
database.
1) Show the steps of MYSQL Installation and start the MYSQL Server and
MYSQL client
Download the jconnector and set the classpath variable in .zshrc or .bashrc file.
jconnector : https://dev.mysql.com/downloads/connector/j/?os=26
Experiment - 11 1
Create a database mydb
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;
class employ{
public static void main(String [] args){
try{
// load the driver class
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
// obtain a connection
String url = "jdbc:mysql://localhost:3306/mydb";
Connection conn = DriverManager.getConnection(url,"void","void");
// obtain a statement
Statement stmt = conn.createStatement();
// make queires
String query0 = "Create table empldata("
+"name varchar(100),"
+"city varchar(100),"
+"salary long"
+");";
String query1 = "Insert into empldata values(\"Blake\",\"New YORK\",99999)";
String query2 = "Insert into empldata values(\"Crisp\",\"New YORK\",100000)";
// execute queires
System.out.println("Creating table and executing queries ");
int rows_affected = 0 ;
rows_affected += stmt.executeUpdate(query0);
rows_affected += stmt.executeUpdate(query1);
rows_affected += stmt.executeUpdate(query2);
}catch(Exception e){
System.out.println(e);
}
}
}
OUTPUT:
Experiment - 11 2
Experiment - 11 3