NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

//myfirstjavaprogram.java
public class myfirstjavaprogram{
public static void main(String args[]){
System.out.println("My name is barry allen");
}
}


Addition of Elements of an Array using Dynamic Array
import java.util.ArrayList;
import java.util.Scanner;

public class DynamicArrayAddition {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>(); // Dynamic Array

System.out.println("Enter numbers (enter -1 to stop):");

while (true) {
int num = input.nextInt();
if (num == -1) break; // Stop input when -1 is entered
numbers.add(num); // Add element to the dynamic array
}

// Calculate sum
int sum = 0;
for (int num : numbers) {
sum += num;
}

// Display results
System.out.println("Numbers entered: " + numbers);
System.out.println("Sum of the elements: " + sum);

input.close();
}
}




Experiment 3: Program to Demonstrate Constructor Overloading, Method
Overloading and Operator Overloading .
class OverloadDemo {
int a, b;
OverloadDemo() {
this.a = 0;
this.b = 0;
}
OverloadDemo(int x, int y) {
this.a = x;
this.b = y;
}
void add() {
System.out.println("Sum (default values): " + (a + b));
}
void add(int x, int y) {
System.out.println("Sum of given numbers: " + (x + y));
}
void add(double x, double y) {
System.out.println("Sum of doubles: " + (x + y));
}
OverloadDemo add(OverloadDemo obj) {
OverloadDemo temp = new OverloadDemo();

temp.a = this.a + obj.a;
temp.b = this.b + obj.b;

return temp;
}
void display() {
System.out.println("Values: a = " + a + ", b = " + b);
}
}
public class OverloadingExample {
public static void main(String[] args) {
OverloadDemo obj1 = new OverloadDemo();
OverloadDemo obj2 = new OverloadDemo(10, 20);

System.out.println("nConstructor Overloading:");
obj1.display();
obj2.display();
System.out.println("nMethod Overloading:");
obj2.add();
obj2.add(15, 25);
obj2.add(5.5, 4.5);
System.out.println("nOperator Overloading Simulation:");
OverloadDemo obj3 = new OverloadDemo(5, 7);
OverloadDemo obj4 = new OverloadDemo(3, 6);
OverloadDemo result = obj3.add(obj4);
System.out.print("After addition: ");
result.display();
}
}



Experiment 4: Program to show the use of Private, Protected, Public and
Default Access Specifiers.

package accessdemo;
class Parent {
private int privateVar = 10;
protected int protectedVar = 20;
public int publicVar = 30;
int defaultVar = 40;
void display() {
System.out.println("Inside Parent Class:");
System.out.println("Private Variable: " + privateVar);
System.out.println("Protected Variable: " + protectedVar);
System.out.println("Public Variable: " + publicVar);
System.out.println("Default Variable: " + defaultVar);
}
class Child extends Parent {
void show() {
System.out.println("nInside Child Class:");
System.out.println("Protected Variable: " + protectedVar);
System.out.println("Public Variable: " + publicVar);
System.out.println("Default Variable: " + defaultVar);
}
}
public class AccessSpecifierDemo {
public static void main(String[] args) {
Parent parent = new Parent();
System.out.println("Inside Main Method:");
System.out.println("Protected Variable: " + parent.protectedVar);
System.out.println("Public Variable: " + parent.publicVar);
System.out.println("Default Variable: " + parent.defaultVar);
Child child = new Child();
child.show();
}
}


Experiment 5: Demonstrate and Use Packages in Java.
// File: com/example/MyPackage.java package com.example;
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass inside mypackage!");
}
}
// File: Main.java
import mypackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}


Experiment 6: Demonstrate and Use Different Types of Inheritance in Java

// InheritanceDemo.java
class Parent {
void show() {
System.out.println("This is Parent class");
}
}
// --- Single Inheritance ---
class Child extends Parent {
void display() {
System.out.println("This is Child class");
}
}
// --- Multilevel Inheritance ---
class Grandparent {
void grandparentMethod() {
System.out.println("This is Grandparent class");
}
}
class Parent2 extends Grandparent {
void parentMethod() {
System.out.println("This is Parent class");
}
}
class Child2 extends Parent2 {
void childMethod() {
System.out.println("This is Child class");
}
}
// --- Multiple Inheritance (Using Interfaces) ---
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A from Interface A");
}
public void methodB() {
System.out.println("Method B from Interface B");
}
}
// --- Hierarchical Inheritance ---
class Child1 extends Parent {
void displayChild1() {
System.out.println("This is Child1 class");
}
}
class Child3 extends Parent {
void displayChild3() {
System.out.println("This is Child3 class");
}
}

public class InheritanceDemo {
public static void main(String[] args) {

// Single Inheritance
System.out.println("Single Inheritance:");
Child obj1 = new Child();
obj1.show();
obj1.display();
// Multilevel Inheritance
System.out.println("nMultilevel Inheritance:");
Child2 obj2 = new Child2();
obj2.grandparentMethod();
obj2.parentMethod();
obj2.childMethod();

// Multiple Inheritance
System.out.println("nMultiple Inheritance:");
C obj3 = new C();
obj3.methodA();
obj3.methodB();
// Hierarchical Inheritance
System.out.println("nHierarchical Inheritance:");
Child1 obj4 = new Child1();
obj4.show();
obj4.displayChild1();
Child3 obj5 = new Child3();
obj5.show();
obj5.displayChild3();
}
}

Experiment 7: Demonstrate Exception Handling in Java.
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in)
try {
System.out.print("Enter a number: ");
int num1 = input.nextInt();
System.out.print("Enter another number: ");
int num2 = input.nextInt();
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (Exception e) {
System.out.println("Error: An unexpected error occurred.");
} finally {
input.close();
System.out.println("Program execution completed.");
}
}



LAB 2
Experiment 1: User Interface using Swing

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingFormExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Form Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 2, 10, 10));
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField();
JLabel ageLabel = new JLabel("Age:");
JTextField ageField = new JTextField();
JLabel addressLabel = new JLabel("Address:");
JTextField addressField = new JTextField();
JLabel contactLabel = new JLabel("Contact:");
JTextField contactField = new JTextField();
JLabel emailLabel = new JLabel("Email:");
JTextField emailField = new JTextField();
JLabel genderLabel = new JLabel("Gender:");
String[] genders = { "Male", "Female", "Other" };
JComboBox<String> genderComboBox = new JComboBox<>(genders);
JLabel countryLabel = new JLabel("Country:");
JTextField countryField = new JTextField();
JButton submitButton = new JButton("Submit");
JTextArea outputArea = new JTextArea(5, 30);
outputArea.setEditable(false);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String age = ageField.getText();
String address = addressField.getText();
String contact = contactField.getText();
String email = emailField.getText();
String gender = (String) genderComboBox.getSelectedItem();
String country = countryField.getText();
String output = String.format("Name: %snAge: %snAddress: %snContact: %snEmail: %snGender:
%snCountry: %s",
name, age, address, contact, email, gender, country);
outputArea.setText(output);
}
});
panel.add(nameLabel);
panel.add(nameField);
panel.add(ageLabel);
panel.add(ageField);
panel.add(addressLabel);
panel.add(addressField);
panel.add(contactLabel);
panel.add(contactField);
panel.add(emailLabel);
panel.add(emailField);
panel.add(genderLabel);
panel.add(genderComboBox);
panel.add(countryLabel);
panel.add(countryField);
panel.add(submitButton);
panel.add(new JScrollPane(outputArea));
frame.add(panel);
frame.setVisible(true);
}
}



LAB 3
Experiment 1: Event Handling in Java

import javax.swing.*;
import java.awt.event.*;
public class EventHandlingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Button not clicked yet", SwingConstants.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button clicked!");
}
});
frame.setLayout(new java.awt.BorderLayout());
frame.add(button, java.awt.BorderLayout.SOUTH);
frame.add(label, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
}
}


LAB 4
Experiment 1: CRUD Operations in JAVA

import java.util.*;
class Student {
int id;
String name;
String address;
Student(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
}
public class StudentCRUD {
static Scanner sc = new Scanner(System.in);
static List<Student> students = new ArrayList<>();
public static void main(String[] args) {
int choice;
do {
System.out.println("nMenu:");
System.out.println("1. Create");
System.out.println("2. Read");
System.out.println("3. Update");
System.out.println("4. Delete");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
sc.nextLine(); // Consume newline
switch (choice) {
case 1:
create();
break;
case 2:
read();
break;
case 3:
update();
break;
case 4:
delete();
break;
case 5:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again.");
}
} while (choice != 5);
}
// Create Operation
public static void create() {
System.out.print("Enter ID: ");
int id = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Name: ");
String name = sc.nextLine();
System.out.print("Enter Address: ");
String address = sc.nextLine();
students.add(new Student(id, name, address));
System.out.println("Student added successfully!");
}
// Read Operation
public static void read() {
System.out.println("nList of Students:");
if (students.isEmpty()) {
System.out.println("No students available.");
return;
}
for (Student student : students) {
System.out.println("ID: " + student.id + ", Name: " + student.name + ", Address: " + student.address);
}
}
// Update Operation
public static void update() {
System.out.print("Enter ID of student to update: ");
int id = sc.nextInt();
sc.nextLine(); // Consume newline
boolean found = false;
for (Student student : students) {
if (student.id == id) {
found = true;
System.out.print("Enter new Name: ");
student.name = sc.nextLine();
System.out.print("Enter new Address: ");
student.address = sc.nextLine();
System.out.println("Student details updated successfully!");
break;
}
}
if (!found) {
System.out.println("Student with ID " + id + " not found.");
}
}
// Delete Operation
public static void delete() {
System.out.print("Enter ID of student to delete: ");
int id = sc.nextInt();
boolean found = false;
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
if (student.id == id) {
iterator.remove();
found = true;
System.out.println("Student with ID " + id + " deleted successfully.");
break;
}
}
if (!found) {
System.out.println("Student with ID " + id + " not found.");
}
}
}


LAB 5
Experiment 1: To handle Http Request and Http Response in Servlet

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Page</title>
</head>
<body>
<center><% out.println("welcome to login page"); %></center>
<center><h1><u>Login Here</u></h1></center>
<center>
<div>
<form action="login" method="POST">
<table >
<tr>
<td>Username:<br><br></td>
<td><input type="text" name="username"><br><br></td>
</tr>
<tr>
<td>Password:<br><br></td>
<td><input type="text" name="password"><br><br></td>
</tr> <tr>
<td colspan="2" style="text-align: center"><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>

Login.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "login", urlPatterns = {"/login"})
public class login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username!= null && password!= null){
if(username.equals("admin") && password.equals("admin123")){
response.sendRedirect("welcome.jsp");
}else{
out.println("invalid username or password");
}
}else{
out.println("no empty fields, please");
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Welcome.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>welcome Page</title>
</head>
<body>
<center><h1>welcome</h1></center>
<center><p>You are logged in.</p></center>
</body>
</html>


Experiment 2: To demonstrate RequestDispatcher in Servlet.

<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.