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

Java Programming Lab Exercises Guide

The document is a collection of Java lab exercises designed to teach programming concepts such as printing messages, arithmetic operations, area calculations, recursion, sorting algorithms, and control statements. Each exercise includes objectives, sample code, and expected output. The exercises range from basic to intermediate programming tasks, providing practical examples for learners.

Uploaded by

st804055
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)
5 views32 pages

Java Programming Lab Exercises Guide

The document is a collection of Java lab exercises designed to teach programming concepts such as printing messages, arithmetic operations, area calculations, recursion, sorting algorithms, and control statements. Each exercise includes objectives, sample code, and expected output. The exercises range from basic to intermediate programming tasks, providing practical examples for learners.

Uploaded by

st804055
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

INDEX

Sr No. Objective Page No. Date Signature

1 Print a welcome message to the console 1

2 Perform addition and display the result 2

3 Calculate and display the area of a circle 3

4 Calculate and display the area of a triangle 4-5

5 Calculate and display the factorial 5

6 Reverse of a String using Recursion 6-7

7 Merge Sort algorithm through a working Java program 7-9

8 The provided Java program, OctalToHexa 10-11

9 The provided Java program, named Diamond 11-13

10 The provided Java program, named Prime 14-15

11 Program to using If-else statement 15-16

12 Program to using Switch Statement 16-17

13 Program to using Loop Statement 17-18

14 Program to using Java Break Statement 18-19

15 Program to using Java Continue Statement 19-20

16 Program to using the [Link]() Method 21

17 Program to loop is to find the sum of natural numbers 22

18 Program to sorted array using loop 23-24

19 Program to count the total characters in a string 24-25

20 Program to using Binary Search 25-26

21 Program to using Java String to int 26-27

22 Program to using Bitwise Operator 27-28

23 Program to using Object Comparison Example 29

24 Program to using Create Object Example 30

25 Program to using Create Object Example 31

Page 0 of 32
LAB EXERCISE #1

Objective(s):
The purpose of this program is to demonstrate the use of the [Link] statement to
display a multi-line welcome message on the console. It serves as a simple example for
beginners to understand the basic syntax of printing output in Java.

❖ This Java program is to print a welcome message to the console.

import [Link].*;

class BCA {
public static void main(String[] args)
{
[Link]("Welcome");
[Link]("To");
[Link]("VBSP University Jaunpur");
}
}

Output:
Welcome
To
VBSP University Jaunpur

Page 1 of 32
LAB EXERCISE #2

Objective(s):
The program is a simple demonstration of variable declaration, addition operation, and output
display in Java. It's designed to show how to declare variables, perform a basic arithmetic
operation, and print the results to the console.

❖ Write Java program is to perform addition and display the result.

import [Link].*;

class BCA {
public static void main(String[] args)
{
int num1 = 10, num2 = 20, sum;
[Link]("The addition of ");
[Link](
num1 + " and " + num2 + " is:");
[Link](num1 + num2);
}
}

OUTPUT:
The addition of 10 and 20 is:
30

Page 2 of 32
LAB EXERCISE #3

Objective(s):
The program will prompt the user to enter the radius of the circle, calculate the area based on
the input, and then display the result.

❖ Write this Java program is to calculate and display the area of a circle.

import [Link];
class AreaOfCircle
{
public static void main(String args[])
{
Scanner s= new Scanner([Link]);
[Link]("Enter the radius:");
double r= [Link]();
double area=(22*r*r)/7 ;
[Link]("Area of Circle is: " + area);
}
}

OUTPUT:
Enter the radius :
7
Area of circle : 154.0

Page 3 of 32
LAB EXERCISE #4

Objective(s):
The program will prompt the user to enter the width and height of the triangle, calculate the
area based on the input, and then display the result.

❖ Write a Program this Java program is to calculate and display the area
of a triangle.

import [Link];
class AreaOfTriangle
{
public static void main(String args[])
{
Scanner s= new Scanner([Link]);
[Link]("Enter the width of the Triangle:");
double b= [Link]();
[Link]("Enter the height of the Triangle:");
double h= [Link]();
[Link]("Area of Triangle is: " + area);
}
}

OUTPUT:
Enter the width of the Triangle:
10
Enter the height of the Triangle:
20

Page 4 of 32
Area of Triangle is:100.0

LAB EXERCISE #5

Objective(s):
The program's primary objective is to showcase a simple algorithm for computing the factorial
of a number using a loop, offering an example of iterative computation in Java. In this specific
case, it calculates the factorial of 5 and prints the result, which is 120 (since 5! = 5 x 4 x 3 x 2
x 1 = 120).

❖ Write the provided Java program is to calculate and display the


factorial.

class Factoral
{
public static void main(String arg[])
{
int n=5,fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
[Link]("factoral="+fact);
}

OUTPUT:
factorial =120

Page 5 of 32
LAB EXERCISE #6

Objective(s):
The program prompts the user to enter a string, then it calculates the reversed version of the
string and prints it to the console.

❖ Write a Java program, named Reverse of a String using Recursion.

class StringReverse
{
void reverse(String str)
{
if ((str==null)||([Link]() <= 1))
[Link](str);
else
{
[Link]([Link]([Link]()-1));
reverse([Link](0,[Link]()-1));
}
}
public static void main(String[] args)
{
String str = "Vaibhav";
StringReverse obj = new StringReverse();
[Link](str);
}
}

Page 6 of 32
OUTPUT:
vahbiaV

LAB EXERCISE #7

Objective(s):
The provided Java program is to demonstrate the implementation of the Merge Sort algorithm
for sorting an array of integers. Merge Sort is a divide-and-conquer sorting algorithm known
for its stability and efficiency.

❖ Write a Merge Sort algorithm through a working Java program.

import [Link];
public class MSort
{
public static void merge(int a[],int l,int m,int h)
{
int i, j,c=l;
int b[]=new int[h+1];
for(i = l,j = m+1; i<=m && j<=h; c++)
{
if(a[i] <= a[j])
b[c] = a[i++];
else
b[c] = a[j++];
}
while(i <= m )

Page 7 of 32
b[c++] = a[i++];
while(j<=h)
b[c++] = a[j++];
for(i = l ; i <= h; i++)
a[i] = b[i];
}
public static void Sort(int a[],int l,int h)
{
if(l<h)
{
int m=(l+h)/2;
Sort(a,l,m);
Sort(a,m+1,h);
merge(a,l,m,h);
}
}
public static void printarray(int a[])
{
for(int i=0; i < [Link]; i++)
{
[Link](a[i]+" ");
}
}
public static void main(String[] args)
{
int n, res,i;
Scanner s = new Scanner([Link]);

Page 8 of 32
[Link]("Enter number of elements in the array:");
n = [Link]();
int a[] = new int[n];
[Link]("Enter "+n+" elements ");
for( i=0; i < n; i++)
{
a[i] = [Link]();
}
[Link]( "elements in array ");
printarray(a);
Sort(a,0,n-1);
[Link]( "\nelements after sorting");
printarray(a);
}
}

OUTPUT:
Enter number of elements in the array:5
Enter 5 elements
12
4
0
5
3
elements in array
12 4 0 5 3
elements after sorting
0 3 4 5 12

Page 9 of 32
LAB EXERCISE #8

Objective(s):
The program aims to convert an octal number provided by the user into its corresponding
hexadecimal representation. It demonstrates the conversion process from octal to decimal and
then from decimal to hexadecimal. The use of functions enhances code modularity and
readability.

❖ Write the provided Java program, OctalToHexa.

import [Link];
class OctalToHexa
{
public static void main(String arg[])
{
int oct, dec=0, i=0, t;
Scanner sc = new Scanner([Link]);
[Link]("Enter Octal Number : ");
oct = [Link]();
while(oct != 0)
{
dec =dec + (oct%10) *(int)[Link](8, i);
i++;
oct = oct/10;
}
String hex=hexadecimal(dec);
[Link]("Hexadecimal number is :"+hex);
}

Page 10 of 32
static String hexadecimal(int q)
{
char a[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int rem;
String hexadec="";
while(q != 0)
{
rem=q%16;
hexadec= a[rem] + hexadec;
q= q/16;
}
return hexadec;
}
}

OUTPUT:

Enter Octal Number:


16
Hexadecimal number is:
E

Enter Octal Number:


18
Hexadecimal number is:
10

Page 11 of 32
LAB EXERCISE #9

Objective(s):
The program's objective is to take user input for the size of the diamond and a symbol, and then
use nested loops to construct and display a diamond pattern on the console. This type of
program is often used for pattern-based output and is common in introductory programming
exercises for learning loop structures and pattern printing in Java.

❖ Write the provided Java program, named Diamond.

import [Link];
public class Diamond
{
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("Enter N : ");
int n=[Link]();
[Link]("Enter Symbol : ");
char c = [Link]().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
[Link](" ");
}
for(int j=1;j<=i*2-1;j++)
{

Page 12 of 32
[Link](c);
}
[Link]();
}
for(int i=n-1;i>0;i--)
{
for(int j=1;j<=n-i;j++)
{
[Link](" ");
}
for(int j=1;j<=i*2-1;j++)
{
[Link](c);
}
[Link]();
}
}

OUTPUT:
*
***
*****
*******
*********

Page 13 of 32
LAB EXERCISE #10

Objective(s):
The program aims to determine and display whether a given number is prime or not. It does so
by counting the factors of the number and checking if the count is exactly 2. The program is
designed to showcase a simple prime-checking algorithm and the use of a separate method for
modularity.

❖ Write the provided Java program, named Prime.

import [Link];
class Prime
{
public static void main(String arg[])
{
[Link]("Enter a number ");
Scanner sc=new Scanner([Link]);
int n=[Link]();
primeCal(n);
}
static void primeCal(int num)
{
int count=0;
for(int i=1;i<=num;i++)
{
if(num%i==0)
{
count++;

Page 14 of 32
}
}
if(count==2)
[Link]("prime number ");
else
[Link]("Not a prime number ");
}
}

OUTPUT:
Enter a number
7
prime number

LAB EXERCISE #11

Objective(s):
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.

❖ Write the Program to using If-else statement.

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;

Page 15 of 32
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}

OUTPUT:

x + y is greater than 20

LAB EXERCISE #12

Objective(s):
Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances
the readability of the program.

❖ Write the Program to using Switch Statement.


public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
Page 16 of 32
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}

OUTPUT:
2

LAB EXERCISE #13

Objective(s):
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.

❖ Write the Program to using Loop Statement.

public class Calculattion {


public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++) {

Page 17 of 32
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}

OUTPUT:
The sum of first 10 natural numbers is 55

LAB EXERCISE #14

Objective(s):
The break statement is used to break the current flow of the program and transfer the control
to the next statement outside a loop or switch statement. However, it breaks only the inner loop
in the case of the nested loop.

❖ Write the Program to using Java Break Statement.

public class BreakExample {

public static void main(String[] args) {


for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
}
Page 18 of 32
}
}
}

OUTPUT:
0
1
2
3
4
5
6

LAB EXERCISE #15

Objective(s):
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.

❖ Write the Program to using Java Continue Statement.

public class ContinueExample {

public static void main(String[] args) {


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

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


Page 19 of 32
if(j == 4) {
continue;
}
[Link](j);
}
}
}
}

OUTPUT:

0
1
2
3
5
1
2
3
5
2
3
5

Page 20 of 32
LAB EXERCISE #16

Objective(s):
In Java programming, we often required to generate random numbers while we develop
applications. Many applications have the feature to generate numbers randomly, such as to
verify the user many applications use the OTP.

❖ Write the Program to using the [Link]() Method.

import [Link];
public class RandomNumberExample1
{
public static void main(String args[])
{
[Link]("1st Random Number: " + [Link]());
[Link]("2nd Random Number: " + [Link]());
[Link]("3rd Random Number: " + [Link]());
[Link]("4th Random Number: " + [Link]());
}
}

OUTPUT:
1st Random Number: 0.17434160924512265
2nd Random Number: 0.4297410090709448
3rd Random Number: 0.4828656381344487
4th Random Number: 0.13267917059488898

Page 21 of 32
LAB EXERCISE #17

Objective(s):
The natural numbers are the numbers that include all the positive integers from 1 to infinity.
For example, 1, 2, 3, 4, 5, ......, n. When we add these numbers together, we get the sum of
natural numbers

❖ Write the Program to using Java for loop is the easiest way to find the
sum of natural numbers.

public class SumOfNaturalNumber1


{
public static void main(String[] args)
{
int i, num = 10, sum = 0;
for(i = 1; i <= num; ++i)
{
sum = sum + i;
}
[Link]("Sum of First 10 Natural Numbers is = " + sum);
}
}

OUTPUT:
Sum of First 10 Natural Numbers is = 55

Page 22 of 32
LAB EXERCISE #18

Objective(s):
In the following program, we have defined an array of type integer. After that, we have invoked
the sort() method of the Arrays class and parses the array to be sort. For printing the sorted
array, we have used for loop.

❖ Write the Program to sorted array using loop.

import [Link];
public class SortArrayExample1
{
public static void main(String[] args)
{
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
[Link](array);
[Link]("Elements of array sorted in ascending order: ");
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}
}
}

OUTPUT:
Array elements in ascending order:
5
12

Page 23 of 32
22
23
34
67
90
109

LAB EXERCISE #19

Objective(s):
In this program, we need to count the number of characters present in the string:
The best of both worlds
To count the number of characters present in the string, we will iterate through the string and
count the characters. In above example, total numbers of characters present in the string are 19.

❖ Write the Program to count the total number of characters in a string.

public class CountCharacter


{
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;

//Counts each character except space


for(int i = 0; i < [Link](); i++) {
if([Link](i) != ' ')
count++;

Page 24 of 32
}
[Link]("Total number of characters in a string: " + count);
}
}

OUTPUT:

Total number of characters in a string: 19

LAB EXERCISE #20

Objective(s):
Binary search is used to search a key element from multiple elements. Binary search is faster
than linear [Link] case of binary search, array elements must be in ascending order. If you
have unsorted array, you can sort the array using [Link](arr) method.

❖ Write the Program to using Binary Search.

class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
[Link]("Element is found at index: " + mid);

Page 25 of 32
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
[Link]("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=[Link]-1;
binarySearch(arr,0,last,key);
}
}

OUTPUT:
Element is found at index: 2

LAB EXERCISE #21

Objective(s):
We can convert String to an int in java using [Link]() method. To convert String into
Integer, we can use [Link]() method which returns instance of Integer class.

Page 26 of 32
❖ Write the Program to using Java String to int.

public class StringToIntExample1{


public static void main(String args[])
{
String s="200";
int i=[Link](s);
[Link](i);
}
}

OUTPUT:
200

LAB EXERCISE #22

Objective(s):
Bitwise Operator: Bitwise XOR operator is used to swap two numbers. It is represented by the
symbol (^). It compares bits of two operands and returns false or 0 if they are equal and returns
true or 1 if they are not equal.

❖ Write the Program to using Bitwise Operator.


import [Link];
public class SwapTwoNumbersExample1
{
public static void main(String args[])
{

Page 27 of 32
int a, b;
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
a = [Link]();
[Link]("Enter the second number: ");
b = [Link]();
[Link]("Before swapping:");
[Link]("a = " +a +", b = " +b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
[Link]("After swapping:");
[Link]("a = " +a +", b = " +b);
}
}

OUTPUT:
Enter the first number: 5
Enter the second number: 9
Before swapping:
a = 5, b = 9
After swapping:
a = 9, b = 5

Page 28 of 32
LAB EXERCISE #23

Objective(s):
The equals() method of the Object class compare the equality of two objects. The two objects
will be equal if they share the same memory address.

❖ Write the Program to using Object Comparison Example.

public class ObjectComparisonExample


{
public static void main(String[] args)
{
Double x = new Double(123.45555);
Long y = new Long(9887544);
[Link]("Objects are not equal, hence it returns " + [Link](y));
[Link]("Objects are equal, hence it returns " + [Link](123.45555));
}
}

OUTPUT:
Objects are not equal, hence it returns false
Objects are equal, hence it returns true

Page 29 of 32
LAB EXERCISE #24

Objective(s):
The objective of the Java program is to demonstrate how to create an object of a class and
invoke a method using that object.

❖ Write the Program to using Create Object Example.

public class CreateObjectExample1


{
void show()
{
[Link]("Welcome to BCA Department");
}
public static void main(String[] args)
{
CreateObjectExample1 obj = new CreateObjectExample1();
[Link]();
}
}

OUTPUT:

Welcome to BCA Department

Page 30 of 32
LAB EXERCISE #25

Objective(s):
The objective of the Java program is to demonstrate exception handling using a try-catch
block. Specifically, the program attempts to perform a division operation (int data=100/0;)
inside the try block, which would result in an ArithmeticException due to dividing by zero.

❖ Write the Program to using Create Object Example.

public class JavaExceptionExample{


public static void main(String args[]){
try{
int data=100/0;
}
catch(ArithmeticException e){[Link](e);}
[Link]("rest of the code...");
}
}

OUTPUT:

Exception in thread main [Link]:/ by zero


rest of the code...

Page 31 of 32

You might also like