[Go to site: main page, start]

0% found this document useful (0 votes)
14 views27 pages

Java Lab Programs - Reference1.0

The document outlines practical Java programming exercises for a B.Sc. degree in Computer Science, focusing on various topics such as file creation, prime number generation, matrix multiplication, character counting, random number generation, string manipulation, multi-threading, and exception handling. Each exercise includes an aim, algorithm, and Java program code to demonstrate the concepts. The document serves as a practical guide for students to implement and understand Java programming techniques.
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)
14 views27 pages

Java Lab Programs - Reference1.0

The document outlines practical Java programming exercises for a B.Sc. degree in Computer Science, focusing on various topics such as file creation, prime number generation, matrix multiplication, character counting, random number generation, string manipulation, multi-threading, and exception handling. Each exercise includes an aim, algorithm, and Java program code to demonstrate the concepts. The document serves as a practical guide for students to implement and understand Java programming techniques.
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

Hidnustan College of Arts and Science

&

UNIVERSITY OF MADRAS

[Link]. DEGREE PROGRAMME IN COMPUTER


SCIENCE WITH ARTIFICIAL INTELLIGENCE
[Link]. DEGREE PROGRAMME IN COMPUTER
SCIENCE WITH DATA SCIENCE

Year: I Semester: II

Java Programming Practical


Program Reference
1
Creating and store java file
1. Create a folder(directory) on the D drive
2. Open notepad and type the Java program and save it on your directory
3. Open Command prompt –in the search bar type cmd and enter, you can
have the command prompt.
4. You can see the command prompt like,
C:\Users\HP>
5. Type like C:\Users\HP>d: press enter key
6. Now you can have D:>
7. Type cd your directory name press enter key
8. Now you can have your directory as D:>Mohan:>
9. Now compile and execute your java program as below:
Execution procedure of a Java program
1. D:> Mohan:>javac Java_FileName.java then press enter key.
2. If there is any error, it list out all, you may correct all errors and save the
program and then compile it.
3. If no errors, the byte code is created and stored in a .class file, then
execute it as follows:
4. D:> Mohan:>java Java_FileName, if there is no runtime error –the
program is executed, you may give input, if need, it gives output.

2
To find the Prime Number Series

Ex. No. 1:
Date:
Aim: To Write an algorithm and Java program that prompts the user for an integer and then prints
out all the prime numbers up to that Integer.
Algorithm:
1. Start
2. Read an integer n
3. For each number i from 2 to n
4. Check if i is divisible by any number from 2 to i − 1
5. If not divisible, print i (it is prime)
6. Stop
Program:
import [Link];
public class PrimeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int n = [Link]();
[Link]("Prime numbers up to " + n + " are:");
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
[Link](i + " ");
}
}
}
Input

Output

Result: The above program is executed for the given input and got the specified output.

3
Matrix Multiplication
Ex. No. 2:
Date:
Aim: Write a Java program to multiply two given matrices.
Algorithm:
1. Start
2. Read number of rows and columns of two matrices
3. Read elements of first matrix A
4. Read elements of second matrix B
5. Multiply matrix A and B and store result in C
6. Display matrix C
7. Stop
Program
import [Link];
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int a[][] = new int[2][2];
int b[][] = new int[2][2];
int c[][] = new int[2][2];
[Link]("Enter elements of Matrix A:");
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
a[i][j] = [Link]();
[Link]("Enter elements of Matrix B:");
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
b[i][j] = [Link]();
// Multiply matrices
for(int i=0; i<2; i++) {
for(int j=0; j<2; j++) {
c[i][j] = 0;
for(int k=0; k<2; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
[Link]("Result Matrix:");
for(int i=0; i<2; i++) {

4
for(int j=0; j<2; j++) {
[Link](c[i][j] + " ");
}
[Link]();
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

5
Count Characters, Words and Lines of a Given Text
Ex. No. 3:
Date:
Aim: To Write a Java program that displays the number of characters, words and lines in a text.
Algorithm:
1. Start
2. Read a text from the user
3. Count the number of characters
4. Count the number of words
5. Count the number of lines
6. Display the counts
7. Stop
Program
import [Link];
public class CountText {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter text (type 'end' to finish):");
int characters = 0;
int words = 0;
int lines = 0;
while (true) {
String line = [Link]();
if ([Link]("end"))
break;
lines++;
characters = characters + [Link]();
String w[] = [Link](" ");
words = words + [Link];
}
[Link]("Lines: " + lines);
[Link]("Words: " + words);
[Link]("Characters: " + characters);
}
}
Input:

Output:

Result: The above program is executed for the given input and got the specified output.

6
Random Number Generation
Ex. No. 4:
Date:
Aim: Generate random numbers between two given limits using Random class and print messages
according to the range of the value generated.
Algorithm:
1. Start
2. Read the lower limit and upper limit
3. Generate a random number between the two limits
4. Check the range of the number
5. Print a suitable message
6. Stop
Program
import [Link];
import [Link];
public class RandomRange {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Random r = new Random();
[Link]("Enter lower limit: ");
int low = [Link]();
[Link]("Enter upper limit: ");
int high = [Link]();
int num = [Link](high - low + 1) + low;
[Link]("Random number: " + num);
if (num < (low + high) / 2)
[Link]("Number is in the lower range");
else
[Link]("Number is in the higher range");
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

7
String Manipulation by Character Array
Ex. No. 5:
Date:
Aim: To write a Java program that to do String Manipulation using Character Array and perform the
following string operations:
a) String length
b) Finding a character at a particular position
c) Concatenating two strings

Algorithm
1. Start
2. Read first string and convert it to a character array
3. Read second string and convert it to a character array
4. Find the length of the first string
5. Find the character at a given position
6. Concatenate both character arrays
7. Display the results
8. Stop

Java Program
import [Link];
public class CharArrayStringOps {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

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


char s1[] = [Link]().toCharArray();

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


char s2[] = [Link]().toCharArray();

// a) String length
int length = [Link];
[Link]("Length of first string: " + length);

// b) Character at a particular position


[Link]("Enter position to find character: ");
int pos = [Link]();

if (pos >= 0 && pos < length)


[Link]("Character at position " + pos + ": "
+ s1[pos]);
else
[Link]("Invalid position");

// c) Concatenation
char result[] = new char[[Link] + [Link]];

int i = 0;

8
for (char c : s1)
result[i++] = c;

for (char c : s2)


result[i++] = c;

[Link]("Concatenated String: ");


[Link](result);
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

9
String Manipulationn by String class
Ex. No. 6:
Date:
Aim: Write a program to perform the following string operations using String class:
a) String Concatenation
b) Search a substring
c) To extract substring from given string

Algorithm
1. Start
2. Read two strings
3. Concatenate the two strings
4. Read a substring to search
5. Check whether the substring is present
6. Extract a substring using start and end index
7. Display the results
8. Stop

Java Program
import [Link];

public class StringOperations {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

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


String s1 = [Link]();

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


String s2 = [Link]();

// a) String Concatenation
String concat = s1 + s2;
[Link]("Concatenated String: " + concat);

// b) Search a substring
[Link]("Enter substring to search: ");
String search = [Link]();

if ([Link](search))
[Link]("Substring found");
else
[Link]("Substring not found");

// c) Extract substring
[Link]("Enter start index: ");
int start = [Link]();

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


int end = [Link]();

10
[Link]("Extracted Substring: " +
[Link](start, end));
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

11
String Manipulationn by StringBuffer class
Ex. No. 7:
Date:
Aim: Write a program to perform string operations using StringBuffer class:
a) Length of a string
b) Reverse a string
c) Delete a substring from the given string
Algorithm
1. Start
2. Read a string from the user
3. Create a StringBuffer object
4. Find the length of the string
5. Reverse the string
6. Delete a substring using start and end index
7. Display the results
8. Stop

Java Program
import [Link];

public class StringBufferOperations {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

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


StringBuffer sb = new StringBuffer([Link]());

// a) Length of string
[Link]("Length: " + [Link]());

// b) Reverse string
[Link]("Reversed: " + [Link]());

// c) Delete substring
[Link]("Enter start index: ");
int start = [Link]();

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


int end = [Link]();

[Link](start, end);
[Link]("After deletion: " + sb);
}
}
Input

Output

Result: The above program is executed for the given input and got the specified output.

12
Implementation of Multi-threaded application

Ex. No. 8:
Date:
Aim: Write a java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread computes
the square of the number and prints. If the value is odd, the third thread will print the value of cube
of the number

Algorithm
1. Start
2. Create a thread to generate a random number every 1 second
3. If the number is even, start second thread to find square
4. If the number is odd, start third thread to find cube
5. Display the result
6. Repeat the process
7. Stop

Java Program
import [Link];
class NumberGenerator extends Thread {
public void run() {
Random r = new Random();

while (true) {
int num = [Link](10); // 0 to 9
[Link]("\nGenerated Number: " + num);

if (num % 2 == 0)
new Square(num).start();
else
new Cube(num).start();

try {
[Link](1000); // 1 second delay
} catch (InterruptedException e) {
}
}
}
}

class Square extends Thread {


int n;

Square(int n) {
this.n = n;
}

public void run() {

13
[Link]("Square: " + (n * n));
}
}

class Cube extends Thread {


int n;

Cube(int n) {
this.n = n;
}

public void run() {


[Link]("Cube: " + (n * n * n));
}
}

public class MultiThreadApplication {


public static void main(String[] args) {
new NumberGenerator().start();
}
}

Input

Output

Result: The above program is executed for the given input and got the
specified output.

14
Implementation of Asynchronous Multi-threaded application
Ex. No. 9:
Date:
Aim: Write a simple threading program which uses the same method asynchronously to print the
numbers 1 to 10 using Thread1 and to print 90 to 100 using Thread2

Algorithm
1. Start
2. Create a class that implements Runnable
3. Use the same run() method for both threads
4. Thread1 prints numbers from 1 to 10
5. Thread2 prints numbers from 90 to 100
6. Start both threads to run asynchronously
7. Stop

Java Program
class PrintNumbers implements Runnable {
int start, end;

PrintNumbers(int start, int end) {


[Link] = start;
[Link] = end;
}

public void run() {


for (int i = start; i <= end; i++) {
[Link]([Link]().getName() + "
: " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {

Thread t1 = new Thread(new PrintNumbers(1, 10), "Thread1");


Thread t2 = new Thread(new PrintNumbers(90, 100),
"Thread2");

[Link]();
[Link]();
}
}
Input

Output
Result: The above program is executed for the given input and got the specified output.

15
Exception Handling

Ex. No. 10:


Date:
Aim: Write a program to demonstrate the use of following exceptions.
a) Arithmetic Exception
b) Number Format Exception
c) Array Index Out of Bound Exception
d) Negative Array Size Exception

Algorithm
1. Start
2. Perform division by zero to cause Arithmetic Exception
3. Convert a non-numeric string to number to cause Number Format Exception
4. Access an invalid array index to cause Array Index Out of Bound Exception
5. Create an array with negative size to cause Negative Array Size Exception
6. Catch and display messages for each exception
7. Stop

Java Program
public class ExceptionDemo {
public static void main(String[] args) {

// a) Arithmetic Exception
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurred");
}

// b) Number Format Exception


try {
int n = [Link]("abc");
} catch (NumberFormatException e) {
[Link]("Number Format Exception occurred");
}

// c) Array Index Out of Bound Exception


try {
int arr[] = {1, 2, 3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out Of Bound Exception
occurred");
}

// d) Negative Array Size Exception


try {
int arr[] = new int[-2];

16
} catch (NegativeArraySizeException e) {
[Link]("Negative Array Size Exception
occurred");
}
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

17
File Handling in Java

Ex. No. 11:


Date:
Aim: Write a Java program that reads on file name from the user, then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file and
the length of the file in bytes?

Algorithm
1. Start
2. Read file name from the user
3. Create a File object using the file name
4. Check whether the file exists
5. Check whether the file is readable
6. Check whether the file is writable
7. Display the file type (file or directory)
8. Display the file length in bytes
9. Stop
Java Program
import [Link];
import [Link];

public class FileDetails {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter file name: ");


String fileName = [Link]();

File file = new File(fileName);

if ([Link]()) {
[Link]("File exists: Yes");
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());

if ([Link]())
[Link]("Type: File");
else
[Link]("Type: Directory");

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


} else {
[Link]("File does not exist");
}
}
}
Input
18
Output

Result: The above program is executed for the given input and got the specified output.

19
GUI Programming in Java

Ex. No. 12:


Date:
Aim: Write a program to accept a text and change its size and font. Include bold italic options. Use
frames and controls.

Algorithm
1. Start
2. Create a Frame
3. Add a TextField to enter text
4. Add Buttons for Bold, Italic, and Normal
5. When a button is clicked, change the font style and size
6. Display the updated text
7. Stop

Java Program
import [Link].*;
import [Link].*;

public class FontStyleDemo extends Frame implements ActionListener {

TextField tf;
Button bold, italic, normal;

FontStyleDemo() {

tf = new TextField("Enter Text Here");


[Link](50, 60, 200, 30);

bold = new Button("Bold");


italic = new Button("Italic");
normal = new Button("Normal");

[Link](40, 120, 50, 30);


[Link](110, 120, 50, 30);
[Link](180, 120, 60, 30);

add(tf);
add(bold);
add(italic);
add(normal);

[Link](this);
[Link](this);
[Link](this);

setSize(300, 200);
setLayout(null);
setVisible(true);

20
}

public void actionPerformed(ActionEvent e) {

if ([Link]() == bold)
[Link](new Font("Arial", [Link], 16));

if ([Link]() == italic)
[Link](new Font("Arial", [Link], 16));

if ([Link]() == normal)
[Link](new Font("Arial", [Link], 16));
}

public static void main(String[] args) {


new FontStyleDemo();
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

21
Mouse Event Handling in Java

Ex. No. 13:


Date:
Aim: Write a Java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired. (Use adapter classes).

Algorithm
1. Start
2. Create a Frame
3. Attach a MouseAdapter to handle mouse events
4. When a mouse event occurs, store the event name
5. Display the event name at the center of the window
6. Stop

Java Program
import [Link].*;
import [Link].*;

public class MouseEventsDemo extends Frame {

String message = "";

MouseEventsDemo() {

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {


message = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent e) {


message = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent e) {


message = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


message = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


message = "Mouse Exited";
repaint();

22
}
});

setSize(400, 300);
setVisible(true);
}

public void paint(Graphics g) {


[Link](message, 160, 150); // center position
}

public static void main(String[] args) {


new MouseEventsDemo();
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

23
Simple Calculator using GUI with Grid Layout

Ex. No. 14:


Date:
Aim: Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +, -,*, % operations. Add a text field to display the result. Handle any
possible exceptions like divide by zero.

Algorithm (Simple)
1. Start
2. Create a Frame
3. Add a TextField to display input and result
4. Arrange digit and operator buttons using GridLayout
5. Perform operations: + , - , * , %
6. Handle divide/modulo by zero using exception handling
7. Display the result
8. Stop

Java Program (Simple Calculator using AWT)


import [Link].*;
import [Link].*;

public class SimpleCalculator extends Frame implements ActionListener {

TextField tf;
String num1 = "", num2 = "", op = "";

SimpleCalculator() {

tf = new TextField();
[Link](false);
add(tf, [Link]);

Panel p = new Panel();


[Link](new GridLayout(4, 4));

String buttons[] = {
"1","2","3","+",
"4","5","6","-",
"7","8","9","*",
"0","%","=","C"
};

for (String s : buttons) {


Button b = new Button(s);
[Link](this);
[Link](b);
}

add(p, [Link]);

24
setSize(300, 300);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {

String s = [Link]();

if ([Link]("C")) {
[Link]("");
num1 = num2 = op = "";
}
else if ([Link]("=")) {
try {
int a = [Link](num1);
int b = [Link](num2);
int result = 0;

switch (op) {
case "+": result = a + b; break;
case "-": result = a - b; break;
case "*": result = a * b; break;
case "%":
if (b == 0) throw new ArithmeticException();
result = a % b;
break;
}
[Link]("" + result);
} catch (ArithmeticException ex) {
[Link]("Error");
}
}
else if ("+-*%".contains(s)) {
num1 = [Link]();
op = s;
[Link]("");
}
else {
[Link]([Link]() + s);
num2 = [Link]();
}
}

public static void main(String[] args) {


new SimpleCalculator();
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

25
Simulation of Traffic Light Controller
Ex. No. 15:
Date:
Aim: Write a Java program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with “stop” or “ready” or “go” should appear above the buttons in a selected color. Initially there is
no message shown.
Algorithm
1. Start
2. Create a Frame
3. Add a Label at the top (initially empty)
4. Add three Radio Buttons (Red, Yellow, Green) using CheckboxGroup
5. When a button is selected:
o Red → show STOP in red
o Yellow → show READY in yellow
o Green → show GO in green
6. Stop

Java Program
import [Link].*;
import [Link].*;

public class TrafficLightDemo extends Frame implements ItemListener


{

Label msg;
Checkbox red, yellow, green;
CheckboxGroup group;

TrafficLightDemo() {

msg = new Label("");


[Link]([Link]);
[Link](new Font("Arial", [Link], 20));
add(msg, [Link]);

group = new CheckboxGroup();

red = new Checkbox("Red", group, false);


yellow = new Checkbox("Yellow", group, false);
green = new Checkbox("Green", group, false);

Panel p = new Panel();


[Link](red);
[Link](yellow);
[Link](green);
add(p, [Link]);

[Link](this);

26
[Link](this);
[Link](this);

setSize(300, 200);
setVisible(true);
}

public void itemStateChanged(ItemEvent e) {

if ([Link]()) {
[Link]("STOP");
[Link]([Link]);
}
else if ([Link]()) {
[Link]("READY");
[Link]([Link]);
}
else if ([Link]()) {
[Link]("GO");
[Link]([Link]);
}
}

public static void main(String[] args) {


new TrafficLightDemo();
}
}

Input

Output

Result: The above program is executed for the given input and got the specified output.

27

You might also like