0% found this document useful (0 votes)
11 views31 pages

JAVALAB

The document contains a series of Java programming exercises and solutions, organized into modules. It covers various topics such as number properties (neon numbers, palindromes), mathematical operations (quadratic equations, sorting), object-oriented programming (classes and constructors), exception handling, and multithreading. Each exercise includes code examples and explanations for implementing the required functionality.

Uploaded by

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

JAVALAB

The document contains a series of Java programming exercises and solutions, organized into modules. It covers various topics such as number properties (neon numbers, palindromes), mathematical operations (quadratic equations, sorting), object-oriented programming (classes and constructors), exception handling, and multithreading. Each exercise includes code examples and explanations for implementing the required functionality.

Uploaded by

aarushi19thakur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSE2006 Programming in Java

Lab Exercises List

ANUSHKA THAKUR (24BAI10438)

Module 01
1. Write a program to find

a. Neon number

b. Check the given number is palindrome or not

c. Different roots of an equation.

d. Sorting of integers

SOLUTIONS:

1. Neon Number
A neon number is a number where the sum of digits of its square is equal to the number.

CODE
import [Link];

public class neonnumber {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int num, square, sum = 0, digit;

[Link]("Enter a number: ");


num = [Link]();
square = num * num;

while (square > 0) {


digit = square % 10;
sum += digit;
square /= 10;
}

if (sum == num)
[Link]("Neon Number");
else
[Link]("Not a Neon Number");
}
}
2. Palindrome Number

A number is palindrome if it reads same forward and backward.

CODE

import [Link];

public class PalindromeNumber {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int num, original, reverse = 0, digit;

[Link]("Enter a number: ");

num = [Link]();

original = num;

while (num > 0) {

digit = num % 10;

reverse = reverse * 10 + digit;

num /= 10;

if (original == reverse)

[Link]("Palindrome Number");

else

[Link]("Not a Palindrome");

}
3. Roots of Quadratic Equation

CODE

import [Link];

public class QuadraticRoots {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

double a, b, c, d, root1, root2;

[Link]("Enter a, b, c: ");

a = [Link]();

b = [Link]();

c = [Link]();

d = b * b - 4 * a * c;

if (d > 0) {

root1 = (-b + [Link](d)) / (2 * a);

root2 = (-b - [Link](d)) / (2 * a);

[Link]("Real and Different roots: " + root1 + " and " + root2);

} else if (d == 0) {

root1 = -b / (2 * a);

[Link]("Real and Equal roots: " + root1);

} else {

[Link]("Imaginary roots");

}
4. Sorting Integers (Ascending Order)

CODE

import [Link];

public class SortIntegers {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n;

[Link]("Enter number of elements: ");

n = [Link]();

int[] arr = new int[n];

[Link]("Enter elements:");

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

// Bubble Sort

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

[Link]("Sorted array:");

for (int i = 0; i < n; i++) {

[Link](arr[i] + " ");

}
Q.2 Write a program to create a calculator using switch case.

import [Link];

public class Calculator {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

double num1, num2;

char operator;

[Link]("Enter first number: ");

num1 = [Link]();

[Link]("Enter second number: ");

num2 = [Link]();

[Link]("Enter operator (+, -, *, /): ");

operator = [Link]().charAt(0);

switch (operator) {

case '+':

[Link]("Result = " + (num1 + num2));

break;

case '-':

[Link]("Result = " + (num1 - num2));

break;

case '*':

[Link]("Result = " + (num1 * num2));

break;

case '/':

if (num2 != 0)

[Link]("Result = " + (num1 / num2));

else

[Link]("Cannot divide by zero");

break;

default:

[Link]("Invalid operator");
}

3. Write a program for Matrix Addition and Multiplication.

import [Link];

public class MatrixOperations {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int r, c;

[Link]("Enter number of rows: ");

r = [Link]();

[Link]("Enter number of columns: ");

c = [Link]();

int[][] A = new int[r][c];

int[][] B = new int[r][c];

int[][] sum = new int[r][c];

// Input Matrix A

[Link]("Enter elements of Matrix A:");

for(int i = 0; i < r; i++) {

for(int j = 0; j < c; j++) {


A[i][j] = [Link]();

// Input Matrix B

[Link]("Enter elements of Matrix B:");

for(int i = 0; i < r; i++) {

for(int j = 0; j < c; j++) {

B[i][j] = [Link]();

// Matrix Addition

[Link]("Matrix Addition:");

for(int i = 0; i < r; i++) {

for(int j = 0; j < c; j++) {

sum[i][j] = A[i][j] + B[i][j];

[Link](sum[i][j] + " ");

[Link]();

// Matrix Multiplication

int[][] product = new int[r][c];

[Link]("Matrix Multiplication:");

for(int i = 0; i < r; i++) {

for(int j = 0; j < c; j++) {

product[i][j] = 0;

for(int k = 0; k < c; k++) {

product[i][j] += A[i][k] * B[k][j];


}

[Link](product[i][j] + " ");

[Link]();

MODULE 02
[Link] a class Employee with overloaded constructors to initialize employee details
based on different combinations of arguments. Ensure the constructors support the

creation of objects in various ways.

class Employee {

int id;

String name;

double salary;

// Default constructor

Employee() {
id = 0;

name = "Not Assigned";

salary = 0.0;

// Constructor with id only

Employee(int id) {

[Link] = id;

name = "Not Assigned";

salary = 0.0;

// Constructor with id and name

Employee(int id, String name) {

[Link] = id;

[Link] = name;

salary = 0.0;

// Constructor with all details

Employee(int id, String name, double salary) {

[Link] = id;

[Link] = name;

[Link] = salary;

// Method to display details

void display() {

[Link]("ID: " + id);

[Link]("Name: " + name);

[Link]("Salary: " + salary);


[Link]("---------------------");

public class Main {

public static void main(String[] args) {

// Different ways to create objects

Employee e1 = new Employee();

Employee e2 = new Employee(101);

Employee e3 = new Employee(102, "Anushka");

Employee e4 = new Employee(103, "Rahul", 50000);

// Display details

[Link]();

[Link]();

[Link]();

[Link]();

}
5. Create a class Person with firstName and lastName as data members. Override
the toString() method to return the full name of the person. Define constructors to take

appropriate parameters.

class Person {

String firstName;

String lastName;

// Default constructor

Person() {

firstName = "Unknown";

lastName = "Unknown";

// Parameterized constructor

Person(String firstName, String lastName) {

[Link] = firstName;

[Link] = lastName;

// Override toString() method

public String toString() {

return firstName + " " + lastName;

public class Main {

public static void main(String[] args) {

// Creating objects

Person p1 = new Person();

Person p2 = new Person("Anushka", "Thakur");


// Printing objects (automatically calls toString())

[Link](p1);

[Link](p2);

6. Create a Student class with name, rollNo, and marks as attributes. Write a method to
calculate the grade based on the marks and display the grade. Create multiple instances

of the Student class and print their grades.

class Student {

String name;

int rollNo;

int marks;

// Constructor

Student(String name, int rollNo, int marks) {

[Link] = name;

[Link] = rollNo;

[Link] = marks;

// Method to calculate grade

String calculateGrade() {

if (marks >= 90)

return "A";

else if (marks >= 75)

return "B";

else if (marks >= 60)

return "C";

else if (marks >= 50)

return "D";
else

return "F";

// Method to display details

void display() {

[Link]("Name: " + name);

[Link]("Roll No: " + rollNo);

[Link]("Marks: " + marks);

[Link]("Grade: " + calculateGrade());

[Link]("----------------------");

public class Main {

public static void main(String[] args) {

// Creating multiple student objects

Student s1 = new Student("Anushka", 1, 92);

Student s2 = new Student("Rahul", 2, 76);

Student s3 = new Student("Priya", 3, 58);

// Display details

[Link]();

[Link]();

[Link]();

7. Write a program to accept three numbers and find the largest of the three using method
overloading.

class Largest {
// Method to find largest of two numbers

int max(int a, int b) {

return (a > b) ? a : b;

// Overloaded method to find largest of three numbers

int max(int a, int b, int c) {

return max(max(a, b), c); // reuse method

public class Main {

public static void main(String[] args) {

Largest obj = new Largest();

int result = [Link](10, 25, 15);

[Link]("Largest number = " + result);

8. Create a program that keeps track of the number of objects created and displays
the count in a function called display().

class Counter {

static int count = 0; // static variable to track objects


// Constructor

Counter() {

count++; // increment whenever object is created

// Method to display count

void display() {

[Link]("Number of objects created: " + count);

public class Main {

public static void main(String[]


args) {

// Creating objects

Counter obj1 = new Counter();

Counter obj2 = new Counter();

Counter obj3 = new Counter();

// Display count

[Link]();

MODULE 03
9. Write a Java program to create a method that takes a string as input and throws an
exception if the string does not contain vowels.

class NoVowelException extends Exception {

NoVowelException(String message) {
super(message);

public class Main {

// Method to check vowels

static void checkVowels(String str) throws NoVowelException {

str = [Link]();

boolean hasVowel = false;

for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

hasVowel = true;

break;

if (!hasVowel) {

throw new NoVowelException("String does not contain any vowels!");

} else {

[Link]("String contains vowels.");

public static void main(String[] args) {

try {

checkVowels("sky"); // change input here

} catch (NoVowelException e) {

[Link]("Exception: " + [Link]());


}

10. Write a Java program to create a method that takes an integer as a parameter and throws
an exception if the number is odd.

class OddNumberException extends Exception {

public OddNumberException(String message) {

super(message);

public class CheckNumber {

// Method to check number

static void checkEven(int num) throws OddNumberException {

if (num % 2 != 0) {

throw new OddNumberException("Number is odd!");

} else {

[Link]("Number is even.");

public static void main(String[] args) {

try {

checkEven(5); // change this value to test

} catch (OddNumberException e) {
[Link]("Exception caught: " + [Link]());

11. Java Program to Display all Threads Status.


public class ThreadStatusDemo {

public static void main(String[] args) {

// Get all active threads in current thread group

ThreadGroup group = [Link]().getThreadGroup();

Thread[] threads = new Thread[[Link]()];

[Link](threads);

[Link]("Thread Name\t\tState");

for (Thread t : threads) {

if (t != null) {

[Link]([Link]() + "\t\t" + [Link]());

}
12. Java program to get the id of a thread.
class ThreadIdDemo extends Thread {

public void run() {

[Link]("Thread Name: " + [Link]().getName());

[Link]("Thread ID: " + [Link]().getId());

public static void main(String[] args) {

ThreadIdDemo t1 = new ThreadIdDemo();

ThreadIdDemo t2 = new ThreadIdDemo();

[Link]();

[Link]();

13. Java Program to Illustrate Priorities in Multithreading.


class PriorityDemo extends Thread {

public void run() {

[Link]("Thread Name: " + [Link]().getName());

[Link]("Thread Priority: " + [Link]().getPriority());

}
public static void main(String[] args) {

PriorityDemo t1 = new PriorityDemo();

PriorityDemo t2 = new PriorityDemo();

PriorityDemo t3 = new PriorityDemo();

// Setting thread names

[Link]("Low Priority Thread");

[Link]("Normal Priority Thread");

[Link]("High Priority Thread");

// Setting priorities

[Link](Thread.MIN_PRIORITY); // 1

[Link](Thread.NORM_PRIORITY); // 5

[Link](Thread.MAX_PRIORITY); // 10

// Start threads

[Link]();

[Link]();

[Link]();

Module 04
14. Java Array Program to Remove All Occurrences of an Element in an Array.
import [Link];
public class RemoveElement {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

// Input array size

[Link]("Enter size of array: ");

int n = [Link]();

int[] arr = new int[n];

// Input elements

[Link]("Enter elements:");

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

// Element to remove

[Link]("Enter element to remove: ");

int key = [Link]();

// Create new array to store result

int[] result = new int[n];

int j = 0;

// Remove all occurrences

for (int i = 0; i < n; i++) {

if (arr[i] != key) {

result[j++] = arr[i];
}

// Display result

[Link]("Array after removing element:");

for (int i = 0; i < j; i++) {

[Link](result[i] + " ");

[Link]();

15. Java program to check whether a string is a Palindrome.


import [Link];

public class PalindromeCheck {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]();


String original = str;

String reversed = "";

// Reverse the string

for (int i = [Link]() - 1; i >= 0; i--) {

reversed += [Link](i);

// Check palindrome

if ([Link](reversed)) {

[Link]("The string is a Palindrome.");

} else {

[Link]("The string is NOT a Palindrome.");

[Link]();

16. Write a Java program to create an array list, add some colors (strings), and print out the
collection.

import [Link];

public class ColorArrayList {

public static void main(String[] args) {

// Create ArrayList

ArrayList<String> colors = new ArrayList<>();


// Add colors

[Link]("Red");

[Link]("Green");

[Link]("Blue");

[Link]("Yellow");

[Link]("Black");

// Print the collection

[Link]("Colors in the ArrayList:");

for (String color : colors) {

[Link](color);

17. Write a Java program to iterate through all elements in a linked list starting at the
specified position.

import [Link];

import [Link];

public class LinkedListIteration {

public static void main(String[] args) {

LinkedList<String> list = new LinkedList<>();


// Add elements

[Link]("Red");

[Link]("Green");

[Link]("Blue");

[Link]("Yellow");

[Link]("Black");

Scanner sc = new Scanner([Link]);

// Input starting position

[Link]("Enter starting index: ");

int index = [Link]();

// Check valid index

if (index < 0 || index >= [Link]()) {

[Link]("Invalid index!");

} else {

[Link]("Elements from position " + index + ":");

// Iterate from given index

for (int i = index; i < [Link](); i++) {

[Link]([Link](i));

[Link]();

}
}

18. Write a Java program to calculate the average of a list of integers using streams.
import [Link];

import [Link];

import [Link];

public class AverageUsingStreams {

public static void main(String[] args) {

// Create a list of integers

List<Integer> numbers = [Link](10, 20, 30, 40, 50);

// Calculate average using streams

OptionalDouble avg = [Link]()

.mapToInt(Integer::intValue)

.average();

// Display result

if ([Link]()) {

[Link]("Average: " + [Link]());

} else {

[Link]("List is empty.");

}
19. Write a Java program to get the file size in bytes, KB, MB.
import [Link];

public class FileSizeDemo {

public static void main(String[] args) {

File file = new File("[Link]"); // change file name/path

if ([Link]()) {

long bytes = [Link]();

double kb = bytes / 1024.0;

double mb = kb / 1024.0;

[Link]("File Size:");

[Link]("Bytes: " + bytes);

[Link]("KB: " + kb);

[Link]("MB: " + mb);

} else {

[Link]("File does not exist.");

20. Write a Java program to read the first 3 lines of a file.


import [Link];

import [Link];

import [Link];
public class ReadFirst3Lines {

public static void main(String[] args) {

try {

BufferedReader br = new BufferedReader(new FileReader("[Link]"));

for (int i = 0; i < 3; i++) {

String line = [Link]();

if (line == null) break;

[Link](line);

[Link]();

} catch (IOException e) {

[Link]("Error: " + [Link]());

Module 05
Create a Student Database and print average mark details of minimum 10 students using

JDBC-ODBC bridge.

import [Link].*;

public class StudentDatabase {

public static void main(String[] args) {

try {
// Load JDBC-ODBC driver

[Link]("[Link]");

// Connect using DSN (create DSN named StudentDSN)

Connection con = [Link]("jdbc:odbc:StudentDSN");

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM Student");

int totalMarks = 0;

int count = 0;

[Link]("Student Details:");

[Link]("-------------------------");

while ([Link]()) {

int id = [Link]("id");

String name = [Link]("name");

int marks = [Link]("marks");

[Link](id + " " + name + " " + marks);

totalMarks += marks;

count++;

// Calculate average

if (count >= 10) {

double average = (double) totalMarks / count;

[Link]("-------------------------");
[Link]("Average Marks: " + average);

} else {

[Link]("Minimum 10 students required!");

[Link]();

} catch (Exception e) {

[Link]("Error: " + e);

Create an employee database and print their payslip of minimum 5 employees using

JDBC-ODBC brige.

import [Link].*;

public class EmployeeDatabase {

public static void main(String[] args) {

try {

// Load JDBC-ODBC driver

[Link]("[Link]");
// Connect using DSN (create DSN named EmployeeDSN)

Connection con = [Link]("jdbc:odbc:EmployeeDSN");

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM Employee");

int count = 0;

[Link]("Employee Payslip");

[Link]("---------------------------");

while ([Link]()) {

int id = [Link]("id");

String name = [Link]("name");

double basic = [Link]("salary");

// Salary calculations

double hra = basic * 0.20; // 20%

double da = basic * 0.10;*

You might also like