VTU – 2021 Scheme | EC Branch | 5th Semester
21EC583 – Java Programming
Lab Programs – Complete Solutions
MODULE 1
Program 1a: Arithmetic Operations on Two Integers
import [Link];
public class Arithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
[Link]("Addition : " + (a + b));
[Link]("Subtraction : " + (a - b));
[Link]("Multiplication : " + (a * b));
}
}
Program 1b: Simple and Compound Interest
import [Link];
public class Interest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Principal: "); double P = [Link]();
[Link]("Enter Rate (%): "); double R = [Link]();
[Link]("Enter Time (yrs): "); double T = [Link]();
double SI = (P * R * T) / 100;
double CI = P * [Link](1 + R / 100, T) - P;
[Link]("Simple Interest : %.2f%n", SI);
[Link]("Compound Interest: %.2f%n", CI);
}
}
Program 1c: Swap Two Numbers (with and without temp)
public class Swap {
public static void main(String[] args) {
int a = 10, b = 20;
// With temporary variable
int temp = a; a = b; b = temp;
[Link]("With temp -> a=" + a + ", b=" + b);
// Without temporary variable
a = 10; b = 20;
a = a + b; b = a - b; a = a - b;
[Link]("Without temp -> a=" + a + ", b=" + b);
}
}
Program 2a: Quadratic Equation Solver
import [Link];
public class Quadratic {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a, b, c: ");
double a = [Link](), b = [Link](), c = [Link]();
double disc = b*b - 4*a*c;
if (disc < 0)
[Link]("No real solutions.");
else if (disc == 0)
[Link]("One solution: x = %.2f%n", -b / (2*a));
else {
double x1 = (-b + [Link](disc)) / (2*a);
double x2 = (-b - [Link](disc)) / (2*a);
[Link]("Two solutions: x1 = %.2f, x2 = %.2f%n", x1, x2);
}
}
}
Program 2b: Print All Prime Numbers from 1 to N
import [Link];
public class Primes {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= [Link](n); i++)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter N: ");
int N = [Link]();
[Link]("Primes from 1 to " + N + ": ");
for (int i = 2; i <= N; i++)
if (isPrime(i)) [Link](i + " ");
[Link]();
}
}
Program 2c: Factorial of a Number
import [Link];
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
long fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
[Link]("Factorial of " + n + " = " + fact);
}
}
Program 3a: Linear and Binary Search
import [Link];
import [Link];
public class Search {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 9, 2, 7};
Scanner sc = new Scanner([Link]);
[Link]("Enter element to search: ");
int key = [Link]();
// Linear Search
int linIdx = -1;
for (int i = 0; i < [Link]; i++)
if (arr[i] == key) { linIdx = i; break; }
[Link]("Linear Search: " + (linIdx >= 0 ? "Found at index " + linIdx : "Not
found"));
// Binary Search (array must be sorted)
[Link](arr);
int binIdx = [Link](arr, key);
[Link]("Binary Search: " + (binIdx >= 0 ? "Found at index " + binIdx + " (sorted
array)" : "Not found"));
}
}
Program 3b: Bubble Sort (Ascending & Descending)
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
int n = [Link];
// Ascending
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1]) { int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; }
[Link]("Ascending : ");
for (int x : arr) [Link](x + " ");
// Descending
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] < arr[j+1]) { int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; }
[Link]("
Descending: ");
for (int x : arr) [Link](x + " ");
}
}
Program 3c: Largest and Smallest Element in Array
public class MinMax {
public static void main(String[] args) {
int[] arr = {3, 7, 1, 9, 4, 6, 2};
int min = arr[0], max = arr[0];
for (int x : arr) { if (x < min) min = x; if (x > max) max = x; }
[Link]("Largest : " + max);
[Link]("Smallest: " + min);
}
}
MODULE 2
Program 4: Matrix Operations (Add, Multiply, Determinant)
public class MatrixOps {
static int[][] add(int[][] A, int[][] B, int n) {
int[][] C = new int[n][n];
for (int i=0;i return C;
}
static int[][] multiply(int[][] A, int[][] B, int n) {
int[][] C = new int[n][n];
for(int i=0;i return C;
}
static int determinant(int[][] A, int n) {
if (n == 1) return A[0][0];
if (n == 2) return A[0][0]*A[1][1] - A[0][1]*A[1][0];
int det = 0;
for (int c = 0; c < n; c++) {
int[][] sub = new int[n-1][n-1];
for (int i=1;i det += (int)[Link](-1, c) * A[0][c] * determinant(sub, n-1);
}
return det;
}
static void print(int[][] M, int n) { for(int[] r:M) { for(int x:r) [Link]("%4d",x);
[Link](); } }
public static void main(String[] args) {
int[][] A = {{1,2},{3,4}}, B = {{5,6},{7,8}};
[Link]("A + B:"); print(add(A,B,2),2);
[Link]("A x B:"); print(multiply(A,B,2),2);
[Link]("det(A) = " + determinant(A,2));
}
}
Program 5: String Operations (Reverse, Palindrome, Compare)
import [Link];
public class StringOps {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Reverse
[Link]("Enter a string: ");
String s = [Link]();
String rev = new StringBuilder(s).reverse().toString();
[Link]("Reversed: " + rev);
// Palindrome
[Link]([Link](rev) ? s + " is a palindrome" : s + " is NOT a palindrome");
// Compare two strings
[Link]("Enter second string: ");
String s2 = [Link]();
int cmp = [Link](s2);
if (cmp == 0) [Link]("Strings are EQUAL");
else if (cmp < 0) [Link](s + " comes BEFORE " + s2);
else [Link](s + " comes AFTER " + s2);
}
}
Program 6: Student Class with n Objects
import [Link];
class Student {
String usn, name, branch, phone;
Student(String usn, String name, String branch, String phone) {
[Link]=usn; [Link]=name; [Link]=branch; [Link]=phone;
}
void display() {
[Link]("%-15s %-15s %-10s %-12s%n", usn, name, branch, phone);
}
}
public class StudentDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link](); [Link]();
Student[] students = new Student[n];
for (int i = 0; i < n; i++) {
[Link]("Student " + (i+1) + ":");
[Link](" USN: "); String usn = [Link]();
[Link](" Name: "); String name = [Link]();
[Link](" Branch: "); String branch = [Link]();
[Link](" Phone: "); String phone = [Link]();
students[i] = new Student(usn, name, branch, phone);
}
[Link]("%n%-15s %-15s %-10s %-12s%n", "USN", "Name", "Branch", "Phone");
[Link]("-".repeat(55));
for (Student s : students) [Link]();
}
}
MODULE 3
Program 7: BankAccount & SBAccount (Inheritance + Method Overriding)
class BankAccount {
protected double balance;
BankAccount(double balance) { [Link] = balance; }
void deposit(double amount) {
balance += amount;
[Link]("Deposited: " + amount + " | Balance: " + balance);
}
void withdraw(double amount) {
balance -= amount;
[Link]("Withdrawn: " + amount + " | Balance: " + balance);
}
}
class SBAccount extends BankAccount {
SBAccount(double balance) { super(balance); }
@Override
void withdraw(double amount) {
if (balance - amount < 100)
[Link]("Withdrawal denied! Balance must remain >= 100. Current: " + balance);
else {
balance -= amount;
[Link]("Withdrawn: " + amount + " | Balance: " + balance);
}
}
}
public class BankDemo {
public static void main(String[] args) {
SBAccount acc = new SBAccount(500);
[Link](200);
[Link](550); // allowed
[Link](200); // denied
}
}
Program 8: Method Overloading and Constructor Overloading
public class OverloadDemo {
// Constructor Overloading
int x, y;
OverloadDemo() { x = 0; y = 0; }
OverloadDemo(int x) { this.x = x; y = 0; }
OverloadDemo(int x, int y) { this.x = x; this.y = y; }
// Method Overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
String add(String a, String b) { return a + b; }
public static void main(String[] args) {
OverloadDemo o1 = new OverloadDemo();
OverloadDemo o2 = new OverloadDemo(5);
OverloadDemo o3 = new OverloadDemo(3, 7);
[Link]("Constructor o1: x=" + o1.x + ", y=" + o1.y);
[Link]("Constructor o2: x=" + o2.x + ", y=" + o2.y);
[Link]("Constructor o3: x=" + o3.x + ", y=" + o3.y);
OverloadDemo m = new OverloadDemo();
[Link]("add(2,3) = " + [Link](2, 3));
[Link]("add(2.5,3.5) = " + [Link](2.5, 3.5));
[Link]("add(1,2,3) = " + [Link](1, 2, 3));
[Link]("add("Hello ","World") = " + [Link]("Hello ", "World"));
}
}
Program 9: Staff Hierarchy (Inheritance – Teaching, Technical, Contract)
import [Link];
class Staff {
int staffId;
String name, phone;
double salary;
Staff(int id, String name, String phone, double salary) {
staffId=id; [Link]=name; [Link]=phone; [Link]=salary;
}
void display() {
[Link]("ID: %d | Name: %-12s | Phone: %s | Salary: %.2f%n",
staffId, name, phone, salary);
}
}
class Teaching extends Staff {
String domain; int publications;
Teaching(int id,String nm,String ph,double sal,String dom,int pub) {
super(id,nm,ph,sal); domain=dom; publications=pub;
}
void display() { [Link](); [Link](" Type: Teaching | Domain: "+domain+" |
Publications: "+publications); }
}
class Technical extends Staff {
String skills;
Technical(int id,String nm,String ph,double sal,String sk) {
super(id,nm,ph,sal); skills=sk;
}
void display() { [Link](); [Link](" Type: Technical | Skills: "+skills); }
}
class Contract extends Staff {
String period;
Contract(int id,String nm,String ph,double sal,String per) {
super(id,nm,ph,sal); period=per;
}
void display() { [Link](); [Link](" Type: Contract | Period: "+period); }
}
public class StaffDemo {
public static void main(String[] args) {
Staff[] s = {
new Teaching(101,"Dr. Rao","9900001111",85000,"AI/ML",12),
new Technical(102,"Mohan","9900002222",55000,"Networking, Linux"),
new Contract(103,"Priya","9900003333",40000,"6 months")
};
[Link]("=== Staff Details ===");
for (Staff st : s) { [Link](); [Link](); }
}
}
MODULE 4
Program 10a: Exception Handling – Division by Zero & ArrayIndexOutOfBounds
import [Link];
public class ExceptionDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Division by zero
try {
[Link]("Enter a: "); int a = [Link]();
[Link]("Enter b: "); int b = [Link]();
if (b == 0) throw new ArithmeticException("Division by zero is not allowed!");
[Link]("a / b = " + (a / b));
} catch (ArithmeticException e) {
[Link]("Caught: " + [Link]());
}
// ArrayIndexOutOfBounds
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught: Array index out of bounds – " + [Link]());
} finally {
[Link]("Finally block always executes.");
}
}
}
Program 10b: Throw Exception for Odd Number
public class OddException {
static void checkEven(int n) throws Exception {
if (n % 2 != 0)
throw new Exception("Number " + n + " is ODD – only even numbers allowed!");
[Link](n + " is EVEN.");
}
public static void main(String[] args) {
int[] numbers = {4, 7, 10, 3};
for (int n : numbers) {
try {
checkEven(n);
} catch (Exception e) {
[Link]("Exception: " + [Link]());
}
}
}
}
Program 11: Abstract Class BankAccount with SavingsAccount & CurrentAccount
abstract class BankAccount {
protected String owner;
protected double balance;
BankAccount(String owner, double balance) {
[Link] = owner; [Link] = balance;
}
abstract void deposit(double amount);
abstract void withdraw(double amount);
void showBalance() {
[Link]("Account holder: " + owner + " | Balance: " + balance);
}
}
class SavingsAccount extends BankAccount {
private double interestRate = 0.04;
SavingsAccount(String owner, double bal) { super(owner, bal); }
@Override
public void deposit(double amount) {
balance += amount + amount * interestRate;
[Link]("[Savings] Deposited " + amount + " (+interest). Balance: " + balance);
}
@Override
public void withdraw(double amount) {
if (amount > balance) [Link]("[Savings] Insufficient funds!");
else { balance -= amount; [Link]("[Savings] Withdrawn " + amount + ". Balance: " +
balance); }
}
}
class CurrentAccount extends BankAccount {
private double overdraftLimit = 500;
CurrentAccount(String owner, double bal) { super(owner, bal); }
@Override
public void deposit(double amount) {
balance += amount;
[Link]("[Current] Deposited " + amount + ". Balance: " + balance);
}
@Override
public void withdraw(double amount) {
if (amount > balance + overdraftLimit)
[Link]("[Current] Exceeds overdraft limit!");
else { balance -= amount; [Link]("[Current] Withdrawn " + amount + ". Balance: " +
balance); }
}
}
public class AbstractBankDemo {
public static void main(String[] args) {
BankAccount sa = new SavingsAccount("Alice", 1000);
[Link](500); [Link](200); [Link]();
[Link]();
BankAccount ca = new CurrentAccount("Bob", 1000);
[Link](300); [Link](1400); [Link]();
}
}
MODULE 5
Program 12: Packages and Access Modifiers
File structure:
• P1/[Link] • P1/[Link] • P1/[Link] • P2/[Link] • P2/[Link]
P1/[Link]
package P1;
public class A {
private int privateVar = 10; // accessible only within A
protected int protectedVar = 20; // accessible within P1 and subclasses
public int publicVar = 30; // accessible everywhere
int defaultVar = 40; // accessible within P1 only
public void display() {
[Link]("Class A:");
[Link](" private = " + privateVar);
[Link](" protected = " + protectedVar);
[Link](" public = " + publicVar);
[Link](" default = " + defaultVar);
}
}
P1/[Link] (inherits from A in same package)
package P1;
public class B extends A {
public void show() {
[Link]("Class B (extends A, same package P1):");
// privateVar NOT accessible
[Link](" protected = " + protectedVar); // OK
[Link](" public = " + publicVar); // OK
[Link](" default = " + defaultVar); // OK (same package)
}
}
P1/[Link] (same package, no inheritance)
package P1;
public class C {
public void show() {
A obj = new A();
[Link]("Class C (same package P1, no inheritance):");
// [Link] NOT accessible
[Link](" protected = " + [Link]); // OK
[Link](" public = " + [Link]); // OK
[Link](" default = " + [Link]); // OK (same package)
}
}
P2/[Link] (inherits from A in different package P1)
package P2;
import P1.A;
public class D extends A {
public void show() {
[Link]("Class D (extends A, different package P2):");
// privateVar NOT accessible
[Link](" protected = " + protectedVar); // OK (subclass)
[Link](" public = " + publicVar); // OK
// defaultVar NOT accessible (different package)
}
}
P2/[Link] (different package, no inheritance)
package P2;
import P1.A;
public class E {
public void show() {
A obj = new A();
[Link]("Class E (different package P2, no inheritance):");
// privateVar NOT accessible
// protectedVar NOT accessible (no inheritance)
[Link](" public = " + [Link]); // Only public accessible
// defaultVar NOT accessible (different package)
}
}
[Link] (Driver class)
import P1.*;
import P2.*;
public class Main {
public static void main(String[] args) {
new A().display(); [Link]();
new B().show(); [Link]();
new C().show(); [Link]();
new D().show(); [Link]();
new E().show();
}
}
Access Modifier Summary Table:
| Modifier | Within Class A | Same Package (B,C) | Subclass diff pkg (D) | Non-subclass diff pkg
(E) |
|-------------|---------------|-------------------|----------------------|--------------------------|
| private | YES | NO | NO | NO |
| default | YES | YES | NO | NO |
| protected | YES | YES | YES | NO |
| public | YES | YES | YES | YES |
End of 21EC583 Java Programming Lab Programs
VTU | EC Branch | 2021 Scheme | 5th Semester