You are on page 1of 63

Experiment - 1

Class OOPs

Type Lab

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

Introduction to Java
1. Installation of Oracle JDK

2. Introduction to Java IDEs

Installation of JDK on Linux

1. Press Ctrl+Shift+T to open the terminal or click on the terminal icon in the applications menu.

2. Type sudo apt install default-jdk and press Enter.

Experiment - 1 1
3. Check the versions of java and javac in the terminal by typing java —version and javac —version, respectively.

4. The JDK is installed, so now you can close the terminal.

Introduction to Java IDEs


The Java IDE (Integrated Development Environment) is a software application that simplifies the writing and debugging of
Java programs. Syntax highlighting and code completion are standard coding aids in most integrated development
environments (IDEs). Typical Java IDEs provide access to a code editor, compiler, debugger, and interpreter via a single
graphical user interface. Java IDEs also feature language-specific elements for testing, including Maven, Ant building
tools, Junit, and TestNG.

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.

JDeveloper: Supported by Oracle Corporation, a free and open-source Java IDE.

Experiment - 1 3
Experiment - 2
Class OOPs

Type Lab

Name: Muditt Sharmma


Rollno.: R2142210506
SAP ID: 500091725

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)

3. Write a program to find the largest of the 3 numbers.

4. Write a program to find the sum of all integers.

1) Write and execute my first java program


Algorithm:
1) Create a class named first
2) Create the main method
3) Print the contents in using the print command

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

2. Create the main method

3. Print the contents required to be printed using the print commands

4. Create two variables a and b

5. Print the two variables using print command

6. Run a loop for 10 times where c=a+b and a=b, b=c

7. Print the value of c

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);
}

}
}

3) Write a program to find the largest of the 3 numbers.


Algorithm:
1. Create a class First3

2. Create the main method

Experiment - 2 2
3. Print the contents required to be printed using print commands

4. Create 3 variables i,j,k and assign values to them

5. If i>j and i>k, print the biggest number is i

6. If j>k and j>i, print the biggest number is j

7. If k>i and k>j print the biggest number is k

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");
}
}
}

4) Write a program to find the sum of all integers.


Algorithm:
1. Create class First5

2. Create main method

3. Print the contents required to be printed using print command

4. Create an int variable sum and set its value to 0

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

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).

2. Write a program to add two numbers using command line arguments.

3. Write a program to implement a command line calculator.

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");

Scanner input = new Scanner(System.in);

System.out.print("Enter the number for the month: ");


int i = input.nextInt();

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.

2) Write a program to add two numbers using command line arguments.

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

2. Create up with the main way

3. Create two variables called "a" and "b."

4. Change the string variables to double variables.

5. Give c the value that is equal to the sum of a and b.

Experiment - 3 2
6. Print the output

3) Write a program to implement a command line calculator.

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;

System.out.println("the sum of the no is:"+Sum);


System.out.println("the subtraction of the no is:"+Dif);
System.out.println("the Multiplication of the no is:"+Prod);
System.out.println("the Division of the no is:"+Quoet);
System.out.println("the Remainder of the no is:"+Rem);

}
}

Algorithm:
1. Create a class calculator

2. Create the main method

3. Create create 7 double data-type variables a,b,Sum,Dif, Prod, Quoet, Rem

4. Convert the string input from the user to double

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

10. Print Sum, Dif, Prod, Quoet, Rem

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;

public static void main(String[] args){


System.out.println("Name: Muditt Sharmma, Sap ID : 500091725, Roll no. : R2142210506");
input = new Scanner(System.in);
setinfo();
getinfo();
}

public static void setinfo(){


System.out.println("Name:");
Name=input.next();
System.out.println("Roll no:");
Rollno=input.nextInt();
System.out.println("Branch:");
Branch=input.next();
}

public static void getinfo(){


System.out.println("Student Details:");
System.out.println("Name:"+Name);
System.out.println("Roll no:"+Rollno);
System.out.println("Branch:"+Branch);
}
}

Algorithm:
1. Load the java.util.* module.

2. Create a class called StudentRec.

3. Create a string variable named Name that is static.

4. Create a static int variable Rollno

5. Create a string variable Branch

6. Create a static scanner, input

Experiment - 3 4
7. Create up with the main way

8. Print the required parts

9. Create a new scanner instance, enter

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

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.

3. Write a JAVA program to implement compile time polymorphism.

4. Write a JAVA program to implement type promotion in method overloading.

5. Write a JAVA program to implement constructor overloading.

1) Write a JAVA program to implement class mechanism. – Create a class,


define datamembers, methods (setData(args) ,getData()) and invoke them
inside main method.

import java.util.*;
class Sleep{
static String Sleptat;
static String Wokeupat;
static Scanner input;

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();
}

public static void setinfo(){


System.out.println("Slept at:");
Sleptat=input.next();
System.out.println("Woke up at:");
Wokeupat=input.next();
}

public static void getinfo(){


System.out.println("Slept From:"+Sleptat);
System.out.println("Till:"+Wokeupat);
}
}

Experiment - 4 1
Algorithm:
1. Import all the modules from java util library.

2. create a class Sleep

3. create two string variables, Sleptat, Wokeupat.

4. create a Scanner input.

5. create the main method.

6. create a new instance for scanner using new.

7. call the setinfo() and getinfo() methods in it.

8. create the setinfo() method.

9. take input from the user.

10. create the getinfo() method.

11. show the input taken from the user.

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 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();
}

public static void setinfo(){


System.out.println("Name:");
Name=input.next();
System.out.println("Roll no:");
Rollno=input.nextInt();
System.out.println("Branch:");
Branch=input.next();
System.out.println("Physics Percentage:");
PhysicsPer=input.nextInt();
System.out.println("Chemistry Percentage:");
ChemistryPer=input.nextInt();
System.out.println("Maths Percentage:");
MathsPer=input.nextInt();
System.out.println("");
}

public static void getinfo(){


System.out.println("Student Details:");
System.out.println("Name:"+Name);
System.out.println("Roll no:"+Rollno);
System.out.println("Branch:"+Branch);
System.out.println("");
}

public static void sorted(){


System.out.println("Physics Percentage:"+PhysicsPer);
if(PhysicsPer<100 && PhysicsPer<40){
System.out.println("You failed in physics");
}
else if(PhysicsPer<100 && PhysicsPer>75){
System.out.println("You scored a distinction in physics");
}
else if(PhysicsPer<100 && PhysicsPer>=40){
System.out.println("You passed");
}
else{
System.out.println("INVALID");
}
System.out.println("");

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

2. create a class StudentMarks

3. create the required variables like Name, Roll no, Branch, and marks.

4. create the scanner input

5. create the main method

6. create a new instance for scanner using new

7. call the setinfo(), getinfo() and sorted() methods in it.

8. create the setinfo() method.

9. take input from the user

10. create the getinfo() method

11. show the user input

12. create the sorted method

13. check the conditions for passing, distinction, first division, second division and third division and show the result
accordingly

3) Write a JAVA program to implement compile time polymorphism.

public class Polymorphism {


static void sum(int a, int b)
{
System.out.println("Sum of the integers: "+(a+b));
}
static void sum(double a, double b)

Experiment - 4 4
{
System.out.println("Sum of the doubles: "+(a+b));
}

public static void main(String[] args)


{
sum(1, 2);

sum(1.2, 2.4);
}
}

Algorithm:
1. create a class called Polymorphism

2. create sum function with parameters int a and int b

3. print the sum of integers a and b

4. create sum functions with parameters double a and double b

5. print the sum of double a and double b

4)Write a JAVA program to implement type promotion in method overloading.

public class TypePromotion{


static double sum(int num1, int num2) {
double s = 0;
s = num1 + num2;
return s;
}

static double sum(int num1, double num2) {


double s = 0;
s = num1 + num2;
return s;
}

public static void main(String[] args) {


double result = 0;

result = sum(10, 20);


System.out.println("Sum : " + result);

result = sum(20, 20.56F);


System.out.println("Sum : " + result);
}
}

Experiment - 4 5
Algorithm:
1. Create a class TypePromotion

2. Create a sum function with parameters as int num1 and int num2

3. create a double variable s with initial value 0

4. let s = num1 + num2

5. return s

6. Create main method

7. create a double variable result with initial value 0

8. result = sum(10,20)

9. show result

10. result = sum(20,20.56F)

11. show result

5) Write a JAVA program to implement constructor overloading.

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

2. create a Rupee method

3. create a private integer variable Rupee

4. create a default constructor ConstructorOverloading()

5. set Rupee to 49

6. create a parameterized constructor ConstructorOverloading with parameters int r

7. call the default constructor from parameterised constructor using this()

8. set Rupee=Rupee+r

9. create the getRupee() method

10. return Rupee

11. create the setRupee() method

12. set this.Rupee as Rupee

13. create the main method

14. create obj as the new instance for ConstructorOverloading() and pass 12 as the value of r in the parenthesis

15. show the final Rupee value

Experiment - 4 7
Experiment-5
Class OOPs

Type Lab

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

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

3) Make private int variables age and rollno


4) Create a setage() function to set the age

5) Create a getage() function to get the age


6) Similarly create functions for rollno

7) Create a function to display


8) Create a class derived and inherit the properties of Student1 in it

9) Create the main method


10) Create a new object obj from Student1

11) Set the values of age and rollno


12) Set the name to Akshat

13) Use the print function to display

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

2. Create a parametrized constructor Player with parameters String n and int a

3. Create a function to display name and age of the 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.

5. Create a class name

6. Create the main method

7. Create objects for cricket_player, football_player and hockey player classes and enter the values that will be displayed

8. Display the output

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

2. Create a String variable empname which will store Employee Name

3. Create a void function to display the employee name

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

7. Create a WorkerPay class

8. Create the main method

9. Create objects for dailyworker and salariedworker and input the values for their name and salary pay

10. Display using compay

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

2. Create a String variable type and float variable duration

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.

5. Create a class Call

6. Create a main method and create objects for every class and display.

Experiment-5 6
Experiment-6
Class OOPs

Type Lab

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725

Branch: Btech. CSE spl (CSF)

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.

2. Implement Multiple and multilevel Inheritance using Interface.

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");
}

public void meth2()


{
System.out.println("Muditt Sharmma");
}
}
class duointerface
{
public static void main(String... args)
{
Faces obj = new Faces();
obj.meth1();
obj.meth2();
}
}

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();
}

class m_level implements A,B


{
public void sleep()
{
System.out.println(" I slept ");
}

public void wake_up()


{
System.out.println("I woke up");
}

public static void main (String... args)


{
m_level obj = new m_level();
obj.sleep();
obj.wake_up();
}
}tu

Algorithm:
1. Create a interfaces A and B and declare method sleep in A and method sleep and method wake_up in B.

2. Create a class m_level and it implements interfaces A and B

3. Describe the functionalities of both sleep and wake_up to be to print “ I slept” and “I woke up” respectively.

4. Create the main function.

5. Create a new object obj

6. Execute the sleep and wake_up method with respect to obj

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 doub implements modulus


{
public void modulus(int y, int z)
{
System.out.println(" The modulus: " + y%z);
}

public void division(int a, int b)


{
System.out.println(" the division:" + (b/a));
}
}

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.

2. Create a class doub and implement modulus

3. Add the functionalities for the previously made method to find the modulus and division.

4. Create class Interface_over and create main method

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 Arithmetic implements test


{
public void square(int side)
{
System.out.println("Square of side" + side + "created");
System.out.println("Area of square: " + (side*side));
System.out.println("Perimeter of sqaure:" +(side*4));
}
}

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.

4. Create a class ToTestInt and create a main method.

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

AIM:
1. Write a Java program to implement the concept of importing classes from user-defined packages.

2. Write a program to add two numbers using command line arguments.

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.

1) Write a Java program to implement the concept of importing classes from


user-defined packages.

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);

calc obj = new calc();


System.out.println("Type the values, a and b");
System.out.print("a = ");
a = input.nextDouble();
System.out.print("b =");
b = input.nextDouble();
System.out.println("Addition : " +obj.Addition(a,b));

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;
}

public double Subtraction(double a, double b)


{
return a-b;
}

public double Multiplication(double a, double b)


{
return a*b;
}

public double Division(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

3. create an object obj for class calc

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

AIM:
1. Write a Java program to implement the concept of importing classes from user-defined packages.

2. Write a program to add two numbers using command line arguments.

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.

1) Write a Java program to implement the concept of importing classes from


user-defined packages.

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);

calc obj = new calc();


System.out.println("Type the values, a and b");
System.out.print("a = ");
a = input.nextDouble();
System.out.print("b =");
b = input.nextDouble();
System.out.println("Addition : " +obj.Addition(a,b));

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;
}

public double Subtraction(double a, double b)


{
return a-b;
}

public double Multiplication(double a, double b)


{
return a*b;
}

public double Division(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

3. create an object obj for class calc

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

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).

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.

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.

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();

arr[i] = new Student(name,rollno);


}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception caught : "+e.getClass().getName());
}

System.out.println("\nStudent Details Stored " );


for(int i = 0 ;i<arr.length;i++){
System.out.println("Name = " + arr[i].name);
System.out.println("Roll no = " + arr[i].rollno);
}
}
}

class Student{
String name;
int rollno;

Student(String name , int roll){


this.name = name;
this.rollno = roll;

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.

2. Make a second variable, c, and put a/b in c.

3. Include a try block around the division statement to handle the ArithmeticException by zero if b is zero.

4. If an exception occurs, display c's -1 default value.

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.

2. perform the modulus operator by converting the string to an integer.

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);
}

System.out.print("Type employee age : ");


int age = input.nextInt();

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.

4. Run the remaining code.

Experiment-8 4
Experiment-8 5
Experiment-9
Class OOPs

Type Lab

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

AIM:
1. Write a program to implement the concept of multithreading by extending the Thread class.

2. Write a program to implement the concept of multithreading by implementing a Runnableinterface.

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.

1)Write a program to implement the concept of multithreading by extending


the Thread class.

class MyThread extends Thread {


String name;

public MyThread(String name) {


this.name = name;
}

public void run() {


for (int i=0;i<10 ;i++) {
System.out.println(name);
}
}

public static void main(String[] args) {


Thread t1 = new MyThread("First Thread");
Thread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}

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.

7) Use the start functions with both t1 and t2


8) End

Experiment-9 1
2) Write a program to implement the concept of multithreading by
implementing a Runnableinterface.

class HelloRunnable implements Runnable{


public void run() {
for(int i=0;i<10;i++){
System.out.println("Hello from Runnable!");
}
}
}
class HelloThread extends Thread {
int j=0;
public void run() {
for(int j=0; j<10 ; j++) {

System.out.println("Hello from a thread!");


}
}

public static void main(String args[]) {


(new HelloThread()).start();
(new Thread(new HelloRunnable())).start();
}
}

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.

3. Create a class HelloThread and extend Thread

4. Create a run method that will print Hello from a thread 10 times

5. Create main method

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.

class threadGenerator implements Runnable{


Thread t;
String odd_or_even;

threadGenerator(String name, String o_or_e){


t = new Thread(this,name);
odd_or_even = o_or_e;
}

public void run(){


for(int i = 1 ; i < 10 ;i++){
if(odd_or_even.startsWith("even")){

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){

threadGenerator evenThread = new threadGenerator("Even-Thread" , "even");


threadGenerator oddThread = new threadGenerator("Odd-Thread", "odd");

evenThread.t.start();
oddThread.t.start();

}
}

Algorithm:
1. Create a class threadGenerator and implement it with runnable interface

2. Create a thread t

3. Create a String odd_or_even

4. Create a constructor threadGenerator with parameters String name, String o_or_e

5. Set t = new Thread and give the parameters as this and name

6. Set odd_or_even as o_or_e

7. Create run method such that it will print odd thread if i is odd and even thread if i is even

8. Create the q3 class

9. Create the main method and create odd and even threads.

10. Use the start method.

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.

class threadCreator implements Runnable{


Thread t;

threadCreator(String name){
t = new Thread(this,name);
System.out.println(t.getName() + " created.");
}

public void run(){


try{
for(int i = 3 ; i > 0 ;i--){
System.out.println("[+] "+ t.getName() + " : " + i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println(t.getName()+" interrupted.");
}
System.out.println("Exiting " + t.getName());
}
}

class q4{
public static void main(String [] args){

System.out.println("thread created.");

threadCreator T1 = new threadCreator("Thread-1");


threadCreator T2 = new threadCreator("Thread-2");

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.");
}

public void run(){


try{
for(int i = 3 ; i > 0 ;i--){
System.out.println(t.getName() + " : " + i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println(t.getName()+" interrupted.");
}
System.out.println("Exiting " + t.getName());
}
}

Experiment-9 7
class q5{
public static void main(String [] args){

System.out.println("Main thread created.");

threadCreator T1 = new threadCreator("Thread-1");


threadCreator T2 = new threadCreator("Thread-2");
threadCreator T3 = new threadCreator("Thread-3");

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

6. Create main method

7. Create three threads t1 t2 t3

8. set priority for them using setPriority function

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

AIM:
1. Write a Java program using the following string methods:

String concat(String str)

boolean equals(Object anObject)

boolean equalsIgnoreCase(String anotherString)

String toUpperCase()

char charAt(int index)

int compareTo(String anotherString)

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)

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.

1) Write a Java program using the following string methods: String


concat(String str), boolean equals(Object anObject), boolean
equalsIgnoreCase(String anotherString), String toUpperCase(), char
charAt(int index), int compareTo(String anotherString)

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("s1 = " + s1);


System.out.println("s2 = " + s2);

System.out.println("s1.equals(\"void \" =>" + r1 );


System.out.println("s1.equalsIgnoreCase(\"Void Walker\" => "+r2 );

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)

public static void main(String [] args){

Stiboo2 obj1 = new Stiboo2();


Integer obj2 = Integer.valueOf(50);
String obj3 = "hell";
String s = " will sleep just well ";
String s1 = new String("hell");
String s2 = s1.intern();
String s3 = "hell";
System.out.println("Hash code- Stiboo object : "+ obj1.hashCode());
System.out.println("hash code-50 int : " +obj2.hashCode());
System.out.println("Hash code-\"hello\" string: " + obj3.hashCode());
System.out.println("String with whitespaces-" + s + "- Length = " + s.length());

System.out.println("String(trimmed whitespaces)-"+ s.trim() +"-");

System.out.println("Original string-" + obj3 +"\n ll replaced with jj - "+ obj3.replace("ll","jj"));


System.out.println(s1==s2);
System.out.println(s2==s3);
System.out.println("s3.substring(2,4)- " + s3.substring(1,3));

}
}

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){

Scanner input = new Scanner(System.in);


System.out.print(" Write an integer : " );
int j = input.nextInt();
Integer k = Integer.valueOf(j);
String l = k.toString();
int m = Integer.parseInt(l);
String n = String.valueOf(m);
Integer o = Integer.parseInt(n);
int p = o;

System.out.println(" int : " + j );


System.out.println(" Integer : " + k );
System.out.println(" String : " + l);
System.out.println(" int : " + m );
System.out.println(" String : " + n );
System.out.println(" Integer : " + o);
System.out.println(" int : " + p);

}
}

Algorithm:
1. use the Integer.valueOf(int) to convert from int to Integer

2. use IntegerObj.toString() to convert Integer to String

3. use parseInt(str_obj) method to convert String 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){

Scanner input = new Scanner(System.in);

System.out.print("Write a float input : " );

float j = input.nextFloat();

Float k = j;
String l = String.valueOf(k);
Float m = Float.parseFloat(l);
float n = m;

System.out.println(" float j : " + j);


System.out.println(" Float k : " + k);
System.out.println(" String l : " + l);
System.out.println(" Float m : " + m);
System.out.println(" float n : " + n);
}
}

Algorithm:
1. use String.valueOf(k) to convert Float k to String l.

2. use Float.parseFloat(l) to convert String l to float m.

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

Name: Muditt Sharmma


Roll No.: R2142210506
SAP ID: 500091725
Branch: Btech. CSE spl (CSF)

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

sudo apt-get install mysql-server && sudo apt-get install mysql-client$

sudo service mysql start && sudo service mysql status

Create a new user and grant permissions :

create user 'void'@'localhost' identified by 'void';

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

CREATE DATABASE mydb;

create a file employ.java which will be connected by 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);

System.out.println(rows_affected+" rows affected.");

}catch(Exception e){
System.out.println(e);
}
}
}

OUTPUT:

Experiment - 11 2
Experiment - 11 3

You might also like