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

Java Programs Part B 1 to 10 1

The document contains a series of Java lab programs for BCA 2nd semester students, covering various topics such as string manipulation, exception handling, user-defined exceptions, GUI creation, applets, and synchronized threads for the producer-consumer problem. Each program is accompanied by its respective file name and demonstrates specific Java functionalities. The content is structured in parts, each focusing on different programming concepts and practical implementations.

Uploaded by

kappekariya
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)
7 views13 pages

Java Programs Part B 1 to 10 1

The document contains a series of Java lab programs for BCA 2nd semester students, covering various topics such as string manipulation, exception handling, user-defined exceptions, GUI creation, applets, and synchronized threads for the producer-consumer problem. Each program is accompanied by its respective file name and demonstrates specific Java functionalities. The content is structured in parts, each focusing on different programming concepts and practical implementations.

Uploaded by

kappekariya
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
You are on page 1/ 13

JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-1.Write a Java Program to demonstrate String Methods


used for manipulating strings like accessing, inserting, modifying and
appending*/
//File Name: StringDemo.java
import java.lang.String;
public class StringDemo
{
public static void main(String[] args)
{
String str = "Java is Good,";

char ch = str.charAt(8);
System.out.println("Character at index 8: " + ch);

StringBuffer sb = new StringBuffer(str);


sb.insert(8, "very ");
System.out.println("After insertion: " + sb.toString());

String str1 = sb.toString().replace("Good", "Best");


System.out.println("After modification: " + str1);

str1 = str1.concat(" Enjoy coding!");


System.out.println("After appending: " + str1);
}
}

1|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-2. Java program to for the creation of Java Bulit-in exceptions*/


//File Name : ExceptionDemo.java
public class ExceptionDemo
{
public static void main(String[] args)
{
// 1. ArithmeticException
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}

// 2. ArrayIndexOutOfBoundsException
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}

// 3. NullPointerException
try {
String text = null;
System.out.println(text.length()); // Calling method on null
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}

// 4. NumberFormatException
try {
String invalidNumber = "abc";
int num = Integer.parseInt(invalidNumber); // Invalid parsing
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " +
e.getMessage());
}
System.out.println("Program continues after handling exceptions.");
}
}

2|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

// Part-B-3.Write a Java Program for creation of User Defined Exceptions.


//FileName:UserException.java
import java.io.*;
import java.util.*;
class InvalidAgeException extends Exception
{
public InvalidAgeException(String message)
{
super(message);
}
}
// Class to demonstrate user-defined exception
public class UserException
{

// Method to check age


static void validateAge(int age) throws InvalidAgeException
{
if (age < 18)
{
throw new InvalidAgeException("Age must be 18 or above to
proceed.");
} else {
System.out.println("Age is valid. You may proceed.");
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the your age");
int age=sc.nextInt();
try {
validateAge(age); // This will trigger the exception
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

3|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-4. Java Program which creates and displays a message on the


window*/
//File Name: MessageWindow.java
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MessageWindow {


public static void main(String[] args) {
// Create a new frame
JFrame frame = new JFrame("Message Window");

// Create a label to display the message


JLabel label = new JLabel("Hello, welcome to Java Swings!",
JLabel.CENTER);

// Set frame properties


frame.add(label);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

javax is a package namespace in Java that contains extended functionalities beyond the
core java package.

Initially, javax was used for Java extensions, but over time, many important libraries
remained under javax instead of being moved to java.

Key Differences Between java and javax:

• java Package: Contains core Java classes like java.lang, java.util, java.io, etc.

• javax Package: Includes additional libraries such as javax.swing (GUI components),


javax.servlet (web applications), and javax.tools (compiler tools).

4|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

//Part-B-5.Java Program to draw several shapes in the created window*/


//FileName: DrawShapes.java
import javax.swing.*;
import java.awt.*;
class ShapePanel extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Set the color and draw a rectangle
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 60);
// Set the color and draw an oval
g.setColor(Color.BLUE);
g.fillOval(200, 50, 100, 60);
// Set the color and draw a line
g.setColor(Color.GREEN);
g.drawLine(50, 150, 300, 150);
// Set the color and draw a triangle
g.setColor(Color.ORANGE);
int[] xPoints = {150, 180, 120};
int[] yPoints = {200, 250, 250};
g.fillPolygon(xPoints, yPoints, 3);
}
}

public class DrawShapes


{
public static void main(String[] args)
{
// Create a frame
JFrame frame = new JFrame("Shapes Window");
// Set up the panel with custom drawings
ShapePanel panel = new ShapePanel();
frame.add(panel);
// Set frame properties
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

5|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-6-Java program Create a simple applet which reveals the personal


information of yours.*/
//File Name: PersonalInfo.java
import java.applet.Applet;
import java.awt.Graphics;

public class PersonalInfo extends Applet


{
public void paint(Graphics g)
{
g.drawString("Name: ABC", 20, 20);
g.drawString("Location: Bengaluru, India", 20, 40);
g.drawString("Hobby: Coding and Exploring Technology", 20, 60);
g.drawString("Favorite Programming Language: Java", 20, 80);
}
}

//File-2 : PersonalInfo.html
<html>
<body>
<applet code="PersonalInfo.class" width="300" height="100"></applet>
</body>
</html>

6|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-7.Create a frame which displays your personal details with


respect to a button click*/
//File Name: FrameDetails.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FrameDetails {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Personal Details");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

// Create the button


JButton button = new JButton("Show Personal Details");
frame.add(button, BorderLayout.SOUTH);

// Create the label


JLabel label = new JLabel("", SwingConstants.CENTER);
frame.add(label, BorderLayout.CENTER);

// Add button click action


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("<html><center><b>Name:</b> <big>Seshadripuram
College</big><br><b>Address:</b> Tumkur<br><b>Courses offered:</b>
BCA, BCom, BBA</center></html>");
}
});

// Make frame visible


frame.setVisible(true);
}
}

7|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-8Develop an Applet that receives an integer in one text field &


compute its factorial value & returns it in another text filed when the
button Compute is clicked.*/
//FileName: FactorialApplet.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class FactorialApplet extends Applet implements ActionListener {


TextField inputField, outputField;
Button computeButton;

public void init() {


// Set layout
setLayout(new FlowLayout());

// Create components
add(new Label("Enter number:"));
inputField = new TextField(10);
add(inputField);

computeButton = new Button("Compute");


add(computeButton);
computeButton.addActionListener(this);

add(new Label("Factorial:"));
outputField = new TextField(10);
outputField.setEditable(false);
add(outputField);
}

public void actionPerformed(ActionEvent e) {


try {
int num = Integer.parseInt(inputField.getText());
int f=1;
for(int i=1;i<=num;i++)
f=f*i;
outputField.setText(String.valueOf(f));
} catch (NumberFormatException ex) {
outputField.setText("Invalid input");
}
}
}
8|Page Department of BCA
JAVA Lab Programs BCA-2nd SEM(SEP)

//File-2 Name: FactorialApplet.html


<html>
<body>
<applet code="FactorialApplet.class" width="300" height="150"></applet>
</body>
</html>

9|Page Department of BCA


JAVA Lab Programs BCA-2nd SEM(SEP)

/*Part-B-9.Program to create a window when we press “M or m” the


window displays Good Morning, “A or a” the window displays Good After
Noon “E or e” the window displays Good Evening, “N or n” the window
displays Good Night*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class GreetingWindow {


public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Greeting Window");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Create label
JLabel label = new JLabel("Press M, A, E, or N",
SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
frame.add(label, BorderLayout.CENTER);
// Add key listener
frame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
char key = Character.toUpperCase(e.getKeyChar());
switch (key) {
case 'M':
label.setText("Good Morning!");
break;
case 'A':
label.setText("Good Afternoon!");
break;
case 'E':
label.setText("Good Evening!");
break;
case 'N':
label.setText("Good Night!");
break;
}
}
});

10 | P a g e Department of BCA
JAVA Lab Programs BCA-2nd SEM(SEP)

// Make frame visible


frame.setVisible(true);
}
}

11 | P a g e Department of BCA
JAVA Lab Programs BCA-2nd SEM(SEP)

//Part-B-10. Write a Java Program using Synchronized Threads which


//demonstrate Producer-Consumer Concept.
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {

private static final int BUFFER_SIZE = 5;


private static final Queue<Integer> buffer = new LinkedList<>();

public static void main(String[] args) {


Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());

producerThread.start();
consumerThread.start();
}

static class Producer implements Runnable {


private int value = 0;

@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.size() == BUFFER_SIZE) {
try {
System.out.println("Buffer is full, Producer is waiting...");
buffer.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
buffer.offer(value);
System.out.println("Produced: " + value);
value++;
buffer.notify();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
12 | P a g e Department of BCA
JAVA Lab Programs BCA-2nd SEM(SEP)

return;
}
}
}
}

static class Consumer implements Runnable {


@Override
public void run() {
while (true) {
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
System.out.println("Buffer is empty, Consumer is waiting...");
buffer.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
int value = buffer.poll();
System.out.println("Consumed: " + value);
buffer.notify();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
}

13 | P a g e Department of BCA

You might also like