0% found this document useful (0 votes)
10 views48 pages

Java Programming Concepts and Examples

Uploaded by

karthik.d0104
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)
10 views48 pages

Java Programming Concepts and Examples

Uploaded by

karthik.d0104
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

EX NO: 1

DATE:
METHOD OVERLOADING

AIM:
To demonstrate method overloading using different data types.

PROCEDURE:

1. Create methods with the same name but different parameter types.
2. Call them using an object.

PROGRAM:

class Overload {
void display(int a) {
[Link]("Integer: " + a);
}

void display(String a) {
[Link]("String: " + a);
}

public static void main(String[] args) {


Overload obj = new Overload();
[Link](100);
[Link]("Java");
}
}
OUTPUT:

RESULT:

Thus the program has been executed successfully.


EX NO: 2
DATE:
Constructor - Book Class

AIM:

To initialize object values using constructor.

PROCEDURE:

1. Define a class with a constructor.


2. Pass values via constructor and display them.

PROGRAM:

class Book {
String title;

Book(String t) {
title = t;
}

void show() {
[Link]("Book: " + title);
}

public static void main(String[] args) {


Book b = new Book("Java Programming");
[Link]();
}
}
OUTPUT:

RESULT:

Thus the program has been executed successfully.

EX NO: 3
DATE:
Method Overriding

AIM:

To override a method from the parent class.

PROCEDURE:

1. Create a method in the parent class.


2. Override it in the child class.

PROGRAM:

class Vehicle {
void start() {
[Link]("Vehicle starting...");
}
}

class Car extends Vehicle {


void start() {
[Link]("Car starting...");
}

public static void main(String[] args) {


Car c = new Car();
[Link]();
}
}

OUTPUT:
RESULT:

Thus the program has been executed successfully.

[Link]
DATE:
SUPER KEYWORD

AIM:

To use super() to call the superclass constructor.

PROCEDURE:
1. Create a superclass with a constructor.

[Link] super() in the subclass constructor.

PROGRAM:

class Person {
Person(String name) {
[Link]("Person: " + name);
}
}

class Employee extends Person {


Employee(String name) {
super(name);
[Link]("Employee Created");
}

public static void main(String[] args) {


Employee e = new Employee("Ravi");
}
}
OUTPUT:

RESULT:
Thus the program has been executed successfully.

[Link]
DATE:
ABSTRACT CLASS

AIM:

To define an abstract class and implement it.

PROCEDURE:

[Link] an abstract class with an abstract method.


[Link] and implement the method.

PROGRAM:

abstract class Shape {


abstract void area();
}

class Circle extends Shape {


void area() {
[Link]("Area of Circle");
}

public static void main(String[] args) {


Shape s = new Circle();
[Link]();
}
}

OUTPUT:
RESULT:
Thus the program has been executed successfully.
[Link]
DATE:
FINAL KEYWORD

AIM:

To demonstrate use of final variable, method, and class.

PROCEDURE:

1. Declare final class, method, and variable.


2. Show restrictions.

PROGRAM:

final class FinalClass {


final int num = 10;

final void display() {


[Link]("Final method: " + num);
}
}

public class TestFinal {


public static void main(String[] args) {
FinalClass f = new FinalClass();
[Link]();
}
}

OUTPUT:
RESULT:
Thus the program has been executed successfully.
[Link]
DATE:
INTERFACE

AIM:
To implement an interface in Java.

PROCEDURE:

1. Create an interface with a method.


2. Implement it in two classes.

PROGRAM:

interface Playable {
void play();
}

class Music implements Playable {


public void play() {
[Link]("Playing music...");
}
}

class Video implements Playable {


public void play() {
[Link]("Playing video...");
}

public static void main(String[] args) {


Playable m = new Music();
Playable v = new Video();
[Link]();
[Link]();
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully.

[Link]
DATE:
USER DEFINED PACKAGE

AIM:

To create and use a custom package.

PROCEDURE:

1. Create a package and a class inside it.


2. Use the class in another file.

PROGRAM:

package bank;

public class Account {

private double balance;

public Account(double initialBalance) {

balance = [Link](initialBalance, 0);

public void deposit(double amount) {

if (amount > 0) balance += amount;

public void withdraw(double amount) {

if (amount > 0 && amount <= balance) balance -= amount;

public double getBalance() {

return balance;

}
package bank;
import [Link];

public class BankApp {


public static void main(String[] args) {
Account acc = new Account(1000);
[Link](500);
[Link](200);
[Link]("Final Balance: $" + [Link]());
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully.
[Link]
DATE:
ENCAPSULATION

AIM:

To implement encapsulation using getters and setters.

PROCEDURE:

1. Create private variables.


2. Access them through public methods.

PROGRAM:

class Student {
private String name;
private int age;

public void setName(String n) {


name = n;
}

public void setAge(int a) {


age = a;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
public static void main(String[] args) {
Student s = new Student();
[Link]("Amit");
[Link](21);
[Link]([Link]() + " " + [Link]());
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully

[Link]
DATE:
JAVA ARRAY
AIM:

To find the smallest and largest elements in an array.

PROCEDURE:

1. Input array elements.


2. Use a loop to find min and max.

PROGRAM:

import [Link];
class MinMax {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 7};
int min = arr[0], max = arr[0];

for (int i : arr) {


if (i< min) min = i;
if (i> max) max = i;
}

[Link]("Min: " + min);


[Link]("Max: " + max);
}
}

OUTPUT:
RESULT:

Thus the program has been executed successfully.


[Link]:10A
DATE:
CUSTOM EXCEPTION

AIM:

To create and use a custom exception.

PROCEDURE:
1. Create custom exception class.
2. Throw exception based on condition.

PROGRAM:

class InvalidAgeException extends Exception {


InvalidAgeException(String msg) {
super(msg);
}
}

public class TestAge {


public static void main(String[] args) throws InvalidAgeException {
int age = 15;
if (age < 18)
throw new InvalidAgeException("Age must be 18 or above.");
else
[Link]("Valid Age");
}
}

OUTPUT:
RESULT:
Thus the program has been executed successfully.

[Link]:10B
DATE:
ARITHMETIC EXCEPTION
AIM:
To write a Java program that demonstrates exception handling using a try-catch block for an
ArithmeticException caused by division by zero.

PROCEDURE:
1. Define the Class:
o Create a public class named Divide.

2. Create the Main Method:


o Use the main method as the entry point for the program.

3. Set Up the Try Block:


o Inside the try block, write a statement that attempts to divide an integer by
zero: int a = 5 / 0;.

o This operation will cause an ArithmeticException at runtime.

4. Handle the Exception:


o Use a catch block that catches ArithmeticException.

o Display an appropriate message like: [Link]("Cannot divide by


zero");.

5. Compile and Run:


o Compile the program using javac [Link].

o Run it using java Divide.

o Observe that instead of the program crashing, it gracefully handles the error
and prints the message.

PROGRAM:

public class Divide {


public static void main(String[] args) {
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully.

[Link]:10C
DATE:
ARRAY INDEX OUT OF BOUNDS EXCEPTION

AIM:

To demonstrate exception handling in Java using a try-catch block for an


ArrayIndexOutOfBoundsException.

PROCEDURE:

1. Define a class:
Create a public class named ArrayTest.
2. Create a main method:
Inside the class, define the main() method, which serves as the entry point for the
program.
3. Declare and initialize an array:
Create an integer array arr with elements {1, 2, 3}.
4. Access an invalid index:
Use [Link](arr[5]); to try to access the 6th element of the array, which
does not exist (array size is 3, valid indices are 0–2).
5. Use try-catch block:
o Wrap the array access inside a try block to monitor for exceptions.

o Catch the ArrayIndexOutOfBoundsException in the catch block and print


"Index out of bounds" to handle the error gracefully.
6. Compile and run the program:
Observe the output to confirm that the exception is caught and handled without
terminating the program abruptly.

PROGRAM:

public class ArrayTest {


public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Index out of bounds");
}
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully.
[Link]: 11
DATE:
MULTITHREADING – EVEN & ODD NUMBERS

AIM:
To create two threads that print even and odd numbers concurrently from 1 to 50.

PROCEDURE:

1. Create two classes implementing Runnable.


2. Start two threads to print even and odd numbers.

PROGRAM:

class EvenThread implements Runnable {


public void run() {
for (int i = 2; i<= 50; i += 2) {
[Link]("Even: " + i);
}
}
}

class OddThread implements Runnable {


public void run() {
for (int i = 1; i<= 49; i += 2) {
[Link]("Odd: " + i);
}
}
}

public class EvenOddThreads {


public static void main(String[] args) {
Thread t1 = new Thread(new EvenThread());
Thread t2 = new Thread(new OddThread());
[Link]();
[Link]();
}
}

OUTPUT:

RESULT:
Thus the program has been executed successfully.

[Link]
DATE:
FILE HANDLING-COPY IMAGE FILE

AIM:

To copy an image file using FileInputStream and FileOutputStream.

PROCEDURE:

1. Use FileInputStream to read source file.


2. Use FileOutputStream to write to destination file.

PROGRAM:
import [Link].*;
public class CopyImage {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("[Link]");
FileOutputStream out = new FileOutputStream("[Link]");

int data;
while ((data = [Link]()) != -1) {
[Link](data);
}

[Link]();
[Link]();
[Link]("File copied successfully.");
} catch (IOException e) {
[Link]("File error: " + e);
}
}
}
OUTPUT:

RESULT:

Thus the program has been executed successfully.


[Link]
DATE:
NETWORKING – SERVER & CLIENT(ECHO)

AIM:
To implement a simple server and client using Socket and ServerSocket.

PROCEDURE:

1. Create a server that listens for a client.


2. Create a client to send and receive messages.

PROGRAM:

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

public class Server {


public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]();

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));


PrintWriter out = new PrintWriter([Link](), true);

String msg = [Link]();


[Link]("Client says: " + msg);
[Link]("Echo: " + msg);

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

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

public class Client {


public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("Hello from client!");


[Link]("Server replied: " + [Link]());

[Link]();
}
}

OUTPUT:
RESULT:

Thus the program has been executed successfully.


[Link]:14A
DATE:
SWING CALCULATOR

AIM:
To create a simple calculator using Swing GUI.

PROCEDURE:

1. Create a GUI with text fields and buttons.


2. Perform arithmetic operations based on button clicks.

PROGRAM:
import [Link].*;
import [Link].*;

public class Calculator {


public static void main(String[] args) {
JFrame f = new JFrame("Calculator");
JTextField t1 = new JTextField(), t2 = new JTextField();
JLabel result = new JLabel("Result:");
JButton add = new JButton("+");

[Link](30, 30, 100, 30);


[Link](150, 30, 100, 30);
[Link](100, 80, 50, 30);
[Link](30, 130, 200, 30);

[Link](e -> {
int a = [Link]([Link]());
int b = [Link]([Link]());
[Link]("Result: " + (a + b));
});

[Link](t1); [Link](t2); [Link](add); [Link](result);


[Link](300, 200);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT:

RESULT:

Thus the program has been executed successfully.


[Link]:14B
DATE:
SWING LOGIN FORM

AIM:
To design a login form with username and password validation.

PROCEDURE:

1. Create text fields for username and password.


2. Check against hardcoded values.

PROGRAM:

import [Link].*;

public class LoginForm {


public static void main(String[] args) {
JFrame f = new JFrame("Login");
JTextField user = new JTextField();
JPasswordField pass = new JPasswordField();
JButton login = new JButton("Login");

[Link](100, 30, 150, 30);


[Link](100, 70, 150, 30);
[Link](100, 110, 80, 30);

[Link](e -> {
String u = [Link]();
String p = new String([Link]());
if ([Link]("admin") &&[Link]("123")) {
[Link](f, "Login Successful!");
} else {
[Link](f, "Invalid credentials");
}
});

[Link](null);
[Link](new JLabel("User:")).setBounds(30, 30, 70, 30);
[Link](new JLabel("Pass:")).setBounds(30, 70, 70, 30);
[Link](user); [Link](pass); [Link](login);
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT:

RESULT:

Thus the program has been executed successfully.


[Link]
DATE:
SWING TODO APP

AIM:

To create a simple ToDo application using Swing.

PROCEDURE:

1. Add task using text field.


2. Remove task from JList.

PROGRAM:

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

public class ToDoApp {


public static void main(String[] args) {
JFrame f = new JFrame("ToDo List");
JTextField task = new JTextField();
JButton add = new JButton("Add");
JButton remove = new JButton("Remove");
DefaultListModel<String>listModel = new DefaultListModel<>();
JList<String>taskList = new JList<>(listModel);

[Link](30, 30, 200, 30);


[Link](240, 30, 80, 30);
[Link](30, 70, 290, 120);
[Link](30, 200, 100, 30);

[Link](e ->[Link]([Link]()));
[Link](e ->[Link]([Link]()));
[Link](task); [Link](add); [Link](taskList); [Link](remove);
[Link](360, 300);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT:

RESULT:

Thus the program has been executed successfully.

[Link]
DATE:
COLLECTIONS – SORT EMPLOYEES

AIM:

To store employees in an ArrayList and sort by salary.

PROCEDURE:

1. Create Employee class.


2. Use Comparator to sort.

PROGRAM:

import [Link].*;
class Employee {
int id;
String name;
double salary;

Employee(int i, String n, double s) {


id = i; name = n; salary = s;
}

public String toString() {


return id + " " + name + " " + salary;
}
}

public class SortEmployees {


public static void main(String[] args) {
ArrayList<Employee> list = new ArrayList<>();
[Link](new Employee(1, "Amit", 40000));
[Link](new Employee(2, "Reena", 30000));
[Link](new Employee(3, "John", 50000));

[Link]([Link](e ->[Link]));

for (Employee e : list) {


[Link](e);
}
}
}

OUTPUT:

RESULT:

Thus the program has been executed successfully.


[Link]:17A
DATE:
JDBC – INSERT, UPDATE, RETRIEVE

AIM:

To perform insert, update, and retrieve operations in MySQL.

PROCEDURE:

1. Create table in MySQL.


2. Write Java JDBC code.
3. Compile and run with JDBC driver.

PROGRAM:

import [Link].*;

public class JDBCExample {


public static void main(String[] args) throws Exception {
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
Statement stmt = [Link]();

[Link]("INSERT INTO students VALUES(1, 'Amit', 20)");


[Link]("UPDATE students SET age=21 WHERE id=1");

ResultSetrs = [Link]("SELECT * FROM students");


while ([Link]()) {
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3));
}
[Link]();
}
}

OUTPUT:
RESULT:

Thus the program has been executed successfully.

[Link]:17B
DATE:
JDBC – Retrieve Text File

Aim:
To retrieve a text file stored in database and save it locally.

PROCEDURE:

1. Connect to MySQL database.


2. Fetch text from `files` table where `id = 1`.
3. Write the text to `[Link]`.
4. Close connection and show "File saved."

Program:
import [Link].*;
import [Link].*;

public class RetrieveText {


public static void main(String[] args) throws Exception {
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
Statement stmt = [Link]();
ResultSetrs = [Link]("SELECT content FROM files WHERE id = 1");

if ([Link]()) {
String text = [Link]("content");
FileWriter fw = new FileWriter("[Link]");
[Link](text);
[Link]();
[Link]("File saved.");
}

[Link]();
}
}

OUTPUT:

RESULT:

Thus the program has been executed successfully.


[Link]:17C
DATE:
JSP Page

Aim:
To display content using JSP.

Procedure:
1. Create a JSP file with HTML content.
2. Use `<%@ page %>` to set page properties.
3. Write HTML inside the JSP file.
4. Run on a server (like Apache Tomcat) to display in browser.

Program:
File: [Link]

<%@ page language="java" contentType="text/html; charset=UTF-8"%>


<html>
<head><title>JSP Page</title></head>
<body>
<h1>Welcome to JSP Page!</h1>
<p>This is a sample JSP content.</p>
</body>
</html>

OUTPUT:
RESULT:

Thus the program has been executed successfully.

You might also like