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

Java

Uploaded by

Varsa
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)
22 views

Java

Uploaded by

Varsa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Basic arthimetic operation

import java.util.Scanner;

public class ArithmeticOperations {

public static void main(String[] args) {

int x, y;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the value of x:");

x = sc.nextInt();

System.out.println("Enter the value of y:");

y = sc.nextInt();

System.out.println("Addition is: " + (x + y));

System.out.println("Subtraction is: " + (x - y));

System.out.println("Multiplication is: " + (x * y));

if (y != 0) {

System.out.println("Division is: " + (x / y));

System.out.println("Modulus is: " + (x % y));

} else {

System.out.println("Cannot divide by zero.");

}
Positive or negative using if

import java.util.Scanner;

public class PositiveOrNegative {

public static void main(String[] args) {

int a;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number:");

a = sc.nextInt();

if (a > 0)

System.out.println("The number is positive");

else if (a < 0)

System.out.println("The number is negative");

else

System.out.println("Zero");

}
Greatest of three numbers

import java.util.Scanner;

public class GreatestNumbers {

public static void main(String[] args) {

int x, y, z;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the first number:");

x = sc.nextInt();

System.out.println("Enter the second number:");

y = sc.nextInt();

System.out.println("Enter the third number:");

z = sc.nextInt();

if (x >= y) {

if (x >= z) {

System.out.println("The largest number is: " + x);

} else {

System.out.println("The largest number is: " + z);

} else {

if (y >= z) {

System.out.println("The largest number is: " + y);

} else {

System.out.println("The largest number is: " + z);

}
Reverse given number

import java.util.Scanner;

public class Reversenumber {

public static void main(String[] args) {

int n, a, m = 0;

Scanner sc = new Scanner(System.in);

System.out.println("Enter any number:");

n = sc.nextInt();

do {

a = n % 10;

m = m * 10 + a;

n = n / 10;

} while (n > 0);

System.out.println("Reverse: " + m);

}
Factorial of a given num

import java.util.Scanner;

public class Factorialnumber {

public static void main(String[] args) {

int fact = 1;

int i = 1;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number to calculate factorial:");

int num = sc.nextInt();

while (i <= num) {

fact *= i;

i++;

System.out.println("Factorial of " + num + " is " + fact);

}
Sorting arrays

import java.util.Scanner;

public class Sortingarrays {

public static void main(String[] args) {

int n, temp;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of elements:");

n = sc.nextInt();

int a[] = new int[n];

System.out.println("Enter all the elements:");

for (int i = 0; i < n; i++)

a[i] = sc.nextInt();

for (int i = 0; i < n - 1; i++) {

for (int j = i + 1; j < n; j++) {

if (a[i] > a[j]) {

temp = a[i];

a[i] = a[j];

a[j] = temp;

System.out.println("Ascending order:");

for (int i = 0; i < n; i++)

System.out.println(a[i]);

}
Finding the grade

import java.util.Scanner;

public class Findinggrade {

public static void main(String[] args) {

String grade = null;

System.out.println("Enter marks: ");

Scanner sc = new Scanner(System.in);

int score = sc.nextInt();

switch (score / 10) {

// for >= 90

case 10:

case 9:

grade = "A";

break;

// for 80-89

case 8:

grade = "B";

break;

// for 70-79

case 7:

grade = "C";

break;

// for 60-69

case 6:

grade = "D";

break;

// for 40-59
case 5:

grade = "E";

break;

// for < 40

default:

grade = "F";

break;

System.out.println("Your grade is: " + grade);

Classes and objects

package Java;

import java.util.Scanner;

class Laptop {

String Brand, RAM, HDD, Processor, Generation;

Laptop(String b, String r, String h, String p, String g) {

Brand = b;

RAM = r;

HDD = h;

Processor = p;

Generation = g;

void display() {

System.out.println("Brand: " + Brand);

System.out.println("RAM: " + RAM);


System.out.println("Hard disk storage capacity: " + HDD);

System.out.println("Processor: " + Processor);

System.out.println("Generation: " + Generation);

public class Classobject {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter brand of laptop:");

String a = sc.nextLine();

System.out.println("Enter RAM of laptop:");

String b = sc.nextLine();

System.out.println("Enter hard disk storage capacity of laptop:");

String c = sc.nextLine();

System.out.println("Enter processor of laptop:");

String d = sc.nextLine();

System.out.println("Enter generation of laptop:");

String e = sc.nextLine();

Laptop x = new Laptop(a, b, c, d, e);

x.display();

sc.close();

}
Constructor overloading

package sakthi;

import java.util.Scanner;

class Rectangle {

int length;

int width;

int height;

Rectangle(int wid, int hei) {

width = wid;

height = hei;

length = 22;

Rectangle(int l, int w, int h) {

length = l;

width = w;

height = h;

void display() {

System.out.println("Length: " + length);

System.out.println("Width: " + width);

System.out.println("Height: " + height);

System.out.println("Volume: " + (length * width * height));

}
public class ConstructorOverloading {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Constructor 1");

Rectangle a = new Rectangle(6, 5, 7);

a.display();

System.out.println("\nConstructor 2");

Rectangle b = new Rectangle(2,1);

b.display();

System.out.println("Enter width:");

int w =scan.nextInt();

System.out.println("Enter height:");

int h =scan.nextInt();

System.out.println("Enter length:");

int l =scan.nextInt();

system.out.println(“\n constructor 3”);

rectangle c = new rectangle(l,w,h);

c.dispaly();

scan.close();

Method overloading

class Addition {

int Add(int a, int b) {

return a + b;

}
double Add(double a, double b, double c) {

return a + b + c;

double Add(int a, double b) {

return a + b;

String Add(String a, String b) {

return a + b;

public class MethodOverloading {

public static void main(String[] args) {

Addition x = new Addition();

System.out.println("Adding two integers: " + x.Add(4, 3));

System.out.println("Adding three integers: " + x.Add(3, 2, 4));

System.out.println("Adding an integer and a real number: " + x.Add(1, 1.5));

System.out.println("Concatenating two strings: " + x.Add("Hello", "world"));

Abstract class

abstract class Bill {

int amount;

public Bill(int amount) {


this.amount = amount - 10000;

public void display() {

System.out.println("Amount: " + this.amount);

abstract void taxCalculation();

class BillAmount extends Bill {

public BillAmount(int amount) {

super(amount);

void taxCalculation() {

double totalAmount = this.amount + this.amount * 5 / 100;

System.out.println("Total amount to be paid: " + totalAmount);

public class AbstractClass {

public static void main(String[] args) {

BillAmount bill = new BillAmount(100);

bill.display();

bill.taxCalculation();

}
Runtime polymorphism

import java.util.Scanner;

class Product {

String product_name = "woofer & amplifier";

int cost = 35000;

void disp() {

System.out.println("Product name: " + product_name);

System.out.println("Cost: " + cost);

class Croma extends Product {

void disp() {

int disc = 10;

System.out.println("Croma: " + disc + "%");

System.out.println("Discount amount: Rs" + (cost * disc / 100));

System.out.println("Cost in Croma: Rs" + (cost - (cost * disc / 100)));

class Reliance extends Product {

void disp() {

int disc = 19;

System.out.println("Reliance: " + disc + "%");

System.out.println("Discount amount: Rs" + (cost * disc / 100));

System.out.println("Cost in Reliance: Rs" + (cost - (cost * disc / 100)));

}
}

class Prodigital extends Product {

void disp() {

int disc = 12;

System.out.println("Prodigital: " + disc + "%");

System.out.println("Discount amount: Rs" + (cost * disc / 100));

System.out.println("Cost in Prodigital: Rs" + (cost - (cost * disc / 100)));

public class AbstractClass {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Croma croma = new Croma();

croma.disp();

single inhertitacnce

class Bank {

int AccNo;

String Name;

double Balance;

Bank(int a, String n, double b) {

AccNo = a;

Name = n;

Balance = b;

}
void display() {

System.out.println("Account Number: " + AccNo);

System.out.println("Name: " + Name);

System.out.println("Balance: " + Balance);

class Cards extends Bank {

String Debit;

String Credit;

Cards(int a, String n, double b, String d, String c) {

super(a, n, b);

Debit = d;

Credit = c;

void displayCards() {

System.out.println("Debit card no: " + Debit);

System.out.println("Credit card no: " + Credit);

public class SingleInheritance {

public static void main(String[] args) {

Cards x = new Cards(100, "sakthi", 20000, "7481585865185816", "1098415715151538863");

x.display();

x.displayCards();

}
Multiple inheritance

class Product {

int pid;

String pname;

Product(int a, String b) {

pid = a;

pname = b;

void display() {

System.out.println("Product ID: " + pid);

System.out.println("Product Name: " + pname);

class Type extends Product {

double cost;

String category;

Type(int a, String b, double c, String d) {

super(a, b);

cost = c;

category = d;

void displayType() {

System.out.println("Cost: " + cost);

System.out.println("Category: " + category);

}
class Popularity extends Type {

String brand;

int ratings;

Popularity(int a, String b, double c, String d, String e, int f) {

super(a, b, c, d);

brand = e;

ratings = f;

void displayPopularity() {

display();

displayType();

System.out.println("Brand: " + brand);

System.out.println("Ratings: " + ratings);

public class MultilevelInheritance {

public static void main(String[] args) {

Popularity x = new Popularity(100, "top", 1300, "clothes", "mintra", 9);

x.displayPopularity();

Hierarchical inheritance

class Banks {

// Implement the Banks class (if needed)


}

class ICICI {

// Implement the ICICI class (if needed)

class Canara {

// Implement the Canara class (if needed)

class Yes {

// Implement the Yes class (if needed)

public class HierarchicalInheritance {

public static void main(String[] args) {

// Instantiate objects and call methods here

// Example:

Banks b = new Banks();

b.display();

// Similar instantiation and method calls for ICICI, Canara, and Yes

Implementation of packages

package Java;

public class Demo {

String name = "Sakthi";

String regNo = "2213721102034";


String className = "Bsc data science"; // 'class' is a reserved keyword, renamed to 'className'

String mailId = "[email protected]";

String contactNo = "9814616658";

String password = "srini";

private void displayPrivate() {

System.out.println("private:" + password);

protected void displayProtected() {

System.out.println("protected:" + mailId);

public void displayPublic() {

System.out.println("public:" + name + ":" + regNo + ":" + className);

void displayDefault() {

System.out.println("Default:" + contactNo);

public static void main(String[] args) {

Demo x = new Demo();

x.displayPrivate();

x.displayProtected();

x.displayPublic();

x.displayDefault();

package Java;
code2

public class RunDemo {

public static void main(String[] args) {

Demo y = new Demo();

System.out.println("Inside the same package");

System.out.println("Accessing public, protected, Default");

y.displayPublic();

y.displayProtected();

y.displayDefault();

Code3

package Java;

public class RunDemo {

public static void main(String[] args) {

Demo y = new Demo();

System.out.println("Inside the same package");

System.out.println("Accessing public, protected, Default");

y.displayPublic();

y.displayProtected();

y.displayDefault();

Implementation of interface

// Define the 'shapes' interface with the 'volume' method

interface shapes {

double PI = 3.14; // 'final' is implicit in interface fields

double volume();
}

// Extend the 'shapes' interface with the 'shapeDemo' interface

interface shapeDemo extends shapes {

void draw();

// Implement the 'shapeDemo' interface with the 'Circle' class

class Circle implements shapeDemo {

int r = 15;

// Implement the 'volume' method

public double volume() {

return (PI * r * r); // Corrected the formula to calculate the area instead of volume

// Implement the 'draw' method

public void draw() {

System.out.println("Drawing a Circle");

// Create the 'InterfaceDemo1' class with the main method

public class InterfaceDemo1 {

public static void main(String[] args) {

Circle x = new Circle();

x.draw();

System.out.println(x.volume()); // This will print the area of the circle

}
Exception handling 1,2,3

public class ThrowExceptionDemo {

public static void validate(int age) {

if (age < 18) {

// Throw ArithmeticException if not eligible to vote

throw new ArithmeticException("Person is not eligible to vote");

} else {

System.out.println("Person is eligible to vote!!");

public static void main(String[] args) {

try {

validate(25);

System.out.println("Eligible To Vote");

} catch (ArithmeticException e) {

System.out.println(e.getMessage());

Code2

class ExceptionDemo {

public static void main(String[] args) {

int div;

try {

div = 5 / 2;

System.out.println("The Result of Division is:" + div);

div = 5 / 0;
System.out.println("The Result of Division is:" + div);

} catch (ArithmeticException e) {

System.out.println("Division by zero.");

Code 3

package sakthi;

public class TryCatchFinally {

public static void main(String[] args) {

int div;

try {

div = 5 / 2;

System.out.println("The Result of Division is:" + div);

div = 5 / 0; // This will cause an ArithmeticException

System.out.println("The Result of Division is:" + div);

} catch (ArithmeticException e) {

System.out.println("Catch - Division by zero. Error");

} finally {

System.out.println("Finally Block - Program Ends Here.");

Implementation of threads

class DemoThread2 implements Runnable {

public void run() {

try {

for (int i = 1; i < 3; i++) {


System.out.println("This is Child Thread");

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Child thread interrupted.");

class RecThread2 {

public static void main(String[] args) {

DemoThread2 obj = new DemoThread2();

Thread x = new Thread(obj);

x.start();

try {

for (int i = 1; i <= 2; i++) {

System.out.println("This is main Thread");

Thread.sleep(5000);

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

Code 2

public class ThreadDemo {

// Inner class that extends Thread

static class CountThreading extends Thread {

private String name;


private int wait;

public CountThreading(String name, int wait) {

this.name = name;

this.wait = wait;

public void run() {

try {

Thread.sleep(wait);

System.out.println(this.name);

} catch (InterruptedException e) {

System.out.println(name + " interrupted.");

public static void main(String[] args) {

CountThreading counterA = new CountThreading("preethi", 500);

CountThreading counterB = new CountThreading("shalini", 1000);

counterA.start();

counterB.start();

System.out.println("Main Thread");

Thread synchronization

class Table {

synchronized void printTable(int n) { // synchronized method

System.out.println("Table of " + n + ":");

for (int i = 1; i <= 5; i++) {


System.out.println(n * i);

try {

Thread.sleep(500);

} catch (Exception e) {

System.out.println("Thread interrupted.");

class MyThread extends Thread {

int n;

Table t;

MyThread(Table x, int y) {

this.t = x;

this.n = y;

public void run() {

t.printTable(this.n);

public class ThreadSync {

public static void main(String[] args) {

Table obj = new Table();

MyThread x = new MyThread(obj, 5);

MyThread y = new MyThread(obj, 10);

x.start();

y.start();
}

String manipulation

public class StringDemo {

public static void main(String[] args) {

String msg = "Welcome to Our College";

String str = "Welcome to Our College";

String s = " Welcome ";

System.out.println(msg.toUpperCase());

System.out.println(msg.toLowerCase());

System.out.println(msg.length());

System.out.println(msg.equals(str));

System.out.println(msg.equals(s));

System.out.println(str.equalsIgnoreCase("welcome to our college"));

System.out.println(s.trim());

System.out.println(msg.concat(" M.O.P."));

System.out.println(msg.charAt(5));

System.out.println(msg.replace("Our", "the"));

System.out.println(msg.substring(7));

System.out.println(msg.contains("Our"));

String[] ni = {"Hi", "Hello", "Hai"};

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

System.out.println(ni[i]);

}
String buffer

package sakthi;

public class StringBufferDemo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("welcome ");

sb.append("college");

System.out.println(sb); // Output: welcome college

sb.insert(7, "to ");

System.out.println(sb); // Output: welcome to college

System.out.println(sb.capacity()); // Output: 24

System.out.println(sb.charAt(5)); // Output: m

sb.replace(0, 5, "Hello ");

System.out.println(sb); // Output: Hello me to college

sb.delete(3, 7);

System.out.println(sb); // Output: Helme to college

sb.reverse();

System.out.println(sb); // Output: egelloc ot emleH

Read and write files

import java.io.*;

public class FileDemo {

public static void main(String[] args) {

try {

FileOutputStream fop = new FileOutputStream("D:\\sakthi.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Contents of File:");


String str = br.readLine();

while (!str.equals("stop")) {

str = str + "\n";

byte[] line = str.getBytes();

fop.write(line);

str = br.readLine();

fop.close();

br.close(); // Close BufferedReader

} catch (Exception e) {

System.out.println(e);

try {

FileInputStream fin = new FileInputStream("D:\\sakthi.txt"); // Corrected file name to


sakthi.txt

int i;

while ((i = fin.read()) != -1) {

System.out.print((char) i);

fin.close();

} catch (Exception e) {

System.out.println(e);

Code2

import java.io.*;
public class FileCopy {

public static void main(String[] args) {

try {

FileInputStream fin = new FileInputStream("D:\\sakthi.txt");

FileOutputStream fop = new FileOutputStream("D:\\rithi.txt");

int i;

while ((i = fin.read()) != -1) {

fop.write(i);

fin.close();

fop.close();

System.out.println("File Copied");

} catch (Exception e) {

System.out.println(e);

Stack

import java.io.*;

import java.util.*;

public class StackDemo {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<Integer>();

stack.push(20);

stack.push(30);

stack.push(50);

System.out.println("Display Stack: " + stack);


System.out.println("Popped element: " + stack.pop());

System.out.println("Popped element: " + stack.pop());

System.out.println("Stack after pop operation: " + stack);

System.out.println("Top element in stack: " + stack.peek());

System.out.println("Search Stack for element 20: " + stack.search(20));

System.out.println("Search Stack for element 30: " + stack.search(30));

Vector

Code 1

import java.io.*;

import java.net.*;

public class ClientDemo {

public static void main(String[] args) {

try {

Socket s = new Socket("localhost", 6666);

DataOutputStream dout = new DataOutputStream(s.getOutputStream());

System.out.println("Client Started....");

System.out.println("Sending msg");

dout.writeUTF("Hello Server"); // Corrected method call to writeUTF

dout.flush();

dout.close();

s.close();

} catch (Exception e) {

System.out.println(e);

}
Code 2

import java.io.*;

import java.util.*;

public class StackDemo {

public static void main(String[] args) {

Stack<Integer> stack = new Stack<Integer>();

stack.push(20);

stack.push(30);

stack.push(50);

System.out.println("Display Stack: " + stack);

System.out.println("Popped element: " + stack.pop());

System.out.println("Popped element: " + stack.pop());

System.out.println("Stack after pop operation: " + stack);

System.out.println("Top element in stack: " + stack.peek());

System.out.println("Search Stack for element 20: " + stack.search(20));

System.out.println("Search Stack for element 30: " + stack.search(30));

Network programming

import java.io.*;

import java.net.*;

public class ServerDemo {

public static void main(String[] args) {

try {

ServerSocket ss = new ServerSocket(6666);

System.out.println("Server Started...");
Socket s = ss.accept(); // Accepts a connection

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = dis.readUTF(); // Reads the UTF message

System.out.println("message=" + str);

s.close(); // Closes the client socket

ss.close(); // Closes the server socket

} catch (Exception e) {

System.out.println(e);

url class

import java.net.*;

public class URLDemo { // Renamed class to follow Java naming conventions

public static void main(String[] args) {

try {

URL url = new URL("https://www.mygreatlearning.com/blog/oops-concepts-in-java");

System.out.println("Protocol: " + url.getProtocol());

System.out.println("Host Name: " + url.getHost());

System.out.println("Port Number: " + url.getPort());

System.out.println("File Name: " + url.getFile());

} catch (Exception e) {

System.out.println(e);

Awt controls

import java.awt.*;
class JobApplication extends Frame {

Frame f = new Frame();

Label l1 = new Label("Job Application");

Label l2 = new Label("Name");

TextField t1 = new TextField();

Label l3 = new Label("Age");

CheckboxGroup cbg = new CheckboxGroup();

Checkbox c1 = new Checkbox("Male", cbg, false);

Checkbox c2 = new Checkbox("Female", cbg, false);

Label l4 = new Label("Skill Set");

Checkbox c3 = new Checkbox("Java");

Checkbox c4 = new Checkbox("SQL");

Checkbox c5 = new Checkbox("Python");

Checkbox c6 = new Checkbox("NLP");

Label l5 = new Label("Applying For");

Choice ch = new Choice();

Button b1 = new Button("Exit");

Button b2 = new Button("Submit");

Button b3 = new Button("Reset");

JobApplication() {

// Set layout and add components here

setLayout(null);

l1.setBounds(100, 30, 100, 20);

l2.setBounds(20, 70, 80, 20);

t1.setBounds(120, 70, 100, 20);

l3.setBounds(20, 100, 80, 20);

c1.setBounds(120, 100, 50, 20);

c2.setBounds(210, 100, 50, 20);

// Add other components similarly


// Add all components to the frame

add(l1);

add(l2);

add(t1);

add(l3);

add(c1);

add(c2);

// Add other components similarly

setSize(400, 400); // Set the size of the frame

setVisible(true); // Make the frame visible

public static void main(String[] args) {

new JobApplication(); // Create an instance of JobApplication

Panel implementation

import java.awt.*;

import java.awt.event.*;

public class PanelDemo {

Frame f = new Frame("Panel Demo");

Panel p1, p2;

Button b1, b2, b3, b4;

Label l1, l2;

public PanelDemo() {
p1 = new Panel();

p2 = new Panel();

l1 = new Label("Panel 1");

l2 = new Label("Panel 2");

b1 = new Button("One");

b2 = new Button("Two");

b3 = new Button("Three");

b4 = new Button("Four");

p1.add(l1);

p1.add(b1);

p1.add(b2);

p2.add(l2);

p2.add(b3);

p2.add(b4);

p1.setBackground(Color.GREEN);

p2.setBackground(Color.YELLOW);

f.add(p1);

f.add(p2);

f.setLayout(new FlowLayout());

f.setSize(300, 300);

f.setVisible(true);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});
}

public static void main(String[] args) {

new PanelDemo();

Panel code 2

import java.awt.*;

import java.awt.event.*;

public class PanelDemo {

Frame f = new Frame("Panel Demo");

Panel p1, p2;

Button b1, b2, b3, b4;

Label l1, l2;

public PanelDemo() {

p1 = new Panel();

p2 = new Panel();

l1 = new Label("Panel 1");

l2 = new Label("Panel 2");

b1 = new Button("One");

b2 = new Button("Two");

b3 = new Button("Three");

b4 = new Button("Four");

p1.add(l1);

p1.add(b1);

p1.add(b2);

p2.add(l2);
p2.add(b3);

p2.add(b4);

p1.setBackground(Color.GREEN);

p2.setBackground(Color.YELLOW);

f.add(p1);

f.add(p2);

f.setLayout(new FlowLayout());

f.setSize(300, 300);

f.setVisible(true);

f.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

public static void main(String[] args) {

new PanelDemo(); // Create an instance of PanelDemo

Simple calculator:

import java.awt.*;

import java.awt.event.*;

class Calculator extends Frame implements ActionListener {


// Declaring Objects

Label l1 = new Label("First Number");

Label l2 = new Label("Second Number");

Label l3 = new Label("Result");

TextField t1 = new TextField();

TextField t2 = new TextField();

TextField t3 = new TextField();

Button b1 = new Button("Add");

Button b2 = new Button("Sub");

Button b3 = new Button("Mul");

Button b4 = new Button("Div");

Button b5 = new Button("Exit");

Panel p1 = new Panel();

Panel p2 = new Panel();

Calculator() {

// Giving Coordinates

// Adding components to the frame

p1.add(l1);

p1.add(t1);

p1.add(l2);

p1.add(t2);

p1.add(l3);

p1.add(t3);

p1.setLayout(new GridLayout(3, 2));

add(p1);

p2.add(b1);

p2.add(b2);

p2.add(b3);

p2.add(b4);
p2.add(b5);

p2.setLayout(new FlowLayout());

add(p2);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

setLayout(new FlowLayout());

setVisible(true);

setSize(300, 300);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

public void actionPerformed(ActionEvent e) {

int n1 = Integer.parseInt(t1.getText());

int n2 = Integer.parseInt(t2.getText());

if (e.getSource() == b1) {

t3.setText(String.valueOf(n1 + n2));

} else if (e.getSource() == b2) {

t3.setText(String.valueOf(n1 - n2));

} else if (e.getSource() == b3) {

t3.setText(String.valueOf(n1 * n2));
} else if (e.getSource() == b4) {

t3.setText(String.valueOf(n1 / n2));

} else if (e.getSource() == b5) {

System.exit(0);

public static void main(String[] args) {

new Calculator();

Implementing Menu

import java.awt.*;

import java.awt.event.*;

public class MenubarDemo implements ActionListener {

Frame f = new Frame("Menu Bar Demo");

MenuBar mb = new MenuBar();

// Create menus

Menu fileMenu = new Menu("File");

Menu editMenu = new Menu("Edit");

Menu saveMenu = new Menu("Save");

// Create menu items

MenuItem newItem = new MenuItem("New");

MenuItem openItem = new MenuItem("Open");

MenuItem closeItem = new MenuItem("Close");

MenuItem exitItem = new MenuItem("Exit");

MenuItem copyItem = new MenuItem("Copy");

MenuItem cutItem = new MenuItem("Cut");


MenuItem findItem = new MenuItem("Find");

MenuItem pdfItem = new MenuItem("as PDF");

MenuItem jpegItem = new MenuItem("as JPEG");

public MenubarDemo() {

// Add menu items to menus

fileMenu.add(newItem);

fileMenu.add(openItem);

fileMenu.add(closeItem);

fileMenu.add(exitItem);

saveMenu.add(pdfItem);

saveMenu.add(jpegItem);

editMenu.add(copyItem);

editMenu.add(cutItem);

editMenu.add(findItem);

// Add menus to menu bar

mb.add(fileMenu);

mb.add(editMenu);

mb.add(saveMenu);

// Set menu bar for the frame

f.setMenuBar(mb);

// Add action listeners

newItem.addActionListener(this);

openItem.addActionListener(this);

closeItem.addActionListener(this);

exitItem.addActionListener(this);
copyItem.addActionListener(this);

// Set label position

Label label = new Label("Hello, Menu Bar!");

label.setBounds(100, 150, 200, 20); // Adjust position and size as needed

f.add(label);

// Set frame properties

f.setVisible(true);

f.setSize(400, 400);

// Implement actionPerformed method for handling menu actions

@Override

public void actionPerformed(ActionEvent e) {

// Handle menu item actions here

// ...

public static void main(String[] args) {

new MenubarDemo();

Code 2

import java.awt.*;

import java.awt.event.*;

public class MouseListenerDemo implements MouseListener {

Frame f = new Frame();

Label label = new Label("Mouse Demo");


public MouseListenerDemo() {

f.add(label);

label.setBounds(20, 50, 100, 20); // Set label position

f.setSize(300, 300);

f.setLayout(new FlowLayout());

f.setVisible(true);

// Add this class as a mouse listener

label.addMouseListener(this);

@Override

public void mouseClicked(MouseEvent e) {

label.setText("Mouse Clicked");

@Override

public void mouseEntered(MouseEvent e) {

label.setText("Mouse Entered");

@Override

public void mouseExited(MouseEvent e) {

label.setText("Mouse Exited");

@Override

public void mousePressed(MouseEvent e) {

label.setText("Mouse Pressed");

}
@Override

public void mouseReleased(MouseEvent e) {

label.setText("Mouse Released");

public static void main(String[] args) {

new MouseListenerDemo();

Dialog box

import java.awt.*;

import java.awt.event.*;

public class DialogDemo {

private static Dialog d;

private Label label;

private Button button;

public DialogDemo() {

Frame f = new Frame();

d = new Dialog(f, "Dialog Example", true);

d.setLayout(new FlowLayout());

label = new Label("Click button to continue.");

button = new Button("OK");

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

d.setVisible(false);
}

});

d.add(label);

d.add(button);

d.setSize(200, 100);

d.setVisible(true);

public static void main(String[] args) {

new DialogDemo();

Applet moving banner

import java.awt.*;

import java.applet.*;

public class MovingTextCL extends Applet implements Runnable {

private String display = "Hello World";

private int x = 50, y = 100;

private Thread t;

public void init() {

t = new Thread(this, "My Thread");

t.start();

public void run() {

while (true) {

x += 10;
if (x > 300)

x = 50;

repaint();

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

public void paint(Graphics g) {

setBackground(Color.yellow);

setForeground(Color.red);

Font f = new Font("Consolas", Font.BOLD, 30);

g.setFont(f);

g.drawString(display, x, y);

Event handling

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Changecolor extends Applet implements KeyListener {

public void init() {

setBackground(Color.white);

addKeyListener(this);

}
@Override

public void keyPressed(KeyEvent e) {

int R = (int) (Math.random() * 100) % 255;

int G = (int) (Math.random() * 100) % 255;

int B = (int) (Math.random() * 100) % 255;

Color Mycolor = new Color(R, G, B);

setBackground(Mycolor);

// Empty methods

@Override

public void keyReleased(KeyEvent e) {

// No specific functionality needed

@Override

public void keyTyped(KeyEvent e) {

// No specific functionality needed

Graphics class

import java.applet.Applet;

import java.awt.*;

public class GraphicsDemo extends Applet {

public void paint(Graphics g) {

g.setColor(Color.red);

g.drawString("Welcome", 50, 50);


g.drawLine(20, 30, 20, 300);

g.drawRect(70, 100, 30, 30);

g.fillRect(170, 100, 30, 30);

g.drawOval(70, 200, 30, 30);

g.setColor(Color.pink);

g.fillOval(170, 200, 30, 30);

g.drawArc(90, 150, 30, 30, 30, 270);

g.fillArc(270, 150, 30, 30, 0, 180);

Layout

Border layout:

import java.awt.*;

import javax.swing.*;

class BorderLayoutDemo extends JFrame {

BorderLayoutDemo() {

JPanel panel = new JPanel();

panel.setLayout(new BorderLayout());

panel.add(new JButton("Welcome"), BorderLayout.NORTH);

panel.add(new JButton("Geeks"), BorderLayout.SOUTH);

panel.add(new JButton("Layout"), BorderLayout.EAST);

panel.add(new JButton("Border"), BorderLayout.WEST);

panel.add(new JButton("GeeksforGeeks"), BorderLayout.CENTER);

add(panel);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(300, 300);

setVisible(true);

}
public static void main(String[] args) {

new BorderLayoutDemo();

Grid layout:

import java.awt.*;

import java.awt.event.*;

public class GridLayoutDemo {

public static void main(String[] args) {

Frame fl = new Frame("Grid Layout Demo");

fl.setLayout(new GridLayout(5, 2));

Button b1 = new Button("One");

Button b2 = new Button("Two");

Button b3 = new Button("Three");

Button b4 = new Button("Four");

Button b5 = new Button("Five");

Button b6 = new Button("Six");

Button b7 = new Button("Seven");

Button b8 = new Button("Eight");

Button b9 = new Button("Nine");

Button b10 = new Button("Ten");

fl.add(b1);

fl.add(b2);

fl.add(b3);

fl.add(b4);

fl.add(b5);
fl.add(b6);

fl.add(b7);

fl.add(b8);

fl.add(b9);

fl.add(b10);

fl.setSize(500, 500);

fl.setVisible(true);

fl.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

Flow layout

import java.awt.*;

import java.awt.event.*;

public class FlowLayoutDemo {

public static void main(String[] args) {

Frame fl = new Frame("Flow Layout Demo");

fl.setLayout(new FlowLayout());

Button b1 = new Button("One");

Button b2 = new Button("Two");

Button b3 = new Button("Three");

Button b4 = new Button("Four");

Button b5 = new Button("Five");


Button b6 = new Button("Six");

Button b7 = new Button("Seven");

Button b8 = new Button("Eight");

Button b9 = new Button("Nine");

Button b10 = new Button("Ten");

fl.add(b1);

fl.add(b2);

fl.add(b3);

fl.add(b4);

fl.add(b5);

fl.add(b6);

fl.add(b7);

fl.add(b8);

fl.add(b9);

fl.add(b10);

fl.setSize(300, 300);

fl.setVisible(true);

fl.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

Jdbc

Code 1

import java.sql.*;
import java.util.Scanner;

public class CreateInsertDemo {

public static void main(String[] args) {

try {

int n, i, t;

Scanner sc = new Scanner(System.in);

String query;

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys", "root",


"sakthi456");

Statement st = con.createStatement();

query = "CREATE TABLE cus_tomer(custid integer, custname text, age integer)";

st.execute(query);

System.out.println("Table Created...");

System.out.println("Enter number of records:");

n = sc.nextInt();

for (i = 1; i <= n; i++) {

System.out.println("Enter id, name, age:");

int id = sc.nextInt();

String name = sc.next();

int age = sc.nextInt();

query = "insert into cus_tomer values (" + id + ", '" + name + "', " + age + ")";

t = st.executeUpdate(query);

System.out.println("Record Inserted");

}
con.close();

} catch (Exception e) {

e.printStackTrace();

Code 2

import java.sql.*;

public class JDBCDisplay {

public static void main(String args[]) {

try {

// Register driver class

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys", "root",


"sakthi456");

// Execute queries

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM cus_tomer");

while (rs.next()) {

System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));

// Close connection

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

e.printStackTrace();

Code 3

package JDBC;

import java.sql.*;

import java.util.*;

public class UpdateDeleteDemo {

public static void main(String args[]) {

String query, name;

int rno;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys", "root",


"sakthi456");

Statement st = con.createStatement();

Scanner sc = new Scanner(System.in);

System.out.println("Enter id and name to be updated:");

rno = sc.nextInt();

name = sc.next();

query = "update cus_tomer set custname = '" + name + "' where custid = " + rno;

st.execute(query);

System.out.println("Record Updated");
System.out.println("Enter id to be deleted:");

rno = sc.nextInt();

query = "delete from cus_tomer where custid = " + rno;

st.execute(query);

System.out.println("Record Deleted");

} catch (Exception e) {

System.out.println(e);

Applet image:

import java.applet.Applet;

import java.awt.*;

public class ImagDemo extends Applet {

Image pic;

public void init() {

pic = getImage(getDocumentBase(), "green.jpeg");

public void paint(Graphics g) {

g.drawImage(pic, 30, 30, this);

You might also like