0% found this document useful (0 votes)
1 views61 pages

Java Lab Programs

The document provides a comprehensive overview of Java programming, covering the structure of a Java program, including comments, package declarations, class definitions, and the main method. It includes several sample programs demonstrating basic concepts such as printing output, arithmetic operations, loops, and object-oriented programming with classes and constructors. Additionally, it discusses method overloading and the use of static variables and methods, along with examples to illustrate each concept.

Uploaded by

devikadevuuu983
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)
1 views61 pages

Java Lab Programs

The document provides a comprehensive overview of Java programming, covering the structure of a Java program, including comments, package declarations, class definitions, and the main method. It includes several sample programs demonstrating basic concepts such as printing output, arithmetic operations, loops, and object-oriented programming with classes and constructors. Additionally, it discusses method overloading and the use of static variables and methods, along with examples to illustrate each concept.

Uploaded by

devikadevuuu983
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

JAVA PROGRAMS

OOPS lab
Structure of Java Program
JAVA COMMENTS

Comments are non-executable parts of a program. A compiler does not execute a comment. It is
used to improve the readability of the code.

// a single line comment is declared like this

/* a multi-line comment is
declared like this
and can have multiple
lines as a comment */

/** a documentation comment starts with a delimiter and ends with */


JAVA PROGRAM STRUCTURE
• Package Declaration : Optional. A package is a group of classes that
are defined by a name. We can create a package with any name. There
can be only one package statement in a Java program. It must be
defined before any class and interface declaration. Eg : package scaler
; //scaler is the package name
• In Java, we have to save the program file name with the same name as
the name of public class in that file.
• Extension should be .java
• javac [Link] // To compile the Java program into byte-code
• java HelloWorld // To run the program
• Import statement : We can import a package, specific class or classes in by using an import statement
• Interface statement : Optional. Interfaces are like a class that includes a group of method declarations. It's an
optional section and can be used to implement multiple inheritances within a program.
• Class definition : A Java program may contain several class definitions.
• Main method class : The main method is from where the execution actually starts and follows the order
specified for the following statements.
Java class
• Vital part of a Java program.
• Without the class, we cannot create any Java program. Each Java program has to be written inside a class .
• A Java program may conation multiple classes.
• class keyword to define the class.
• The class is a blueprint of a Java program. It contains information about user-defined methods, variables, and
constants.
• Every Java program has at least one class that contains the main() method.
• They should begin with an uppercase letter
Java class
• For example:
class Student //class definition
{
}
Public Main Class

public class MyFirstJavaProgram {

This line is creating a new class MyFirstJavaProgram and


being public, this class is to be defined in the same name
file as [Link]. This convention
helps Java compiler to identify the name of public class
to be created before reading the file content.
Public Static Void Main

public static void main(String []args)


{
}
This line represents the main method that JVM calls when this program is loaded
into memory. This is a compulsory part of the structure of Java program. This is
the entry point of the compiler where the execution starts. This method is used to
execute the program. Once this method is finished, program is finished in single
threaded environment.
Public Static Void Main

• public − defines the scope of the main method. Being public,


this method can be called by external program like JVM.
• static − defines the state of the main method. Being static,
this method can be called by external program like JVM
without first creating the object of the class.
• void − defines the return type of the main method. Being
void, this method is not returning any value.
• main − name of the method
• String []args − arguments passed on command line while
executing the java command.
[Link]() method

• [Link]("Hello World"); // prints


Hello World
• [Link] represents the primary console and
its println() method is taking "Hello World" as input
and it prints the same to the console output.
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS

1.1 Hello World program


public class MyFirstJavaProgram
{
/* This is my first java program. * This will print 'Hello World' as the output */
public static void main(String []args)
{
[Link]("Hello World"); // prints Hello World
}
}
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS
1.2 Program to Add Two Integers

public class Add


{
public static void main(String[] args)
{
// Declaring two integers
int a = 10;
int b = 20; // Adding the two integers and storing the result in a new variable 'sum’
int sum = a + b; // Printing the result in the format "10 + 20 = 30"
[Link](a + " + " + b + " = " + sum);
}
}
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS

• Save : [Link]
• Compile : javac [Link]
• Run : java Add
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS

1.3 Simple Loop Example (Counting 1 to 10)


public class LoopExample
{
Save: [Link]
Compile : javac [Link]
public static void main(String[] args)
Run : java LoopExample
{
for (int i = 1; i <= 10; i++)
{
[Link](i);
}
}
}
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS
1.4 SUM OF FIRST 10 NUMBERS

class Sum
{ Save : [Link]
public static void main(String args[]) Compile: javac [Link]
{ Run : java Sum
int i,sum=0;
for(i=0;i<=10;i++)
{
sum=sum+i;
}
[Link](“Sum=”+sum);
}
}
EXPERIMENT 1 : JAVA SAMPLE PROGRAMS
1.5 Even or odd program
public class EvenOdd
{
public static void main(String[] args)
{
int number = 10 // Define a number to check
if (number % 2 == 0)
{
[Link](number + " is an even number."); // If the remainder is 0, it's an even number
}
else
{
[Link](number + " is an odd number."); // If the remainder is not 0, it's an odd number
}
}
}
EXPERIMENT 1 : JAVA SAMPLE
PROGRAMS

• Exp: 1.6 LARGEST OF 3 NUMBERS


• Write a java program to find the largest of 3 numbers by reading user
inputs.
EXPERIMENT 1 : JAVA SAMPLE
PROGRAMS
• Exp: 1.7 SUM OF TWO NUMBERS
• Write a java program to find the sum of two numbers by reading user
inputs and creating objects.
Experiment 2 – JAVA PROGRAM USING CLASS
AND OBJECT
• Exp.2.1: Person Class
• Create a class named Person with member variables name and age , with member function setDetails to set
the values of name and age and getDetails to display the values of name and age. Create a Test class and
create an object of Person class and test its functions.
Experiment 2.1 – JAVA PROGRAM USING CLASS AND
OBJECT – Person Class
class Person
public class Test
Each Java program should have only {
{
one class declared with public access private String name;
public static void main(String args[])
specifier. There cannot be private int age;
{
public void setDetails(String n,int a)
two public classes in a single Java Person p = new Person();
{
program. Additionally, the name of [Link](“ALEX”,35);
name = n;
the public class should be the same as [Link]();
age = a;
the name of the Java file. }
}
}

public void getDetails()


Save : [Link] (filename should match {
public class name) [Link]("Name:"+name);
[Link]("Age:"+age);
}
}
Experiment 2 – JAVA PROGRAM USING CLASS AND
OBJECT
• [Link]: 2.2 : Student Class
• Create a class named Student with member variables name, rollno, department, year with
member function setDetails to set the values of name, rollno, department, year and
getDetails to display the values name, rollno, department, year . create a
Studentdetails class and create an object of student class and test its functions.
class Student
{
// Class variables
String name;
int rollNo;
String department;
int year;
// Method to set the details of a student
void setDetails(String studName, int studRollNo, String studDepartment, int studYear)
{
name = studName;
rollNo = studRollNo;
department = studDepartment;
year = studYear;
}
// Method to get student details
void getDetails()
{
[Link]("\nStudent Details:");
[Link]("Name: " + name);
[Link]("Roll Number: " + rollNo);
[Link]("Department: " + department);
[Link]("Year: " + year);
}
}
public class StudentDetails
{ // Displaying the details of each student
public static void main(String[] args)
{ [Link]();
// Creating objects for 5 students [Link]();
Student s1 = new Student(); [Link]();
Student s2 = new Student(); [Link]();
Student s3 = new Student(); [Link]();
Student s4 = new Student(); }
Student s5 = new Student(); }

// Set details of student Objects


[Link]("John", 123, "Computer Science", 3);

[Link]("Smith", 456, "Electrical Engineering", 2);

[Link]("Johnson", 789, "Civil Engineering", 4);

[Link]("Rohith", 101, "Mechanical Engineering", 1);

[Link]("Deepa", 112, "Chemical Engineering", 2);


EXPERIMENT 3 – Constructor

Write a Java program to create a Rectangle class with two


members: length and width. The class should have a method
calculateArea to calculate the area of the rectangle. Create a
class called RectangleArea and create two objects of the
Rectangle class use a parameterized constructor to set the
values of length , width and display the area of each rectangle.
EXPERIMENT 3 – Constructor
Save : [Link]
class Rectangle
{
// Instance variables to store the length and width of the rectangle
int length, width;
// Constructor to initialize the length and width of the rectangle
public Rectangle(int x, int y)
{ // Main class to test the Rectangle class
length = x; public class RectangleArea
width = y; {
} public static void main(String[] args)
// Method to calculate the area of the rectangle {
public int calculateArea() // Creating two objects of Rectangle class
{ Rectangle r1 = new Rectangle(10, 5); // Length 10, Width 5
return length * width; Rectangle r2= new Rectangle(8 , 4); // Length 8, Width 4
} // Displaying the area of both rectangles
[Link]("Area of Rectangle 1: " + [Link]());
}
[Link]("Area of Rectangle 2: " + [Link]());
}
}
EXPERIMENT – 4 Demonstrate the role of
constructors using CONSTRUCTOR OVERLOADING
• Write a Java program to create a Student class with members: name,
age, rollNo. Use a default contructor to set name, age, rollNo to
default values and use a parameterized constructor to set name,
age, rollNo. The class should have a method displayDetails to display
the name, age, rollNo of Student. Create a class called TestStudent and
create two objects of the Student class and test its functionalities.
EXPERIMENT – 4 Demonstrate the role of constructors using
CONSTRUCTOR OVERLOADING
// Student class with default and parameterized constructor // Parameterized constructor
class Student public Student(String stName, int stAge, int stRollNo)
{ {
// Member variables [Link]("Student 2 details using Parameterized Constructor:
String name; // Initializing member variables with provided values
int age; name = stName;
int rollNo; age = stAge;
rollNo = stRollNo;
// Default constructor }
public Student()
{ // Method to display student details
// Default values for member variables public void displayDetails()
[Link]("Student 1 details using Default Constructor:"); {
name = "Unknown"; [Link]("Name: " + name);
age = 0; [Link]("Age: " + age);
rollNo = 0; [Link]("Roll Number: " + rollNo);
} }
}
EXPERIMENT 4 - Demonstrate the role of constructors using
CONSTRUCTOR OVERLOADING

OUTPUT:
// Main class to test student class
public class TestStudent Student 1 details using Default Constructor:
{ Name: Unknown
public static void main(String[] args) Age: 0
{ Roll Number: 0
// creating a student object using the default constructor
Student s1 = new Student(); Student 2 details using Parameterized
[Link](); Constructor:
Name: John
// Creating a student object using the parameterized constructor Age: 20
Student s2 = new Student(“John", 20, 101); Roll Number: 101
[Link]();
}
}
EXPERIMENT 5 – METHOD OVERLOADING
• Write a Java program that uses method overloading to calculate the area of a
square and a rectangle.
EXPERIMENT 5 – METHOD OVERLOADING
// Class 1: Shape (contains overloaded methods)
class Shape
{
// Method to calculate the area of a square (side length)
public int area(int side)
{
return side * side; // Area of square = side * side
}
// Method to calculate the area of a rectangle (length and breadth)
public int area(int length, int breadth)
{
return length * breadth; // Area of rectangle = length * breadth
}
}
EXPERIMENT 5 – METHOD OVERLOADING

public class Test


{
public static void main(String[] args)
{
// Create an object of Shape class
Shape shape = new Shape();

// Calling the overloaded area method for square with side length 5
[Link]("Area of Square : " + [Link](5));

// Calling the overloaded area method for rectangle with length 10 and breadth 4
[Link]("Area of Rectangle : " + [Link](10, 4));
}
}
JAVA PROGRAM USING ARRAY OF OBJECTS

// Person class with name and age as instance variables


class Person
{
String name;
int age;
// Constructor to initialize name and age
Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
// Method to display the person's details
void display()
{
[Link]("Name: " + name + ", Age: " + age);
}
}
JAVA PROGRAM USING ARRAY OF OBJECTS
public class Test
{
public static void main(String[] args)
{
// Create an array of Person objects
Person[] p = new Person[3];

// Initialize the array with Person objects


p[0] = new Person("Alice", 25);
p[1] = new Person("Bob", 30);
p[2] = new Person("Charlie", 22);

// Loop through the array and call the display method for each Person object
for (int i = 0; i < [Link]; i++)
{
p[i].display(); // Calling display method to show details
}
}
}
JAVA PROGRAM USING STATIC VARIABLES AND METHODS
// Class containing static variables and methods
class StaticExample
{
// Static variable
static int count = 0;
// Static block - executed once when the class is loaded
static
{
[Link]("Static block executed!");
count = 10; // Initializing static variable
}
// Static method to display the count
static void displayCount()
{
[Link]("Count: " + count);
}
// Non-static method to increment the count
void incrementCount()
{ count++; // Increment the static variable
}
}
JAVA PROGRAM USING STATIC VARIABLES AND
METHODS
public class Test
{ OUTPUT:
public static void main(String[] args) Static block executed!
{ Count: 10
// Calling static method using class name from the other class Count: 11
[Link]();

// Creating an object of StaticExample class


StaticExample obj = new StaticExample();

// Calling non-static method to modify the static variable


[Link]();

// Calling static method again to show updated value of static variable


[Link]();
}
}
EXPERIMENT 6 – JAVA PROGRAM IMPLEMENTING EXCEPTION HANDLING
import [Link];
public class SimpleExceptionHandling
{ catch (Exception e)
public static void main(String[] args) {
{ // Handling any other unexpected exceptions
//Read two numbers [Link]("An unexpected error occurred: " + [Link]());
Scanner s = new Scanner([Link]); }
[Link](“Enter two numbers to divide : ”); finally
int num1 = [Link](); // Numerator {
int num2 = [Link](); //Denominator // Code that will always execute
[Link]("This is the finally block.");
try }
{ }
// Trying to divide the numbers }
int result = num1 / num2;
[Link]("Result: " + result);
} OUTPUT:
catch (ArithmeticException e) Error: Division by zero is not allowed.
{
This is the finally block.
// Handling division by zero
[Link]("Error: Division by zero is not allowed.");
}
EXPERIMENT 7 – JAVA PROGRAM IMPLEMENTING SINGLE INHERITANCE
// Parent Class // Main Class
class Animal public class SingleInheritanceExample
{ {
void eat() public static void main(String[] args)
{ {
[Link]("This animal eats food."); Dog myDog = new Dog();
}
} [Link](); // Inherited method
// Child Class (inherits Animal) [Link](); // Dog-specific method
class Dog extends Animal }
{ }
void bark()
{
[Link]("The dog barks."); OUTPUT:
} This animal eats food.
} The dog barks.
public
EXPERIMENT 8 – JAVA PROGRAM IMPLEMENTING MULTILEVEL INHERITANCE
// Base class (Parent class)
class Animal
{ public class TestAnimal
void eat() {
{ public static void main(String[] args)
[Link]("Animal is eating"); {
}
// Creating an object of Puppy class
}
Puppy p = new Puppy();
// Derived class (Child class of Animal)
class Dog extends Animal
{ // Accessing methods from all three classes
void bark() [Link](); // From Animal class
{ [Link](); // From Dog class
[Link]("Dog barks"); [Link](); // From Puppy class
} }
} }
// Further derived class (Child class of Dog)
class Puppy extends Dog OUTPUT:
{ Animal is eating
void play() Dog barks
{ Puppy is playing
[Link]("Puppy is playing");
}
}
EXPERIMENT 9 – JAVA PROGRAM IMPLEMENTING HIERARCHICAL
// Parent Class INHERITANCE
class Animal
{ // Main Class
void eat() public class TestExample
{ {
[Link]("This animal eats food"); public static void main(String[] args)
} {
} Dog myDog = new Dog();
// Child Class 1 (inherits Animal)
class Dog extends Animal [Link](); // Inherited method
{ [Link](); // Dog-specific method
void bark()
{ Cat myCat = new Cat();
[Link]("The dog barks");
} [Link](); // Inherited method
} [Link](); // Cat-specific method
// Child Class 2 (inherits Animal)
}
class Cat extends Animal
}
{ OUTPUT:
void meow() This animal eats food
{ The dog barks
[Link]("The cat meows"); This animal eats food
} The cat meows
public
EXPERIMENT 10 – JAVA PROGRAM IMPLEMENTING
MULTIPLE INHERITANCE USING INTERFACE
interface AnimalEat
{
void eat(); //abstract method class Animal implements AnimalEat, AnimalTravel
} {
interface AnimalTravel public void eat() // overriding
{ {
void travel(); //abstract method [Link]("Animal is eating"); public class MultipleInheritanceTest
} } {
public void travel() // overriding public static void main(String args[])
{ {
[Link]("Animal is traveling"); Animal a = new Animal();
} [Link]();
} [Link]();
}
}

OUTPUT
Animal is eating
Animal is traveling
MULTIPLE INHERITANCE USING INTERFACE
Output:
This is a person.
This person is a student.
Enter marks of 3 subjects: 75 80 85
Total Marks = 240.0
EXPERIMENT 11 – User Defined Package Java
Program

• Aim: To write a Java program to perform addition and subtraction of


two numbers using a user-defined package.
(new ActionListener() { });

//code for actionPerformed() { }


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

public class LoginForm {


public static void main(String[] args) {
// Create the JFrame object
JFrame f = new JFrame("Login Validation");

// Initialize components
JTextField t1 = new JTextField(); // Email field
JTextField t2 = new JTextField(); // Password field (JPasswordField
can also be used)
JButton b1 = new JButton("Login");
JLabel l1 = new JLabel("Email:");
JLabel l2 = new JLabel("Password:");
// Set positions for components // Action Listener logic
[Link](20, 30, 80, 30); [Link](new ActionListener() {
[Link](100, 30, 150, 30); public void actionPerformed(ActionEvent evt) {
[Link](20, 70, 80, 30); String email = [Link]();
[Link](100, 70, 150, 30); String pass = [Link]()); // getPassword() is used for JPasswordField
[Link](100, 120, 80, 30);
if (email .equals("admin") && [Link]("pass"))
// Add components to the JFrame object {
[Link](l1); [Link](f, "Login Successful");
[Link](t1); }
[Link](l2); else {
[Link](t2); [Link](f, "Invalid Credentials", "Error",
[Link](b1); JOptionPane.ERROR_MESSAGE);
}
// Frame settings }
[Link](300, 220); });
[Link](null); }
[Link](true);
}
[Link](JFrame.EXIT_ON_CLOSE);
Email

Password Login

Submit
import [Link].*; // 2. Create UI Components
import [Link].*;
JLabel userLabel = new JLabel(" Username:");
JTextField userField = new JTextField();
import [Link].*;
JLabel passLabel = new JLabel(" Password:");
import [Link].*; JPasswordField passField = new JPasswordField();
JButton submitButton = new JButton("Submit");
public class JDBCLoginApp {
public static void main(String[] args) { // 3. Add Components to Frame
// 1. Create the JFrame Object
[Link](userLabel);
[Link](userField);
JFrame frame = new JFrame("Login Database Connection");
[Link](passLabel);
[Link](350, 200); [Link](passField);
[Link](new GridLayout(3, 2, 10, 10)); [Link](new JLabel("")); // Spacer
[Link](JFrame.EXIT_ON_CLOSE); [Link](submitButton);
// 4. Submit Button Logic // SELECT ALL RECORDS
String selectQuery = "SELECT * FROM employee";
[Link](new ActionListener() {
Statement st = [Link]();
public void actionPerformed(ActionEvent e) { ResultSet rs = [Link](selectQuery);

String data = "---- Employee Table ----\n\n";


String username = [Link]();
while ([Link]()) {
String password = new String([Link]()); data += "ID: " + [Link]("id") +
" | Username: " + [Link]("username") +
" | Password: " + [Link]("password") + "\n";
try { }
// SHOW DATA IN SWING
[Link]("[Link]"); [Link](frame, data);

[Link]();
Connection conn = [Link]("jdbc:mysql://localhost:3306/har", "root","" );
} catch (Exception ex) {
// INSERT RECORD
[Link](frame, "Error: " + [Link]());
String insertQuery = "INSERT INTO employee (username, password) VALUES (?, ?)"; [Link]();
}
PreparedStatement insertStmt = [Link](insertQuery); }
[Link](1, username); });

[Link](2, password); // 5. Make visible


int rows = [Link](); [Link](null); // Center on screen
[Link](true);
if (rows > 0) { }
}
[Link](frame, "Record Inserted Successfully!");
}
Open terminal:
mysql -u root –p
Run:
CREATE DATABASE har;
USE har;
CREATE TABLE employee (id INT AUTO_INCREMENT
PRIMARY KEY, username VARCHAR(50), password
VARCHAR(50));

Check table:
SHOW TABLES;
DESC employee;
• How to Execute
• To compile and run from the terminal, you must include the JDBC JAR
in the classpath
• # Compile
• javac -cp .:[Link] [Link]

• # Run
• java -cp .:[Link] JDBCLoginApp

You might also like