0% found this document useful (0 votes)
5 views13 pages

Java

The document contains Java programming exercises covering various topics such as calculating sums, factorials, converting numbers, checking for prime numbers, and demonstrating string manipulation. It also includes examples of class creation, method overloading, access specifiers, static functions, boxing and unboxing, and package usage. Each exercise is presented with code snippets and sample outputs to illustrate the concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Java

The document contains Java programming exercises covering various topics such as calculating sums, factorials, converting numbers, checking for prime numbers, and demonstrating string manipulation. It also includes examples of class creation, method overloading, access specifiers, static functions, boxing and unboxing, and package usage. Each exercise is presented with code snippets and sample outputs to illustrate the concepts effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

CORE – 8 Practical: Java Programming Lab

1. To find the sum of any number of integers entered as command line arguments.
import java.util.*;
public class SumOfNumbers
{
public static void main(String args[])
{
int i, sum=0, z;
Scanner sc = new Scanner(System.in);
System.out.print("\n Enter Number of Numbers to be Calculated: ");
int n = sc.nextInt();
for(i=0;i<n;i++)
{
System.out.print("Enter the number: ");
z = sc.nextInt();
sum=sum+z;
}
System.out.println("The sum of the numbers is: "+sum);
}
}
op
Enter Number of Numbers to be Calculated: 2
Enter the number: 1
Enter the number: 2
The sum of the numbers is: 3
-----------------------------------------------------------------------------
2. To find the factorial of a given number.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to find its factorial: ");
int number = sc.nextInt();
sc.close();
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("The factorial of " + number + " is: " + factorial);
}
}
op
Enter a number to find its factorial: 5
The factorial of 5 is: 120
-------------------------------------------------------------------
3. To convert a decimal to binary number.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = sc.nextInt();
String binary = Integer.toBinaryString(decimal);
System.out.println("Binary equivalent: " + binary);
}
}
Output:
Enter a decimal number: 10
Binary equivalent: 1010
-----------------------------------------------------------------------------------
-
4. To check if a number is prime or not, by taking the number as input from the
keyboard.
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to check if it is prime: ");
int number = sc.nextInt();
sc.close();
boolean isPrime = true;
if (number <= 1) {
isPrime = false; // 0 and 1 are not prime numbers
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
op
Enter a number to check if it is prime: 7
7 is a prime number.
Enter a number to check if it is prime: 8
8 is not a prime number.
-----------------------------------------------------------------------------------
-----------------
5. To find the sum of any number of integers interactively, i.e., entering every
number from
the keyboard, whereas the total number of integers is given as a command line
argument.

import java.util.Scanner;
public class InteractiveSum {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java InteractiveSum <number_of_integers>");
System.exit(1);
}

int n = Integer.parseInt(args[0]);
int sum = 0;
Scanner scanner = new Scanner(System.in);

try {
for (int i = 0; i < n; i++) {
System.out.print("Enter integer " + (i + 1) + ": ");
int num = scanner.nextInt();
sum += num;
}
} catch (NumberFormatException e) {
System.err.println("Invalid input. Please enter integers only.");
} finally {
scanner.close();
}

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


}
}

Output:
//the command line argument is 3
Enter integer 1: 10
Enter integer 2: 20
Enter integer 3: 30
Sum: 60
------------------------------------------------------------------------------
6. Write a program that show working of different functions of String and String
Buffer
classs like set Char At( ), set Length( ), append( ), insert( ), concat( )and
equals( ).
public class StringAndStringBufferDemo {
public static void main(String[] args) {
System.out.println("String class functions:");
String str1 = "Hello";
String str2 = "World";
String strConcat = str1.concat(" ").concat(str2);
System.out.println("Concatenation using concat(): " + strConcat);
boolean isEqual = str1.equals(str2);
System.out.println("Equals using equals(): " + isEqual);
System.out.println("\nStringBuffer class functions:");
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println("After append(): " + sb.toString());
sb.insert(6, "Beautiful ");
System.out.println("After insert(): " + sb.toString());
sb.setCharAt(6, 'b');
System.out.println("After setCharAt(): " + sb.toString());
sb.setLength(5);
System.out.println("After setLength(): " + sb.toString());
StringBuffer sb2 = new StringBuffer("Hello");
boolean isBufferEqual = sb.toString().equals(sb2.toString());
System.out.println("StringBuffer equals using equals(): " + isBufferEqual);
}
}
op
String class functions:
Concatenation using concat(): Hello World
Equals using equals(): false

StringBuffer class functions:


After append(): Hello World
After insert(): Hello Beautiful World
After setCharAt(): Hello beautiful World
After setLength(): Hello
StringBuffer equals using equals(): true
-----------------------------------------------------------------------------------
----
7. Write a program to create a – “distance” class with methods where distance is
computed
in terms of feet and inches, how to create objects of a class and to see the use of
this
pointer.
class Distance {
private int feet;
private int inches;
public Distance() {
this.feet = 0;
this.inches = 0;
}
public Distance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
public void setDistance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
public void displayDistance() {
System.out.println("Distance: " + this.feet + " feet, " + this.inches + "
inches");
}

public void addDistance(Distance d) {


this.inches += d.inches;
this.feet += d.feet + this.inches / 12;
this.inches %= 12;
}
public void getDistance() {
System.out.println("Feet: " + this.feet + ", Inches: " + this.inches);
}
}
public class DistanceDemo {
public static void main(String[] args) {
Distance d1 = new Distance(5, 9);
Distance d2 = new Distance(3, 4);
System.out.print("Distance 1: ");
d1.displayDistance();
System.out.print("Distance 2: ");
d2.displayDistance();
d1.addDistance(d2);
System.out.print("After adding Distance 2 to Distance 1: ");
d1.displayDistance();
}
}
op
Distance 1: Distance: 5 feet, 9 inches
Distance 2: Distance: 3 feet, 4 inches
After adding Distance 2 to Distance 1: Distance: 9 feet, 1 inches
-----------------------------------------------------------------------------------
-----------------------
8. Modify the – “distance” class by creating constructor for assigning values (feet
and
inches) to the distance object. Create another object and assign second object as
reference
variable to another object reference variable. Further create a third object which
is a clone
of the first object.
class Distance implements Cloneable {
private int feet;
private int inches;
public Distance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
adjust();
}
private void adjust() {
if (inches >= 12) {
feet += inches / 12;
inches %= 12;
}
}
public void display() {
System.out.println("Distance: " + feet + " feet " + inches + " inches");
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
Distance d1 = new Distance(5, 13);
Distance d2 = new Distance(3, 11);
Distance d3 = d2;
System.out.println("Reference assignment:");
d3.display();
Distance d4 = (Distance)d1.clone();
System.out.println("Cloned object:");
d4.display();
}
}
Output:

Output:
Reference assignment:
Distance: 3 feet 11 inches
Cloned object:
Distance: 6 feet 1 inches
-----------------------------------------------------------------------------
9. Write a program to show that during function overloading, if no matching
argument is
found, then Java will apply automatic type conversions (from lower to higher data
type).

public class OverloadingDemo {


public void display(int a) {
System.out.println("Method with int argument: " + a);
}
public void display(double a) {
System.out.println("Method with double argument: " + a);
}
public void display(long a) {
System.out.println("Method with long argument: " + a);
}
public static void main(String[] args) {
OverloadingDemo obj = new OverloadingDemo();
obj.display(10);
obj.display(10.5);
obj.display(100000L);
byte b = 25;
obj.display(b);
short s = 50;
obj.display(s);
float f = 5.75f;
obj.display(f);
}
}
op
Method with int argument: 10
Method with double argument: 10.5
Method with long argument: 100000
Method with int argument: 25
Method with int argument: 50
Method with double argument: 5.75
-----------------------------------------------------------------------------------
--------------
10. Write a program to show the difference between public and private access
specifiers. The
program should also show that primitive data types are passed by value and objects
are
passed by reference and to learn use of final keyword.
class Test {
public int publicVar = 10;
private int privateVar = 20;
final int finalVar = 30;
void changeValues(int primitive, Test obj) {
primitive = 100;
obj.publicVar = 100;
}
}
public class AccessDemo {
public static void main(String[] args) {
Test t = new Test();
System.out.println("Public variable: " + t.publicVar);
System.out.println("Final variable: " + t.finalVar);
int primitive = 50;
Test obj = new Test();
System.out.println("Before - primitive: " + primitive + ", obj.publicVar: "
+ obj.publicVar);
t.changeValues(primitive, obj);
System.out.println("After - primitive: " + primitive + ", obj.publicVar: "
+ obj.publicVar);
}
}
Output:
Public variable: 10
Final variable: 30
Before - primitive: 50, obj.publicVar: 10
After - primitive: 50, obj.publicVar: 100
---------------------------------------------------------------------------
11. Write a program to show the use of static functions and to pass variable length
arguments in a function.
public class StaticAndVarargsDemo {
public static void displayMessage(String message) {
System.out.println("Message: " + message);
}
public static int sum(int... numbers) {
int total = 0;
for (int number : numbers) {
total += number;
}
return total;
}
public static void main(String[] args) {
StaticAndVarargsDemo.displayMessage("Java Programming");
int result1 = StaticAndVarargsDemo.sum(1, 2, 3);
int result2 = StaticAndVarargsDemo.sum(10, 20, 30, 40, 50);
int result3 = StaticAndVarargsDemo.sum();
System.out.println("Sum of 1, 2, 3: " + result1);
System.out.println("Sum of 10, 20, 30, 40, 50: " + result2);
System.out.println("Sum of no arguments: " + result3);
}
}
op
Message: Java Programming
Sum of 1, 2, 3: 6
Sum of 10, 20, 30, 40, 50: 150
Sum of no arguments: 0
------------------------------------------------------------------
14. Write a program to demonstrate the concept of boxing and unboxing.
public class BoxingUnboxingDemo {
public static void main(String[] args) {
int primitiveInt = 42;
Integer boxedInt = primitiveInt;
System.out.println("Boxed Integer: " + boxedInt);
double primitiveDouble = 3.14;
Double boxedDouble = primitiveDouble;
System.out.println("Boxed Double: " + boxedDouble);
Integer unboxedInt = 100;
int primitiveIntFromBoxed = unboxedInt;
System.out.println("Unboxed int: " + primitiveIntFromBoxed);
Double unboxedDouble = 2.718;
double primitiveDoubleFromBoxed = unboxedDouble;
System.out.println("Unboxed double: " + primitiveDoubleFromBoxed);
java.util.List<Integer> integerList = new java.util.ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
System.out.println("Integer List: " + integerList);
int sum = 0;
for (Integer i : integerList) {
sum += i;
}
System.out.println("Sum of Integer List: " + sum);
}
}
op
Boxed Integer: 42
Boxed Double: 3.14
Unboxed int: 100
Unboxed double: 2.718
Integer List: [1, 2, 3]
Sum of Integer List: 6

15. Create a multi-file program where in one file a string message is taken as
input from the user and the function to display the message on the screen is given
in another file (make use of Scanner package in this program).

MessageInput.java:
package message;
import java.util.Scanner;
public class MessageInput {
public static String getMessage() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your message: ");
return sc.nextLine();
}
}

MessageDisplay.java:
package message;
public class MessageDisplay {
public static void main(String[] args) {
String message = MessageInput.getMessage();
System.out.println("Your message: " + message);
}
}
Output:
Enter your message: Hello Java
Your message: Hello Java

16. Write a program to create a multilevel package and also creates a reusable
class to generate Fibonacci series, where the function to generate Fibonacci series
is given in a different file belonging to the same package.
Fibonacci.java:
package math.series;
public class Fibonacci {
public static void generate(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci series: ");
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
}
System.out.println();
}
}
TestFibonacci.java:
package math.series;
import java.util.Scanner;

public class TestFibonacci {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = sc.nextInt();
Fibonacci.generate(n);
}
}
Output:
Enter number of terms: 5
Fibonacci series: 0 1 1 2 3
17. Write a program that creates illustrates different levels of protection in
classes/subclasses belonging to same package or different packages
package pkg1;
public class SamePackageTest {
public void testAccess() {
BaseClass base = new BaseClass();
System.out.println("=== Same Package (Non-Subclass) ===");
System.out.println("Public var: " + base.publicVar);
System.out.println("Protected var: " + base.protectedVar);
System.out.println("Default var: " + base.defaultVar);
base.publicMethod();
base.protectedMethod();
base.defaultMethod();
base.accessPrivate();
}
}
package pkg2;
import pkg1.BaseClass;
public class SubClass extends BaseClass {
public void testAccess() {
System.out.println("=== Subclass (Different Package) ===");
System.out.println("Public var: " + publicVar);
System.out.println("Protected var: " + protectedVar);
publicMethod();
protectedMethod();
accessPrivate();
}
}
package pkg2;
import pkg1.BaseClass;
public class DifferentPackageTest {
public void testAccess() {
BaseClass base = new BaseClass();
System.out.println("=== Different Package (Non-Subclass) ===");
System.out.println("Public var: " + base.publicVar);
base.publicMethod();
base.accessPrivate();
}
}
package pkg2;
import pkg1.SamePackageTest;
public class MainTest {
public static void main(String[] args) {
SamePackageTest samePkg = new SamePackageTest();
samePkg.testAccess();
SubClass sub = new SubClass();
sub.testAccess();
DifferentPackageTest diffPkg = new DifferentPackageTest();
diffPkg.testAccess();
}
}
op
=== Same Package (Non-Subclass) ===
Public var: 10
Protected var: 20
Default var: 30
Public method: 10
Protected method: 20
Default method: 30
Accessing privateVar: 40
Private method: 40

=== Subclass (Different Package) ===


Public var: 10
Protected var: 20
Public method: 10
Protected method: 20
Accessing privateVar: 40
Private method: 40

=== Different Package (Non-Subclass) ===


Public var: 10
Public method: 10
Accessing privateVar: 40
Private method: 40

18. Write a program – “Divide By Zero” that takes two numbers a and b as input,
computes a/b, and invokes Arithmetic Exception to generate a message when the
denominator is zero.
import java.util.Scanner;
public class DivideByZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers (a b): ");
int a = sc.nextInt();
int b = sc.nextInt();

try {
System.out.println("Result: " + (a / b));
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed");
}
}
}
Output:
Enter two numbers (a b): 10 0
Error: Division by zero is not allowed

19. Write a program to show the use of nested try statements that emphasizes the
sequence of checking for catch handler statements.
public class NestedTry {
public static void main(String[] args) {
try {
System.out.println("Outer try block");
try {
System.out.println("Inner try block");
int result = 10 / 0;
} catch (NullPointerException e) {
System.out.println("Inner catch - NullPointer");
}
} catch (ArithmeticException e) {
System.out.println("Outer catch - ArithmeticException");
}
}
}
Output:
Outer try block
Inner try block
Outer catch - ArithmeticException

20. Write a program to create your own exception types to handle situation specific
to your application (Hint: Define a subclass of Exception which itself is a
subclass of Throwable).
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomException {


static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older");
}
System.out.println("Valid age");
}

public static void main(String[] args) {


try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
Output:
Caught exception: Age must be 18 or older

21. Write a program to demonstrate priorities among multiple threads.


class MyThread extends Thread {
public MyThread(String name) {
super(name);
}

public void run() {


System.out.println(getName() + " running with priority " + getPriority());
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
Output:
Thread-2 running with priority 10
Thread-1 running with priority 1

22. Write a program to demonstrate different mouse handling events like mouse
Clicked( ), mouse Entered ( ), mouse Exited ( ), mouse Pressed( ), mouse
Released( ) & mouse Dragged( ).
import java.awt.*;
import java.awt.event.*;

public class MouseEventsDemo extends Frame implements MouseListener {


public MouseEventsDemo() {
addMouseListener(this);
setSize(300, 200);
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


System.out.println("Mouse clicked at " + e.getX() + ", " + e.getY());
}

public void mouseEntered(MouseEvent e) {


System.out.println("Mouse entered");
}

public void mouseExited(MouseEvent e) {


System.out.println("Mouse exited");
}

public void mousePressed(MouseEvent e) {


System.out.println("Mouse pressed");
}

public void mouseReleased(MouseEvent e) {


System.out.println("Mouse released");
}

public static void main(String[] args) {


new MouseEventsDemo();
}
}
23. Write a program to demonstrate different keyboard handling events.
import java.awt.*;
import java.awt.event.*;

public class KeyboardEventsDemo extends Frame implements KeyListener {


public KeyboardEventsDemo() {
addKeyListener(this);
setSize(300, 200);
setVisible(true);
}

public void keyPressed(KeyEvent e) {


System.out.println("Key pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


System.out.println("Key released: " + e.getKeyChar());
}

public void keyTyped(KeyEvent e) {


System.out.println("Key typed: " + e.getKeyChar());
}

public static void main(String[] args) {


new KeyboardEventsDemo();
}
}

You might also like