0% found this document useful (0 votes)
0 views55 pages

First Year Java Lab

The document provides a series of Java programming exercises aimed at first-year students, covering basic concepts such as class creation, variable declaration, array manipulation, and operator usage. It includes examples of Java programs for printing messages, solving quadratic equations, multiplying arrays, sorting elements, creating student objects, demonstrating polymorphism, and implementing inheritance. Each example is accompanied by code snippets and expected outputs to illustrate the functionality of the programs.

Uploaded by

praveenlk41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views55 pages

First Year Java Lab

The document provides a series of Java programming exercises aimed at first-year students, covering basic concepts such as class creation, variable declaration, array manipulation, and operator usage. It includes examples of Java programs for printing messages, solving quadratic equations, multiplying arrays, sorting elements, creating student objects, demonstrating polymorphism, and implementing inheritance. Each example is accompanied by code snippets and expected outputs to illustrate the functionality of the programs.

Uploaded by

praveenlk41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

First Year Java lab

Prof. Jagdeesh Patil S, I.E.S,


M.E IISc Bangalore
Former Senior VP CISCO Systems (USA)
HOD Department of ISE
class FirstExample
{

public static void main(String args[])


{
System.out.println("This is a simple Java program for First year Students.");
}
}

//The name of the class defined by the program is also FirstExample


//By convention, the name of that class should match the name of the file that holds the program.

Compilation Command
F:\Java>javac FirstExample3.java
Run Command
F:\Java>java FirstExample3
This is a simple Java program for First year Students.
class Example2
{
public static void main(String args[])
{
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
Result:
This is num: 100
The value of num * 2 is 200
//Exp1: Quadratic Equation
//Question Write a JAVA program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c
and //use the quadratic formula.
import java.util.Scanner;
public class QuadraticEquationDemo
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.print("Enter a: ");
double a = input.nextDouble();

System.out.print("Enter b: ");
double b = input.nextDouble();

System.out.print("Enter c: ");
double c = input.nextDouble();

double discriminant = b * b - 4 * a * c;
if (discriminant > 0)
{
System.out.println("The equation has real and distinct roots.");
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
else if (discriminant == 0)
{
System.out.println("The equation has real and equal roots.");
double root = -b / (2 * a);
System.out.println("The root is " + root);
}
else
{
System.out.println("The equation has no real roots.");
double realp = -b / (2 * a);
double imagp = (Math.sqrt(-discriminant)) / (2 * a);
System.out.printf("The roots are (%.2f + i%.4f) and (%.2f - i%.4f)\n",realp, imagp, realp, imagp);
}
Result:

F:\Java>java QuadraticEquationDemo
Enter a: 2
Enter b: 3
Enter c: 4
The equation has no real roots.
The roots are (-0.75 + i1.1990) and (-0.75 - i1.1990)
//Exp1: Array Multiplication
//Question Write a JAVA program for multiplication of two arrays.
import java.util.Scanner;
import java.util.Arrays;

public class MultiplyArraysDemo


{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of elements in the first array: ");
int n = input.nextInt();
int[] array1 = new int[n];
for (int i = 0; i < n; i++)
{
System.out.print("Enter element " + (i+1) + " of the first array: ");
array1[i] = input.nextInt();
System.out.print("Enter the number of elements in the second array: ");
int m = input.nextInt();
int[] array2 = new int[m];
for (int i = 0; i < m; i++)
{
System.out.print("Enter element " + (i+1) + " of the second array: ");
array2[i] = input.nextInt();
}

if (n != m)
{
System.out.println("Error: Arrays have different length, not possible to multiply them.");
return;
}

int[] result = new int[n];


for (int i = 0; i < n; i++)
{
result[i] = array1[i] * array2[i];
}

System.out.println("Result of multiplying arrays: " + Arrays.toString(result));


Result:

F:\Java>java MultiplyArraysDemo
Enter the number of elements in the first array: 2
Enter element 1 of the first array: 1
Enter element 2 of the first array: 2
Enter the number of elements in the second array: 2
Enter element 1 of the second array: 3
Enter element 2 of the second array: 4
Result of multiplying arrays: [3, 8]
Exp3:Question Demonstrate the following operations and sign extension with Java programs
i) ≪
ii) ≫
iii) ⋙
import java.util.Scanner;

class OperatorDemoSignExtension {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.print("\nLeft Shift Operator\nEnter a number : ");


int num = sc.nextInt();
System.out.print("Enter the number of positions for the Left Shift Operation : ");
int pos = sc.nextInt();
int res = num << pos;
System.out.println("\nResult of Left Shift Operation");
System.out.printf("\n%d << %d = %d\n", num, pos, res);

System.out.print("\nRight Shift Operator\nEnter a number : ");


num = sc.nextInt();
System.out.print("Enter the number of positions for the Right Shift Operation : ");
pos = sc.nextInt();

res = num >> pos;


System.out.println("\nResult of Right Shift Operation");
System.out.printf("\n%d >> %d = %d\n", num, pos, res);
if(num < 0)
{
System.out.println("We observe that Even after the Right Shift operation the sign bit of negative number is preserved. sign extension.");
}
System.out.print("\nUnsigned Right Shift Operator\nEnter a number : ");
num = sc.nextInt();
System.out.print("Enter the number of positions for the Unsigned Right Shift Operation : ");
pos = sc.nextInt();

res = num >>> pos;


System.out.println("\nResult of Unsigned Right Shift Operation");
System.out.printf("\n%d >>> %d = %d\n", num, pos, res);
}
F:\Java>java OperatorDemoSignExtension

Left Shift Operator


Enter a number : 16
Enter the number of positions for the Left Shift Operation : 2

Result of Left Shift Operation

16 << 2 = 64

Right Shift Operator


Enter a number : 16
Enter the number of positions for the Right Shift Operation : 2

Result of Right Shift Operation

16 >> 2 = 4

Unsigned Right Shift Operator


Enter a number : 16
Enter the number of positions for the Unsigned Right Shift Operation : 2
Exp4: Question Write a JAVA program to sort list of elements in ascending and
descending order.
import java.util.Scanner;

public class ExchangeSortDemo1


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in the array: ");
int n = sc.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements of the array: ");


for (int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println("\nSorted array in ascending order: ");


for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] < arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println("\nSorted array in descending order: ");


for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}

}
}
Result:
F:\Java>javac ExchangeSortDemo1.java

F:\Java>java ExchangeSortDemo1
Enter the number of elements in the array:
4
Enter the elements of the array:
6
1
90
43

Sorted array in ascending order:


1 6 43 90
Sorted array in descending order:
90 43 6 1
Ex5: Create a JAVA class called Student with the following details as
variables within it.
USN
NAME
BRANCH
PHONE
PERCENTAGE
Write a JAVA program to create n Student objects and print the USN,
Name, Branch, Phone, and
percentage of these objects with suitable headings.
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

class StudentType
{
private String USN;
private String NAME;
private String BRANCH;
private String PHONE;
private double PERCENTAGE;

public StudentType(String USN, String NAME, String BRANCH, String PHONE, double
PERCENTAGE)
{
this.USN = USN;
this.NAME = NAME;
this.BRANCH = BRANCH;
this.PHONE = PHONE;
this.PERCENTAGE = PERCENTAGE;
public String getUSN()
{
return USN;
}

public String getNAME()


{
return NAME;
}

public String getBRANCH()


{
return BRANCH;
}

public String getPHONE()


{
return PHONE;
}

public double getPERCENTAGE()


{
return PERCENTAGE;
}
}
public class StudentDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
List<StudentType> students = new ArrayList<>();

System.out.println("Enter the number of students:");


int n = sc.nextInt();

for (int i = 1; i <= n; i++)


{
System.out.println("Enter the details of student " + i + ":");
System.out.print("USN: ");
String USN = sc.next();
System.out.print("NAME: ");
String NAME = sc.next();
System.out.print("BRANCH: ");
String BRANCH = sc.next();
System.out.print("PHONE: ");
String PHONE = sc.next();
System.out.print("PERCENTAGE: ");
double PERCENTAGE = sc.nextDouble();

students.add(new StudentType(USN, NAME, BRANCH, PHONE, PERCENTAGE));


}
System.out.println("\nSTUDENT DETAILS\n=====================");
System.out.println("USN" + "\t\t" + "NAME" + "\t" + "BRANCH" + "\t" + "PHONE" + "\t\t" +
"PERCENTAGE");
for (StudentType student : students)
{
System.out.println(student.getUSN() + "\t" + student.getNAME() + "\t" +
student.getBRANCH() +"\t" + student.getPHONE() + "\t" + student.getPERCENTAGE());
}
}
}
F:\Java>java StudentDemo
Enter the number of students:
3
Enter the details of student 1:
USN: tyr456
NAME: jag
BRANCH: ec
PHONE: 7685468
PERCENTAGE: 49
Enter the details of student 2:
USN: iuyrefhj7
NAME: jkodr
BRANCH: cse
PHONE: 908654
PERCENTAGE: 67
Enter the details of student 3:
USN: 9jhgfrtys
NAME: kloitr
BRANCH: ise
PHONE: 098765
PERCENTAGE: 09

STUDENT DETAILS
=====================
USN NAME BRANCH PHONE PERCENTAGE
tyr456 jag ec 7685468 49.0
iuyrefhj7 jkodr cse 908654 67.0
9jhgfrtys kloitr ise 098765 9.0
Ex6: Polymorphism - Method Overloading: Write a JAVA program demonstrating
Method overloading and Constructor overloading.
class PointType
{
private double x;
private double y;

// Constructor overloading
public PointType()
{
this.x = 0;
this.y = 0;
}

public PointType(double x, double y)


{
this.x = x;
this.y = y;
}
// Method overloading to calculate distance between two PointType objects
public double distance(PointType point)
{
System.out.println("\nCalculating distance between two PointType objects");
return Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2));
}

// Method overloading to calculate distance between a PointType object and a


//int specified by its coordinates
public double distance(double x, double y)
{
System.out.println("Calculating distance between a PointType object and int specified by its coordinates");
return Math.sqrt(Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2));
}

public void show()


{
System.out.printf("(%.1g,%.1g)\n",x,y);
}
}
class PointDemo
{
public static void main(String[] args)
{
PointType point1 = new PointType(1, 1);
PointType point2 = new PointType(7, 9);
System.out.print("\npoint1 coordinates :");
point1.show();
System.out.print("point2 coordinates :");
point2.show();
double dVal = point1.distance(point2);
System.out.println("Distance between point1 and point2: " + dVal );

PointType point3 = new PointType();


System.out.print("\npoint3 coordinates :");
point3.show();
dVal = point3.distance(3,4);
System.out.println("Distance between point3 and (3, 4): " + dVal);
}
}
Result:
F:\Java>java PointDemo

point1 coordinates :(1,1)


point2 coordinates :(7,9)

Calculating distance between two PointType objects


Distance between point1 and point2: 10.0

point3 coordinates :(0,0)


Calculating distance between a PointType object and int specified by its
coordinates
EX7: Inheritance
Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing
three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a
JAVA program to read and display at least 3 staff objects of all three categories.
class Staff
{
private int staffId;
private String name;
private String phone;
private double salary;

public Staff(int staffId, String name, String phone, double salary)


{
this.staffId = staffId;
this.name = name;
this.phone = phone;
this.salary = salary;
}
public int getStaffId()
{
return staffId;
}

public String getName()


{
return name;
}

public String getPhone()


{
return phone;
}

public double getSalary()


{
return salary;
}
public void DisplayInfo()
{
System.out.println("Name: " + this.getName());
System.out.println("Staff ID: " + this.getStaffId());
System.out.println("Phone: " + this.getPhone());
System.out.println("Salary: " + this.getSalary());
}
}
class Technical extends Staff
{
private String skills;

public Technical(int staffId, String name, String phone, double salary, String skills)
{
super(staffId, name, phone, salary);
this.skills = skills;
}

public String getSkills()


{
return skills;
}
public void DisplayInfo()
{
super.DisplayInfo();
System.out.println("Skills: " + this.getSkills());
}
}
class Contract extends Staff
{
private int period;

public Contract(int staffId, String name, String phone, double salary, int period)
{
super(staffId, name, phone, salary);
this.period = period;
}

public int getPeriod()


{
return period;
}
public void DisplayInfo()
{
super.DisplayInfo();
System.out.println("Period: " + this.getPeriod()+" months");
}
}
public class StaffTypeDemo
{
public static void main(String[] args)
{
Teaching t1 = new Teaching(1, "Rajesh Nayak", "9822546534", 75000, "Computer Science", 15);
Teaching t2 = new Teaching(2, "Sita Devi", "8787432499", 80000, "Mathematics ", 20);
Teaching t3 = new Teaching(3, "John Peter", "8528734373", 85000, "Physics", 25);
Technical te1 = new Technical(4,"Ramesha","9473673642",90000,"Java,Python,C++");
Technical te2 = new Technical(5,"Suresha","8917612332",95000,"JavaScript,React,Node.js");
Technical te3 = new Technical(6,"Dinesha","9944222323",100000,"Python,TensorFlow,Keras");
Contract c1 = new Contract(7, "Abida Begum", "9323786211", 75000, 6);
Contract c2 = new Contract(8, "Lily Thomas", "8776551219", 80000, 12);
Contract c3 = new Contract(9, "Seema Jain", "9922324343", 85000, 18);
//display the staff objects
System.out.println("Teaching Staff 1:");
t1.DisplayInfo();
System.out.println("\nTeaching Staff 2:");
t2.DisplayInfo();
System.out.println("\nTeaching Staff 3:");
System.out.println("\nTechnical Staff 1:");
te1.DisplayInfo();

System.out.println("\nTechnical Staff 2:");


te2.DisplayInfo();

System.out.println("\nTechnical Staff 3:");


te3.DisplayInfo();

System.out.println("\nContract Staff 1:");


c1.DisplayInfo();

System.out.println("\nContract Staff 2:");


c2.DisplayInfo();

System.out.println("\nContract Staff 3:");


c3.DisplayInfo();
}
}
Result: Publications: 20
F:\Java>Javac StaffTypeDemo.java
Teaching Staff 3:
F:\Java>Java StaffTypeDemo Name: John Peter
Teaching Staff 1: Staff ID: 3
Name: Rajesh Nayak Phone: 8528734373
Staff ID: 1 Salary: 85000.0
Phone: 9822546534 Domain: Physics
Salary: 75000.0 Publications: 25
Domain: Computer Science
Publications: 15 Technical Staff 1:
Name: Ramesha
Teaching Staff 2: Staff ID: 4
Name: Sita Devi Phone: 9473673642
Staff ID: 2 Salary: 90000.0
Phone: 8787432499 Skills: Java,Python,C++
Salary: 80000.0
Domain: Mathematics
Technical Staff 2: Phone: 9323786211
Name: Suresha Salary: 75000.0
Staff ID: 5 Period: 6 months
Phone: 8917612332
Salary: 95000.0 Contract Staff 2:
Skills: JavaScript,React,Node.js Name: Lily Thomas
Staff ID: 8
Technical Staff 3: Phone: 8776551219
Name: Dinesha Salary: 80000.0
Staff ID: 6 Period: 12 months
Phone: 9944222323
Salary: 100000.0 Contract Staff 3:
Skills: Python,TensorFlow,Keras Name: Seema Jain
Staff ID: 9
Contract Staff 1: Phone: 9922324343
Name: Abida Begum Salary: 85000.0
Staff ID: 7 Period: 18 months
Experiment 8: Demonstrate dynamic dispatch using abstract class in JAVA.
abstract class Shape
{
abstract void draw();
}

class Circle extends Shape


{
void draw()
{
System.out.println("Drawing Circle");
}
}

class Square extends Shape


{
void draw()
{
System.out.println("Drawing Square");
}
}

class DynamicDispatchDemo
{
public static void main(String[] args)
{
Shape s;
s = new Circle();
s.draw();
s = new Square();
s.draw();
Result:

F:\Java>java DynamicDispatchDemo
Drawing Circle
Drawing Square
Experiment9: Create two packages P1 and P2. In package P1, create class A, class B inherited from A, class
C . In package P2, create class D inherited from class A in package P1 and class E. Demonstrate working of
access modifiers (private, public, protected, default) in all these classes using JAVA.
// Package P1
package com.P1;
// Class A1 with private and protected variables and public methods
public class A
{
private int x;
protected int y;

public void setX(int x)


{
this.x = x;
}

public int getX()


{
return x;
}

public void setY(int y)


{
this.y = y;
}

public int getY()


{
// Package P1
package com.P1;

// Class B inherited from A with default variable and public method


public class B extends A
{
int z;

public void setZ(int z)


{
this.z = z;
}

public int getZ()


{
return z;
}
}
//save as B.Java
// Package P1
package com.P1;

// Class C with private variable and public method


public class C
{
private int w;

public void setW(int w)


{
this.w = w;
}

public int getW()


{
return w;
}
}

// Save as C.java
// Package P2
package com.P2;

// Class D inherited from A with protected variable and public method


public class D extends com.P1.A
{
protected int v;

public void setV(int v)


{
this.v = v;
}

public int getV()


{
return v;
}
}
// Save as D.java
// Package P2
package com.P2;

// Class E with private variable and public method


public class E
{
private int u;

public void setU(int u)


{
this.u = u;
}

public int getU()


{
return u;
}
}
// Save as E.java
import com.P1.A1;
import com.P1.B;
import com.P1.C;
import com.P2.D;
import com.P2.E;

public class PackageDemo


{

public static void main(String[] args)


{

// Creating an object of class A in package P1


A a = new A();
a.setX(10);
a.setY(20);
System.out.println("Value of x: " + a.getX());
System.out.println("Value of y: " + a.getY());
// Creating an object of class B in package P1
B b = new B();
b.setX(30);
b.setY(40);
b.setZ(50);
System.out.println("Value of x: " + b.getX());
System.out.println("Value of y: " + b.getY());
System.out.println("Value of z: " + b.getZ());

// Creating an object of class C in package P1


C c = new C();
c.setW(60);
System.out.println("Value of w: " + c.getW());
// Creating an object of class D in package P2
D d = new D();
d.setX(70);
d.setY(80);
d.setV(90);
System.out.println("Value of x: " + d.getX());
System.out.println("Value of y: " + d.getY());
System.out.println("Value of v: " + d.getV());

// Creating an object of class E in package P2


E e = new E();
e.setU(100);
System.out.println("Value of u: " + e.getU());
}
}
The above files should be stored in the folder structure as shown in the above
diagram.
First create a folder com in the same folder where you saved PackageDemo.java.
Then within com directory create two directories P1 and P2. Within P1 directory
store the files A.java, B.java and C.java. Within P2 directory store the files D.java
and E.java.
F:\Java>java PackageDemo
Value of x: 10
Value of y: 20
Value of x: 30
Value of y: 40
Value of z: 50
Value of w: 60
Value of x: 70
Value of y: 80
Value of v: 90
Value of u: 100
Experiment 10: Write a JAVA program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an
exception when b is equal to zero. Also demonstrate working of ArrayIndexOutOfBoundException.
import java.util.Scanner;
public class ExceptionDemo3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter two integers: ");
int a = sc.nextInt();
int b = sc.nextInt();
try
{
if (b == 0)
{
throw new ArithmeticException("Division by zero");
}
int result = a / b;
System.out.println("Result of integer division: " + result);
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
try
{
int[] arr = new int[5];
arr[10] = 50; //invalid index generates exception
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
}
F:\Java>java ExceptionDemo3
Enter two integers:
24
Result of integer division: 0
Index 10 out of bounds for length 5

You might also like