0% found this document useful (0 votes)
9 views37 pages

Java Class, Inheritance, and Methods

The document contains multiple Java programming examples demonstrating various concepts such as class and object implementation, constructors, inheritance, method overloading and overriding, interfaces, abstract classes, exception handling, threading, and thread synchronization. Each section includes code snippets and expected outputs to illustrate the concepts effectively. The examples cover a wide range of fundamental programming principles in Java.

Uploaded by

riyazmd10001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views37 pages

Java Class, Inheritance, and Methods

The document contains multiple Java programming examples demonstrating various concepts such as class and object implementation, constructors, inheritance, method overloading and overriding, interfaces, abstract classes, exception handling, threading, and thread synchronization. Each section includes code snippets and expected outputs to illustrate the concepts effectively. The examples cover a wide range of fundamental programming principles in Java.

Uploaded by

riyazmd10001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. a) Write a Java sample program to implement class and object concepts.

class Student {
// Properties (Fields)
String name;
int age;
String grade;
// Method to display student detail
public void displayStudentInfo() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
[Link]("Student Grade: " + grade);
}
}

// Main class to test the Student


public class Main {
public static void main(String[] args) {
// Creating an object of the Student class
Student student1 = new Student();

// Setting values directly (no constructor)


[Link] = "Alice";
[Link] = 20;
[Link] = "A";

// Calling method on the object to display student information


[Link]();

// Creating another student object and setting values


Student student2 = new Student();
[Link] = "Bob";
[Link] = 22;
[Link] = "B";

// Calling method on the second student object to display info


[Link]();
}
}

Output:
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac [Link]

C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java Main
Student Name: Alice
Student Age: 20
Student Grade: A
Student Name: Bob
Student Age: 22
Student Grade: B
1. b) Write a Java program to illustrate types of constructors.
class Student {
// Properties (Fields)
String name;
int age;
String grade;
// Constructor to initialize the Student object
public Student(String name, int age, String grade) {
[Link] = name;
[Link] = age;
[Link] = grade;
}
// Method to display student details
public void displayStudentInfo() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
[Link]("Student Grade: " + grade);
}
}
// Main class to test the Student class
public class Main1 {
public static void main(String[] args) {
// Creating Student objects and initializing them with constructor
Student student1 = new Student("Alice", 20, "A");
Student student2 = new Student("Bob", 22, "B");
// Calling method on the student objects to display their details
[Link]();
[Link]();
}
}
Output:
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac [Link]
C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java Main1

Student Name: Alice


Student Age: 20
Student Grade: A
Student Name: Bob
Student Age: 22
Student Grade: B
2.a) Write a Java program to illustrate the concept of Single level and Multi level Inheritance.
// Base class: Bank
class Bank {
// Property of the Bank class
String bankName;
// Constructor to initialize bank name
public Bank(String bankName) {
[Link] = bankName;
}

// Method to display bank information


public void displayBankInfo() {
[Link]("Bank Name: " + bankName);
}
}

// Single Level Inheritance: SavingsAccount is a subclass of Bank


class SavingsAccount extends Bank {
// Property of SavingsAccount class
double balance;

// Constructor to initialize SavingsAccount with balance and bank name


public SavingsAccount(String bankName, double balance) {
super(bankName); // Call the parent (Bank) constructor
[Link] = balance;
}

// Method to display savings account balance


public void displayBalance() {
[Link]("Savings Account Balance: $" + balance);
}

// Method to deposit money into savings account


public void deposit(double amount) {
balance += amount;
[Link]("Deposited $" + amount + " into Savings Account.");
}
}

// Multi-Level Inheritance: CheckingAccount is a subclass of SavingsAccount


class CheckingAccount extends SavingsAccount {
// Property of CheckingAccount class
double overdraftLimit;

// Constructor to initialize CheckingAccount with overdraft limit and balance


public CheckingAccount(String bankName, double balance, double overdraftLimit) {
super(bankName, balance); // Call the parent (SavingsAccount) constructor
[Link] = overdraftLimit;
}

// Method to display checking account info including overdraft limit


public void displayCheckingInfo() {
[Link]("Checking Account Balance: $" + balance);
[Link]("Overdraft Limit: $" + overdraftLimit);
}

// Method to withdraw money from checking account (with overdraft protection)


public void withdraw(double amount) {
if (amount <= balance + overdraftLimit) {
balance -= amount;
[Link]("Withdrew $" + amount + " from Checking Account.");
} else {
[Link]("Insufficient funds. Cannot withdraw more than available balance + overdraft limit.");
}
}
}

// Main class to test the inheritance


public class Main2 {
public static void main(String[] args) {
// Single level inheritance: SavingsAccount object
[Link]("---- Savings Account ----");
SavingsAccount savings = new SavingsAccount("City Bank", 5000);
[Link](); // Inherited from Bank
[Link](); // Own method
[Link](1500); // Own method
[Link](); // Check updated balance

// Multi-level inheritance: CheckingAccount object


[Link]("\n---- Checking Account ----");
CheckingAccount checking = new CheckingAccount("City Bank", 3000, 500);
[Link](); // Inherited from Bank
[Link](); // Own method
[Link](3500); // Withdraw with overdraft
[Link](); // Check updated info
}
}

Output:

Bank Name: City Bank


Savings Account Balance: $5000.0
Deposited $1500.0 into Savings Account.
Savings Account Balance: $6500.0
Bank Name: City Bank
Checking Account Balance:
$3000.0 Overdraft Limit:
$500.0
Withdrew $3500.0 from Checking
Account. Checking Account
Balance: $-500.0
Overdraft Limit: $500.0
2.b) Write a Java program to illustrate the concept of class with method overloading and method
overriding
Method Overloading Program
import [Link];

class Shape {
double calculateArea(double r)
{
return [Link]*r*r;
}
double calculateArea(double l,double w)
{
return l*w;
}
double calculateArea(int s)
{
return s*s;
}
}
public class MethodOverloadingExample {
public static void main(String[] args) {

Shape shape = new Shape();


Scanner scanner = new Scanner([Link]);
[Link]("radius of the circle: ");
double radius = [Link]();
double circleArea = [Link](radius);
[Link]("Area of the circle: %.2f\n", circleArea);
[Link]("length of the rectangle: ");
double length = [Link]();
[Link]("width of the rectangle: ");
double width = [Link]();
double rectangleArea = [Link](length, width);
[Link]("Area of the rectangle: %.2f\n", rectangleArea);
[Link]("side length of the square: ");
int side = [Link]();
double squareArea = [Link](side);
[Link]("Area of the square: %.2f\n", squareArea);
[Link]();
}
}

Output:
radius of the circle: 3.5
Area of the circle: 38.48
length of the rectangle: 0
width of the rectangle: 5
Area of the rectangle: 0.00
side length of the square: 6
Area of the square: 36.00

MethodOverridingExample

import [Link].*;
class Calculator {
double calculate(double a,double b)
{
return a+b;
}

}
class ScientificCalculator extends Calculator {
// @Override
double calculate(double a,double b)
{
return a*b;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
Calculator calculator = new Calculator();
[Link]("a = ");
double a=[Link]();
[Link]("b = ");
double b=[Link]();
[Link]("a+b: " + [Link](a,b));

ScientificCalculator scientificCalculator = new ScientificCalculator();


[Link]("a*b: " + [Link](a, b));
}
}

Output:
a = 96.2
b = 63.5
a+b: 159.7
a*b: 6108.7

3.a) Write a Java program to demonstrate the Interfaces & Abstract Classes.
package q18023;
// import required classes
// Define interface Calculator { }
import [Link].*;
interface Calculator
{
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
}
class BasicCalculator implements Calculator {
// Define required methods
public double add(double a,double b)
{
return a+b;
}
public double subtract(double a, double b)
{
return a-b;
}
public double multiply(double a, double b)
{
return a*b;
}
public double divide(double a, double b){
return a/b;
}
}
public class Calc {
public static void main(String[] args) {
Calculator calculator = new BasicCalculator();
Scanner sc=new Scanner([Link]);
int a=[Link]();
int b=[Link]();
double result1 = [Link](a, b);
double result2 = [Link](a, b);
double result3 = [Link](a, b);
double result4 = [Link](a, b);

[Link]("Addition: " + result1);


[Link]("Subtraction: " + result2);
[Link]("Multiplication: " + result3);
[Link]("Division: " + result4);

}
}

Output:

5
10
Addition:·15.0
Subtraction:·-5.0
Multiplication:·50.0
Division:·0.5

Abastractclass implements

package q11286;
abstract class CalcArea {
abstract double triangleArea(double b, double h);
abstract double rectangleArea(double l, double b);
abstract double squareArea(double s);
abstract double circleArea(double r);
}

class FindArea extends CalcArea {


@Override
double triangleArea(double b, double h) {
return 0.5 * b * h;
}
@Override
double rectangleArea(double l, double b) {
return l * b;
}

@Override
double squareArea(double s) {
return s * s;
}

@Override
double circleArea(double r) {
return 3.14 * r * r;
}
}
public class Area {
public static void main(String args[]) {
if ([Link] < 2) {
[Link]("Please provide two arguments.");
return;
}
double arg1 = [Link](args[0]);
double arg2 = [Link](args[1]);
FindArea area = new FindArea();

[Link]("Area of triangle : "+[Link](arg1, arg2));


[Link]("Area of rectangle : "+ [Link](arg1, arg2));
[Link]("Area of square : "+[Link](arg1));
[Link]("Area of circle : "+[Link](arg2));
}
}
// Write all the classes with definitions

Output:

Area·of·triangle·:·7.529400000000001
Area·of·rectangle·:·15.058800000000002
Area·of·square·:·12.6736
Area·of·circle·:·56.18370600000001

3 b) Write a Java program to implement the concept of exception handling.


import [Link].*;
class CheckWeight {

// Method to validate the weight and throw the custom exception


public static void validateWeight(int weight) throws InvalidWeight {
if (weight > 100) {
throw new InvalidWeight("Exception caught: "+weight+" is invalid
weight");
}
else
[Link](weight+" is the valid weight");
}

// Main method to test the validWeight method


public static void main(String[] args) {

// Create an instance of CheckWeight class


CheckWeight Ck=new CheckWeight();
// Create a Scanner object to read input
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter the weight
[Link]("Enter weight: ");
// Read the weight from the user
int weight = [Link]();
// Call the validWeight method and handle the custom exception
try {
// Validate the weight
validateWeight(weight);
}
// Catch and handle the InvalidWeight exception
catch (InvalidWeight e) {

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

}
}
// Define a user-defined exception named InvalidWeight
class InvalidWeight extends Exception {
public InvalidWeight(String message) {
super(message);
}
}

Output:
Enter·weight:·101

Exception·caught:·101·is·invalid·weight
3.c) Write a Java program to illustrate the concept of threading using Thread Class
and runnable Interface.

// Using Thread class


class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread (Thread Class): " + i);
try {
[Link](500); // Sleep for 500ms
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}

// Using Runnable interface


class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread (Runnable Interface): " + i);
try {
[Link](500); // Sleep for 500ms
} catch (InterruptedException e) {
[Link]("Runnable interrupted.");
}
}
}
}

public class ThreadingExample {


public static void main(String[] args) {
// Using Thread class
MyThread thread1 = new MyThread();
// Using Runnable interface
MyRunnable runnable = new MyRunnable();
Thread thread2 = new Thread(runnable);

// Start both threads


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

Output:

Thread (Thread Class): 1


Thread (Runnable Interface): 1
Thread (Thread Class): 2
Thread (Runnable Interface): 2
Thread (Thread Class): 3
Thread (Runnable Interface): 3
Thread (Thread Class): 4
Thread (Runnable Interface): 4
Thread (Thread Class): 5
Thread (Runnable Interface): 5

4. Write a Java program to illustrate the concept of Thread synchronization.


package q18198;
import [Link];

class TablePrinter implements Runnable {


private int tableNumber;

public TablePrinter(int tableNumber) {


[Link] = tableNumber;
}

//write your code....


public void run() {
try {
for (int i = 1; i <= 10; i++) {
// Print the multiplication result for this table number
[Link]( + tableNumber + " * " + i + " = " + (tableNumber * i));
// Sleep for 100 milliseconds to add a small delay
[Link](100);
}
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of tables:");
int numTables = [Link]();
Thread[] threads = new Thread[numTables];

//write your code....


for (int i = 1; i <= numTables; i++) {
TablePrinter tablePrinter = new TablePrinter(i); // Create a new TablePrinter for table
i
threads[i - 1] = new Thread(tablePrinter); // Assign the thread to the array
threads[i - 1].start(); // Start the thread
}
try {
for (int i = 0; i < numTables; i++) {
threads[i].join(); // Wait for each thread to finish
}
} catch (InterruptedException e) {
[Link]("Main thread interrupted: " + [Link]());
}
[Link]();

}
}

Output:
Enter the number of tables:1
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
1 * 10 = 10
5. Write a Java Program that reads a line of integers, and then displays each
integer, and the sum of all the integers (Use String Tokenizer class of [Link])
import [Link];
import [Link];
public class sumofIntegers {
public static void main(String args[]) {
Scanner scanner=new Scanner([Link]);
String input = [Link]();
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while ([Link]()) {
// Parse each token as an integer
int num = [Link]([Link]());

// Print the current number


[Link](num);

// Add the current number to the sum


sum += num;
}
[Link](sum);
}
}
Output:
123456
1
2
3
4
5
6
21

6.a) Write a Java program that reads a file name from the user, and then displays
inform action about whether the file exists, whether the file is readable, whether the file
is writable, the type of file and the ength of the file in bytes.
import [Link];
import [Link];
public class FileInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for the file name
[Link]("Enter the file name (with path if necessary): ");
String fileName = [Link]();
// Create a File object
File file = new File(fileName);
// Check if the file exists
if ([Link]()) {
[Link]("File exists: Yes");
// Check if the file is readable
[Link]("Readable: " + ([Link]() ? "Yes" : "No"));
// Check if the file is writable
[Link]("Writable: " + ([Link]() ? "Yes" : "No"));
// Get the file type (directory or file)
if ([Link]()) {
[Link]("Type: Directory");
} else {
[Link]("Type: File");
}
// Get the length of the file in bytes
[Link]("Length: " + [Link]() + " bytes");
} else {
[Link]("File exists: No");
}
// Close the scanner
[Link]();
}
}

Output:
Enter the file name (with path if necessary): C:\Users\batch_vfqr8xp\OneDrive\Desktop\
JAVA_PGMS\[Link]
File exists: Yes
Readable: Yes
Writable: Yes
Type: File
Length: 19 bytes
6.b) Write a Java program to illustrate the concept of I/O Streams.
import [Link].*;
import [Link];
public class IOStreamExample {
public static void main(String[] args) {
// File paths for input and output files
Scanner scanner = new Scanner([Link]);
[Link]("file name:");
String inputFileName = [Link]();
String outputFile = "[Link]";
// Create InputStream and OutputStream objects
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
// Create FileInputStream to read data from the input file
File inputFile = new File(inputFileName);

// Check if the input file exists


if (![Link]()) {
[Link]("No such file");
return;
}

fileInputStream = new FileInputStream(inputFile);

// Create FileOutputStream to write data to the output file


fileOutputStream = new FileOutputStream(outputFile);

int content;
// Read each byte from the input file and write it to the output file
while ( (content = [Link]()) != -1 ){
[Link](content);
}
// Reading from the output file and printing its contents
FileInputStream outputFileStream = new FileInputStream(outputFile);
StringBuilder outputContent = new StringBuilder();
while ((content = [Link]()) != -1) {
[Link]((char) content);
}
[Link]("Contents of the output file:");
[Link]([Link]());

// Close the output file stream


}
catch (IOException e) {
[Link]("No such file");
} finally {
try {
// Close the streams to release resources
if (fileInputStream != null) {
[Link]();
}
if (fileOutputStream != null) {
[Link]();
}
} catch (IOException e) {
[Link]("Error while closing streams: " + [Link]());
}
}
}
}

Output:
file name:[Link]
Contents of the output file:
Hello IT Department

7. a) Write a Java applet program to implement Color and Graphics class

import [Link].*;
import [Link].*;
import [Link];
/*<applet code="GraphicDemo" width=350 height=700> </applet> */
public class GraphicDemo extends Applet {
public void init()
{
Color c1 = [Link];
setBackground(c1);
Color c2=[Link];
setForeground(c2);
}
public void paint(Graphics g) {
// Draw lines.
[Link](0, 0, 100, 90);
[Link](0, 90, 100, 10);
[Link](40, 25, 250, 80);
// Draw rectangles.
[Link](10, 150, 60, 50);
[Link](100, 150, 60, 50);
[Link](190, 150, 60, 50, 15, 15);
[Link](280, 150, 60, 50, 30, 40);
// Draw Ellipses and Circles
[Link](10, 250, 50, 50);
[Link](90, 250, 75, 50);
[Link](190, 260, 100, 40);
// Draw Arcs
[Link](10, 350, 70, 70, 0, -180); [Link](60, 350, 70, 70, 0, -90);
// Draw a polygon
int xpoints[] = {10, 200, 10, 200, 10};
int ypoints[] = {450, 450, 650, 650, 450};
int num = 5;
[Link](xpoints, ypoints, num);
int xmpoints[]={40,40,50,60,60};
int ympoints[]={60,40,50,40,60}; //Another polygon
[Link](xmpoints, ympoints, num); }
}

Output:
7.b) write a simple java program to implement AWT class
import [Link].*;
import [Link].*;

public class SimpleAWTExample extends Frame implements ActionListener {

// Components
Label label;
Button button;

// Constructor to set up the UI


public SimpleAWTExample() {
// Set frame title
setTitle("AWT Example");

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

// Initialize components
label = new Label("Click the button");
button = new Button("Click Me");

// Add action listener to button


[Link](this);

// Add components to frame


add(label);
add(button);

// Set size and make it visible


setSize(300, 150);
setVisible(true);

// Window close handler


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // Close the window
}
});
}

// Handle button click event


public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}

// Main method
public static void main(String[] args) {
new SimpleAWTExample();
}
}

8. Write a java Applet program to implement Mouse and Key events

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

/* <applet code="MouseKeyApplet" width=400 height=300></applet> */

public class MouseKeyApplet extends Applet implements MouseListener,


MouseMotionListener, KeyListener {
String message = "";
int mouseX = 0, mouseY = 0;

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setBackground([Link]);
setFocusable(true); // Important for key events
}

public void paint(Graphics g) {


[Link](message, mouseX, mouseY);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

public void mouseEntered(MouseEvent e) {


message = "Mouse Entered";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

public void mouseExited(MouseEvent e) {


message = "Mouse Exited";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

public void mousePressed(MouseEvent e) {


message = "Mouse Pressed";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

public void mouseReleased(MouseEvent e) {


message = "Mouse Released";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

// MouseMotionListener methods
public void mouseDragged(MouseEvent e) {
message = "Mouse Dragged";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

public void mouseMoved(MouseEvent e) {


message = "Mouse Moved";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}

// KeyListener methods
public void keyPressed(KeyEvent e) {
message = "Key Pressed: " + [Link]();
repaint();
}

public void keyReleased(KeyEvent e) {


message = "Key Released: " + [Link]();
repaint();
}

public void keyTyped(KeyEvent e) {


message = "Key Typed: " + [Link]();
repaint();
}
}

To Run the Applet


1. Save the file as `[Link]`.
2. Compile: `javac [Link]`
3. Run using an applet viewer:

appletviewer [Link]
9. Write a Java applet program to implement Adapter classes

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

/* <applet code="MouseAdapterExample" width=400 height=300></applet> */

public class MouseAdapterExample extends Applet {

String message = "";


int x = 0, y = 0;

public void init() {


setBackground([Link]);

// Attach custom mouse adapter


addMouseListener(new MyMouseAdapter());
}

public void paint(Graphics g) {


[Link](message, x, y);
}

// Custom adapter class


class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
x = [Link]();
y = [Link]();
message = "Mouse Clicked at (" + x + ", " + y + ")";
repaint();
}
}
}

1. Save as `[Link]`
2. Compile: `javac [Link]`
3. Run with: `appletviewer [Link]
OutPut:

10. Write a JDBC program to implement CURD operation


/*Create a table in database as follows
create table students(id number(20) primary key, name varchar(20),grade number)/*

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

public class StudentJDBCApp {


static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
static final String USER = "system";
static final String PASS = "system"; // Replace with your MySQL password

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

try {
[Link]("[Link]");
Connection conn = [Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
while (true) {
[Link]("\n1. Add Student");
[Link]("2. View Students");
[Link]("3. Update Student Grade");
[Link]("4. Delete Student");
[Link]("5. Exit");
[Link]("Choose an option: ");
int choice = [Link]();
[Link](); // consume newline

switch (choice) {
case 1:
[Link]("Enter ID: ");
int id = [Link]();
[Link]();
[Link]("Enter name: ");
String name = [Link]();
[Link]("Enter grade: ");
int grade = [Link]();
String insert = "INSERT INTO students (id,name, grade) VALUES
("+id+",'" + name + "', " + grade + ")";
[Link](insert);
[Link]("Student added.");
break;

case 2:
ResultSet rs = [Link]("SELECT * FROM students");
[Link]("ID | Name | Grade");
while ([Link]()) {
[Link]([Link]("id") + " | " + [Link]("name") + " |
" + [Link]("grade"));
}
break;

case 3:
[Link]("Enter student ID: ");
int id1 = [Link]();
[Link]("Enter new grade: ");
int newGrade = [Link]();
[Link]("UPDATE students SET grade = " + newGrade +
" WHERE id = " + id1);
[Link]("Grade updated.");
break;
case 4:
[Link]("Enter student ID to delete: ");
int delId = [Link]();
[Link]("DELETE FROM students WHERE id = " +
delId);
[Link]("Student deleted.");
break;

case 5:
[Link]("Goodbye!");
[Link]();
[Link]();
[Link]();
return;

default:
[Link]("Invalid choice.");
}
}

} catch (Exception e) {
[Link]();
}
}
}

Output:
//Note Create lib folder in current directory paste [Link] folder and follow
the instructions
To compile:

C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>javac -cp .;lib\[Link]


[Link]

To run the code:


C:\Users\batch_vfqr8xp\OneDrive\Desktop\JAVA_PGMS>java -cp .;lib\[Link]
StudentJDBCApp

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 1
Enter ID: 7
Enter name: naga
Enter grade: 5
Student added.

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
1 | null | 3
2 | null | 4
7 | naga | 5

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 3
Enter student ID: 7
Enter new grade: 1
Grade updated.

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
1 | null | 3
2 | null | 4
7 | naga | 1

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 4
Enter student ID to delete: 1
Student deleted.

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option: 2
ID | Name | Grade
2 | null | 4
7 | naga | 1

1. Add Student
2. View Students
3. Update Student Grade
4. Delete Student
5. Exit
Choose an option:5

11. 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.
import [Link].*;
import [Link].*;

public class SimpleCalculator extends Frame implements ActionListener {


TextField display;
String operator = "";
double num1 = 0, num2 = 0;

public SimpleCalculator() {
setTitle("Simple Calculator");
setLayout(new BorderLayout());

// Text field at the top


display = new TextField();
add(display, [Link]);

// Panel with buttons


Panel panel = new Panel();
[Link](new GridLayout(4, 4, 5, 5));

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

for (String b : buttons) {


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

add(panel, [Link]);

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

// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();

if ([Link]("C")) {
[Link]("");
operator = "";
num1 = num2 = 0;
} else if ([Link]("=")) {
num2 = [Link]([Link]());
double result = 0;

switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "%": result = num1 % num2; break;
}

[Link]([Link](result));
operator = "";
} else if ("+-*%".contains(cmd)) {
num1 = [Link]([Link]());
operator = cmd;
[Link]("");
} else {
[Link]([Link]() + cmd);
}
}

public static void main(String[] args) {


new SimpleCalculator();
}
}

12. Write Servlet application for following


i. Html & Servlet Communication
ii. Select record from database
iii. Application for login page
iv. Insert record into database

Structure of the Project:

WebApp/
├── [Link]
├── [Link]
├── [Link]
├── WEB-INF/
│ └── [Link]
└── src/
├── [Link]
├── [Link]
├── [Link]

1. [Link] (HTML to Servlet communication)


<!DOCTYPE html>
<html>
<head><title>HTML Servlet Communication</title></head>
<body>
<h2>Welcome Page</h2>
<form action="[Link]">
<input type="submit" value="Login">
</form>
<form action="[Link]">
<input type="submit" value="Insert Record">
</form>
<form action="select" method="get">
<input type="submit" value="View Records">
</form>
</body>
</html>
Output:

[Link]
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Output:

[Link]

<!DOCTYPE html>
<html>
<head><title>Insert</title></head>
<body>
<h2>Insert New Record</h2>
<form action="insert" method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output:
[Link]

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

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String user = [Link]("username");


String pass = [Link]("password");

try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = [Link]("SELECT * FROM users WHERE
username=? AND password=?");
[Link](1, user);
[Link](2, pass);

ResultSet rs = [Link]();

if ([Link]()) {
[Link]("<h2>Welcome, " + user + "</h2>");
} else {
[Link]("<h2>Invalid Credentials</h2>");
}
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class InsertServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String name = [Link]("name");


String email = [Link]("email");

try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
PreparedStatement ps = [Link]("INSERT INTO users(name,email)
VALUES(?,?)");
[Link](1, name);
[Link](2, email);

int i = [Link]();
if (i > 0) {
[Link]("<h2>Record inserted successfully</h2>");
}

[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class SelectServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:@localhost:1521:xe",
"system", "system");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");

[Link]("<h2>User Records:</h2>");
[Link]("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>");

while ([Link]()) {
[Link]("<tr><td>" + [Link]("id") + "</td><td>" +
[Link]("name") + "</td><td>" + [Link]("email") + "</td></tr>");
}

[Link]("</table>");
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

[Link]
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>InsertServlet</servlet-name>
<servlet-class>InsertServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertServlet</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SelectServlet</servlet-name>
<servlet-class>SelectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectServlet</servlet-name>
<url-pattern>/select</url-pattern>
</servlet-mapping>
</web-app>
//Create database in Oracle 10g
--login to oracle10 express edition:
--[Link]
--username: system
--password: system
-- Step 1: Create the table
CREATE TABLE users (
id NUMBER PRIMARY KEY,
username VARCHAR2(50),
password VARCHAR2(50),
name VARCHAR2(50),
email VARCHAR2(50)
);

-- Step 2: Create a sequence for generating unique IDs


CREATE SEQUENCE users_seq
START WITH 1
INCREMENT BY 1
NOCACHE;

-- Step 3: Create a trigger to assign sequence value to ID


CREATE OR REPLACE TRIGGER users_trigger
BEFORE INSERT ON users
FOR EACH ROW
BEGIN
SELECT users_seq.NEXTVAL INTO :[Link] FROM dual;
END;
/

insert into users values(1,'naga','naga','naga','naga@[Link]')

select * from users

Common questions

Powered by AI

Constructors in Java initialize objects when they are created. In the 'Student' class, a constructor is used to initialize the object with a name, age, and grade, ensuring the object starts with a valid state . Constructors help in setting initial values and establishing invariants for objects. For instance, 'CheckingAccount' uses a constructor to initialize its bank name, balance, and overdraft limit, thus ensuring these properties have defined values upon object creation .

Method overloading occurs when multiple methods in the same class have the same name but different parameters. For example, in the 'Shape' class, the 'calculateArea' method is overloaded to compute areas of different shapes (circle, rectangle, square) based on different input parameters . Method overriding, on the other hand, occurs when a subclass provides a specific implementation for a method already defined in its superclass. An example is in 'ScientificCalculator', which overrides the 'calculate' method of its superclass 'Calculator' to perform multiplication instead of addition .

Exception handling in Java involves using try-catch blocks to manage exceptions and ensure program stability. The 'CheckWeight' class demonstrates this by throwing a custom 'InvalidWeight' exception if a specified condition is met (weight greater than 100). Developers write exception scenarios in try blocks and capture anticipated exceptions in catch blocks, providing error messages or resolving actions . The goal is to prevent application crashes and maintain operability during exceptional conditions.

Java implements single-level inheritance where a class inherits directly from another class, such as 'SavingsAccount' inheriting from 'Bank', allowing it to access 'Bank' properties and methods directly . Multi-level inheritance is implemented when a class derives from a class that is already derived (e.g., 'CheckingAccount' inheriting from 'SavingsAccount'), providing a structure where classes can build upon previously defined classes, enhancing extensibility and reuse . Single-level simplifies relationships, while multi-level allows for more complex hierarchies and behavior extensions.

JDBC (Java Database Connectivity) enables Java applications to interact with databases through operations such as Create, Read, Update, and Delete (CRUD). In the 'StudentJDBCApp', SQL queries are utilized to perform these operations: insertion (using 'INSERT INTO'), reading (through 'SELECT'), updating (with 'UPDATE'), and deletion ('DELETE FROM') of student records in a database . JDBC encapsulates these database interactions, offering a structured approach to manage data within Java applications efficiently.

In Java, interfaces define a contract with abstract methods that implementing classes must provide. Abstract classes can include both fully defined methods and abstract ones. For instance, 'Calculator' is an interface mandating its methods be implemented by 'BasicCalculator' . A developer might choose an interface when needing to define capabilities shared across different classes, without enforcing a class hierarchy. Abstract classes are preferred when creating a base class with shared code, allowing some methods to be implemented while still requiring others to be overridden. This choice affects flexibility and design architecture.

A basic calculator application in Java uses classes from java.awt and java.awt.event packages to build and manage GUI components. The 'SimpleCalculator' class extends Frame, incorporating buttons for digits and operations arranged in a GridLayout. Event handling is implemented via ActionListener; button actions are defined in the 'actionPerformed' method, manipulating text fields to reflect user interactions and calculations. This setup facilitates intuitive user interaction through a graphical interface, responding to button presses for arithmetic operations .

Encapsulation in Java restricts direct access to an object's data and methods, which protects against unauthorized modification and misuse. The examples, however, lack strict encapsulation as fields like 'name', 'age', and 'grade' in the 'Student' class are accessed directly rather than through getters and setters . Proper encapsulation would involve declaring these fields as private and providing public methods to access and update them, ensuring controlled access and modification. This enhances maintainability and security.

In Java, file I/O can be managed directly through streams, which offer byte or character-level operations, facilitating efficient data transfer, especially for large files. Streams provide lower-level, precise control but require careful exception handling. High-level classes like Scanner and PrintWriter abstract these complexities, allowing more straightforward methods for reading from and writing to files by wrapping streams in a more user-friendly API. This abstraction improves ease of use at the cost of reduced performance tuning and flexibility .

Multithreading in Java enables concurrent execution of different parts of a program, improving performance by making better use of CPU resources. The given example demonstrates creating multiple threads each responsible for calculating and printing a different multiplication table concurrently . This approach allows threads to execute independently, reducing overall completion time and enhancing application responsiveness, as tasks run in parallel rather than sequentially. Proper thread management, including synchronization and exception handling, ensures safe and efficient operation.

You might also like