0% found this document useful (0 votes)
3 views

Computer Programming (Java)

The document outlines various Java experiments, including creating a Java Applet to display 'HELLO JAVA', connecting to a MySQL database using JDBC, demonstrating interfaces, handling exceptions, and understanding class structures. Each experiment includes objectives, required software, theory, source code, procedures, observations, results, and conclusions. The experiments collectively illustrate fundamental Java programming concepts and practices.
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)
3 views

Computer Programming (Java)

The document outlines various Java experiments, including creating a Java Applet to display 'HELLO JAVA', connecting to a MySQL database using JDBC, demonstrating interfaces, handling exceptions, and understanding class structures. Each experiment includes objectives, required software, theory, source code, procedures, observations, results, and conclusions. The experiments collectively illustrate fundamental Java programming concepts and practices.
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/ 12

Experiment No 5

Objective: To write and execute a Java Applet program that displays the message "HELLO
JAVA" in a web browser or applet viewer.

Apparatus/Software Required:

• Java Development Kit (JDK)


• Text Editor (e.g., Notepad, VS Code)
• Applet Viewer or Web Browser with Java Plugin

Theory:

An applet is a Java program that runs in a web browser or applet viewer. Unlike standalone
applications, applets do not require a main() method. Instead, they inherit from the Applet class
and override methods like paint() to perform actions such as drawing on the screen.

Source Code:

import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="HelloJavaApplet.class" width=300 height=150>
</applet>
*/

public class HelloJavaApplet extends Applet {


public void paint(Graphics g) {
g.drawString("HELLO JAVA", 100, 75);
}
}
Procedure:

1. Open a text editor and write the above code.


2. Save the file as HelloJavaApplet.java.
3. Open Command Prompt (or Terminal) and navigate to the directory where the file is
saved.
4. Compile the program using the command:
5. javac HelloJavaApplet.java
6. Create an HTML file named HelloJavaApplet.html with the following content:
7. <html>
8. <body>
9. <applet code="HelloJavaApplet.class" width="300" height="150"></applet>
10. </body>
11. </html>
12. Open the HTML file in a Java-enabled web browser or run it using the applet viewer:
13. appletviewer HelloJavaApplet.java

Observation:
After execution, the message "HELLO JAVA" appears centered on the applet window.

Result:
The applet successfully displays the message “HELLO JAVA” in the applet window.

Conclusion:
The experiment demonstrates how to create a basic Java Applet and display text using the
Graphics class and drawString() method.
Experiment No: 4

Objective: To write and execute a Java program that connects to a database and performs
basic operations such as retrieving and displaying data.

Apparatus/Software Required:

• Java Development Kit (JDK)


• MySQL or any other relational database
• JDBC Driver (e.g., mysql-connector-java.jar)
• Text Editor or IDE (e.g., Notepad, VS Code, IntelliJ)

Theory:

Java Database Connectivity (JDBC) is an API that enables Java programs to interact with
databases. Using JDBC, we can connect to a database, send SQL queries, and retrieve
results. The typical steps in JDBC are:

1. Load the JDBC driver.


2. Establish a connection to the database.
3. Create a statement
4. Execute the query
5. Process the result.
6. Close the connection.

Source Code

Import java.sql.Connection;

Import java.sql.DriverManager;

Import java.sql.ResultSet;
Import java.sql.Statement;

Public class DBConnectExample {

Public static void main(String[] args) {

Try {

// Load the JDBC driver

Class.forName(“com.mysql.cj.jdbc.Driver”);

// Connect to the database

Connection con = DriverManager.getConnection(

“jdbc:mysql://localhost:3306/testdb”, “root”, “yourpassword”);

// Create a statement

Statement stmt = con.createStatement();

// Execute a query

ResultSet rs = stmt.executeQuery(“SELECT * FROM students”);

// Display results

While (rs.next()) {

System.out.println(“ID: “ + rs.getInt(1) +

“, Name: “ + rs.getString(2));

// Close connection

Con.close();
} catch (Exception e) {

System.out.println€;

Procedure:

1. Install and run a MySQL database server.


2. Create a database named testdb.
3. Create a table using the command:

CREATE TABLE students (id INT, name VARCHAR(50));

INSERT INTO students VALUES (1, ‘Alice’), (2, ‘Bob’);

4. Download and add mysql-connector-java.jar to the project classpath.


5. Write and save the above Java code as DBConnectExample.java.
6. Compile the code using:
Javac DBConnectExample.java
7. Run the program:
Java DBConnectExample

Observation:

The console displays the contents of the students table, showing ID and Name of each
student.

Result:

The program successfully connects to the MySQL database and retrieves data using JDBC.

Conclusion:

The experiment demonstrates how to use Java JDBC to establish a connection with a
database and execute SQL queries.
Experiment No . 3

Objective: To write and execute a Java program demonstrating interfacing between two
classes using an interface.

Apparatus/Software Required:

Java Development Kit (JDK)

Text Editor or IDE (e.g., Notepad, VS Code, IntelliJ)

Theory:

In Java, an interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces provide
a way to achieve abstraction and multiple inheritance in Java.

When two classes need to communicate, one class can implement an interface defined by
another class, ensuring loose coupling and modularity.

Source Code:

// Interface

Interface Message {

Void showMessage();

// Class implementing the interface

Class Hello implements Message {

Public void showMessage() {

System.out.println(“Hello from the Hello class!”);


}

// Another class using the interface

Public class InterfaceDemo {

Public static void main(String[] args) {

Message msg = new Hello(); // Interface reference to Hello object

Msg.showMessage(); // Calls overridden method

Procedure:

1. Open a text editor and type the above code.


2. Save the file as InterfaceDemo.java.
3. Open the command prompt or terminal and navigate to the directory where the file
is saved.
4. Compile the code:
Javac InterfaceDemo.java
5. Run the program:
Java InterfaceDemo

Observation:

The console displays the message:

“Hello from the Hello class!”

Result:

The program successfully demonstrates interfacing between two classes using the
Message interface.

Conclusion:
This experiment shows how interfaces in Java are used to allow communication between
classes, enforce abstraction, and support multiple inheritance.

Experiment No 2.

Objective: To understand the concept of exception handling in Java .

Theory:

Exception handling in Java is a mechanism to handle runtime errors, so the normal flow of the
application can be maintained. Java provides five keywords to handle exceptions:

• try: Defines a block of code to be tested for errors.


• catch: Defines a block of code to handle the exception.
• finally: Defines a block of code that will always execute after try/catch.
• throw: Used to throw an exception.
• throws: Declares exceptions in a method signature.

Program:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
int[] numbers = {10, 0, 5};

for (int i = 0; i < numbers.length; i++) {


try {
System.out.println("Dividing 100 by " + numbers[i]);
int result = 100 / numbers[i];
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("This block always executes.\n");
}
}

System.out.println("Program continues after exception handling.");


}
}

Output:
Dividing 100 by 10
Result: 10
This block always executes.
Dividing 100 by 0
Error: Cannot divide by zero.
This block always executes.

Dividing 100 by 5
Result: 20
This block always executes.

Program continues after exception handling.

Conclusion:

The program successfully demonstrates how exception handling allows the program to catch and
manage runtime errors such as divide-by-zero, and continue executing without crashing.
Experiment No 1

Objective: To understand the concept of a class in Java and how it is used to define and
create objects.

Theory:

In Java, a class is a blueprint from which individual objects are created. A class contains
fields (variables) and methods to define the behavior of an object.

Basic structure of a class includes:

Fields: Variables to store data.

Methods: Functions that define

Objects: Instances of a class.

Program:

// Class definition

Class Student {

// Fields (attributes)

String name;

Int age;

// Method to display student details

Void displayInfo() {

System.out.println(“Student Name: “ + name);


System.out.println(“Student Age: “ + age);

// Main class

Public class ClassConceptDemo {

Public static void main(String[] args) {

// Creating an object of Student class

Student student1 = new Student();

// Assigning values to object attributes

Student1.name = “John”;

Student1.age = 20;

// Calling method using object

Student1.displayInfo();

Output:

Student Name: John

Student Age: 20

Conclusion:

This program demonstrates how to define a class, create an object, assign values to its
attributes, and call its methods in Java. It helps to understand the foundation of object-
oriented programming.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy