/* Simple Java program .
*/
public class Hi
{
public static void main(String args[])
{
[Link]("Welcome to java class");
}
/* Simple Java program to demostrate class and object . */
class Car {
String color; // attribute
String model; // attribute
void drive() //method
{ color="red";
model="swift";
[Link]("The car is driving by me and its in "+color+" color model is "+model);
}
}
public class Vehicle
{
public static void main(String arg[])
{
Car c=new Car();
[Link]();
}
}
/* Simple Java program to demostrate datatypes . */
public class Hello
{
//attributes
String name="SRI";
int rno=108;
char section='A';
float marks=599.5f;
double phoneno=94923932;
void display()//methods
{
[Link]("Name:"+name+"\nRollno:"+rno+"\nsection:"+section+"\nmarks:"+"\
nphoneno:"+phoneno);
}
public static void main(String args[])
{
Hello h=new Hello();
[Link]();
}
}
//simple Java program to demostrate if demo using cmd line arguments
public class ifdemo
{
public static void main(String args[])
{
int age=[Link](args[0]);
if (age > 18)
{
[Link]("Adult");
} else
{
[Link]("Minor");
}
}
}
//simple Java program to demostrate forloop demo using Scanner
import [Link].*;
public class Frloop
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner([Link]);
n=[Link]();
for (int i = 0; i < n; i++)
{
[Link](i);
}
}
}
//simple Java program to demostrate function demo using IO package & DataInputStream
import [Link].*;
class FunDemo {
public static void main(String arg[])throws IOException
{
FunD fd=new FunD();
DataInputStream dis=new DataInputStream([Link]);
int a=[Link]([Link]());
int b=[Link]([Link]());
[Link]([Link](a,b));
}
}
class FunD{
public static int add(int a, int b)
{
return a + b;
}
}
//simple Java program to demostrate function demo using IO package & BufferReader
import [Link].*;
public class Whloop
{
public static void main(String args[])throws IOException
{
int n;
BufferedReader sc=new BufferedReader(new InputStreamReader([Link]));
n=[Link]([Link]());
int i = 0;
while (i < n) {
[Link](i);
i++;
}
}
}
/*Write a simple JAVA program using switch control structure. */
class SwitchCS
{
public static void main (String args[])
{
int a;
a=[Link] (args[0]);
switch(a)
{
case 0:
[Link] ("Zero"); break;
case 1:
[Link] ("One"); break;
default:
[Link] ("Enter 0/1");
}
}
}
/* Java program to demonstrate constructor concept. */
class ClassConstructor
{
double h,w,d;
ClassConstructor () {h=2; w=3; d=4;}
ClassConstructor (double h2, double w2, double d2)
{
h=h2; w=w2; d=d2;
}
double volume()
{
return h*w*d;
}
}
class AddingConstructor
{
public static void main (String []args)
{
double v;
ClassConstructor cm=new ClassConstructor();
v=[Link]();
[Link] ("Box Volume"+v);
ClassConstructor c=new ClassConstructor(1.2,2.3,2.1);
v=[Link]();
[Link] ("Box2 Volume" +v);
}
}
/* Java Program to demonstrate 1d-array */
import [Link].*;
class Array1D
{
public static void main (String args[]) throws Exception
{
int nums[];
int size;
nums=new int[5];
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter array range:");
size=[Link]([Link]());
for(int i=0; i<size; i++)
{
[Link] ("Enter num ["+i+"] element");
nums[i]=[Link] ([Link]());
}
[Link] ("Array values are:");
for (int i:nums)
[Link] (i);
}
}
/* Java program to multiply two matrices */
import [Link].*;
class Mul
{
int ar,ac,br,bc;
int A[][]=new int[5][5]; int B[][]=new int[5][5]; int C[][]=new int[5][5];
Mul(int arow,int acol,int brow,int bcol)
{
ar=arow; ac=acol; br=brow; bc=bcol;
}
void mulMat() throws Exception
{
DataInputStream dis=new DataInputStream([Link]);
//Reading Matrix A
for(int i=0;i<ar;i++)
{
for(int j=0;j<ac;j++)
{
[Link]("Enter A["+i+"]["+j+"[ element");
A[i][j] =[Link]([Link]());
}
}
// Reading Matrix B
for(int i=0;i<br;i++)
{
for(int j=0;j<bc;j++)
{
[Link]("Enter B["+i+"]["+j+"[ element");
B[i][j] =[Link]([Link]());
}
}
// Multipling Matrix
for(int i=0;i<ar;i++)
{
for(int j=0;j<bc;j++)
{
C[i][j]=0;
for(int k=0;k<ac;k++)
{
C[i][j]+=A[i][j]*B[i][j];
}
}
}
// Print Matrix
[Link]("\n"+"Resultant Matrix is" );
for(int i=0;i<ar;i++)
{
for(int j=0;j<bc;j++)
[Link](C[i][j]+"\t");
[Link]();
}
}
}
public class MatMul
{
public static void main(String[] args) throws Exception
{
int Ar,Ac,Br,Bc;
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter the sizes of A And B");
Ar=[Link]([Link]()); Ac=[Link]([Link]());
Br=[Link]([Link]()); Bc=[Link]([Link]());
if(Ac!=Br)
[Link]("Mat mul is not possible");
else
{
Mul m=new Mul(Ar,Ac,Br,Bc);
[Link]();
}
}
}
/* Java Program to demonstrate Constructor and method overloading */
import [Link].*;
class Std
{
int rno, rank;
String name, hob, goal, ach;
double per,att;
Std (String n,int r,int rk)
{
name=n; rno=r; rank=rk;
}
Std (String n,int r, int rk, double p, double a)
{
name=n; rno=r; rank=rk; per=p; att=a;
}
Std (String n, int r, int rk, double p, double a, String ach, String h, String g)
{
name=n; rno=r; rank=rk; per=p; att=a; [Link]=ach; hob=h; goal=g;
}
void displayDetails()
{
[Link] ("Students information");
[Link] ("Name is\t" + name+"\t"+"rno is"+"\t"+rno+"rank is\t"+rank);
[Link]("Attendance is\t"+att+"per is\t"+per);
[Link]("Hobbies are\t"+hob+"Achievement is\t"+ach+"Goal is \t"+goal);
}
void meetingStds (String n, double p, double a)
{
[Link] ("Proctor counseling");
if (a<75)
[Link] ("Submit medical certificate to proctor otherwise you will be detained");
else
if (a>75 && p<60)
[Link] ("Not eligible for campus interviews and you have to attend remedial classes");
else
[Link] (" I whish you all the best");
}
void meetingStds (String n, int r)
{
[Link] (" Co-ordinator counseling");
[Link] ("along with students make a call to home and tell the"+
" parents students secrets");
}
void meetingStds()
{
[Link] ("CSI Students counseling");
[Link] ("Details of upcoming events");
}
}
public class ConstructorMethodOverloading
{
public static void main (String [] args) throws Exception
{
String n,h,a,g;
int r,rk;
double p, att;
DataInputStream dis=new DataInputStream ([Link]);
[Link] ("Enter name, hobbies, achievement and goal");
n=[Link](); h=[Link]();
a=[Link](); g=[Link]();
[Link] ("Enter rno, rank");
r=[Link] ([Link]());
rk=[Link] ([Link]());
[Link] ("Enter att. Percentage");
att=[Link] ([Link]());
p=[Link] ([Link]());
new Std (n,r,rk);
new Std (n,r,rk,p,att);
Std sc=new Std (n,r,rk,p,att,a,h,g);
[Link]();
[Link]();
[Link] (n,p,att);
[Link] (n,r);
}
}
/*
/* Java program to demonstrate multiple inheritance concept */
import [Link].*;
class S1
{
int rno, rank;
String name;
S1(String n, int r, int rk)
{
name=n; rno=r; rank=rk;
}
}
class S2 extends S1
{
double per, att;
S2 (String n,int r, int rk, double p, double a)
{
super (n,r,rk);
per=p;
att=a;
}
}
class S3 extends S2
{
String hob,goal, ach;
S3 (String n,int r, int rk, double p, double a, String ach, String h, String g)
{
super (n,r,rk,p,a);
[Link]=ach;
hob=h;
goal=g;
[Link]("s3 name is"+name);
}
void displayDetails()
{
[Link]("Student information");
[Link] ("name is \t"+name+"\t"+"rno is\t"+rno+"rank is \t"+rank);
[Link] ("attendance is \t"+att+"per is \t"+per);
[Link] ("Hobbies are \t"+hob+"achievement is \t"+ach+"Goal is"+goal);
}
}
public class InheritanceStdClass1
{
public static void main (String [] args) throws Exception
{
String n,h,a,g;
int r,rk;
double p,att;
DataInputStream dis=new DataInputStream ([Link]);
[Link] ("Enter name, hobbies, achievements and goal");
n=[Link]();
h=[Link]();
a=[Link]();
g=[Link]();
[Link] ("Enter rno, rank");
r=[Link]([Link]());
rk=[Link] ([Link]());
[Link] ("Enter attendance, percentage");
att=[Link] ([Link]());
p=[Link] ([Link]());
S3 sc=new S3 (n,r,rk,p,att,a,h,g);
[Link]();
}
}
/* Java program to display array elements using recursive print function */
class RecTest
{
int values[];
RecTest(int i)
{
values=new int[i];
}
void printArr(int i)
{
if(i==0) {[Link]("Output 0---->9");return;}
else {[Link]("["+(i-1)+"]"+values[i-1]); printArr(i-1);}
[Link]("["+(i-1)+"]"+values[i-1]);
}
}
public class Recursion
{
public static void main(String[] args)
{
RecTest rt=new RecTest(10);
for(int i=0;i<10;i++) [Link][i]=i;
[Link](10);
}
}
interface VCE
{
double funds=7000;
void fundsDiv();
void recruitFaculty();
void maintainGoodResults();
void prepareStdsForRanks();
void placementFull();
}
class CSE implements VCE
{
public void fundsDiv() {[Link](funds+1);}
public void recruitFaculty()
{
[Link] ("B.E./B.T./M.T./M.E. with distinction");
[Link] ("Experience o/n yrs");
}
public void maintainGoodResults()
{
[Link] ("force the stds to come regularly to the college");
}
public void prepareStdsForRanks()
{
[Link] ("Prepare mannals & imp. Q’s");
}
public void placementFull()
{
[Link] (" Campus connecting prog., CSI");
}
}
class Mech implements VCE
{
public void fundsDiv() {[Link] (funds/4);}
public void recruitFaculty()
{
[Link] ("B.E./B.T./M.T./M.E. with distinction");
[Link] ("Industrial experience");
}
public void maintainGoodResults()
{
[Link] ("Apply mech force");
}
public void prepareStdsForRanks()
{
[Link] ("increase practical knowledge & imp Q’s");
}
public void placementFull()
{
[Link] ("explain them company requirements");
}
}
class InterfaceExample
{
public static void main (String [] args)
{
VCE vc;
CSE cs=new CSE();
Mech m=new Mech();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
/* Java Program to explain the concept of Abstract class */
abstract class VCEstd
{
int rno;
String name;
VCEstd (int r, String n) {rno=r; name=n;}
void eligibleCriteria()
{
[Link] ("Must possess 60% \n any Engg discipline");
}
void conductGroupDiscussions()
{
[Link] ("Emphasis on attitude, communication skills,"
+"Presentation skills, inter personal skills, leadership qualities");
}
abstract void writtenTest();
abstract void interviewProcess();
abstract void packageDetails();
}
class CTS extends VCEstd
{
CTS (int r, String n) {super(r,n);}
void writtenTest()
{
[Link] ("Time 60 Mins 30 aplitude questions,10 logical reasoning, 10
technical");
}
void interviewProcess()
{
[Link] ("Technical round && HR round");
}
void packageDetails()
{
[Link] ("3.5 Lac per annum");
}
}
class TCS extends VCEstd
{
TCS (int r, String n) {super (r,n);}
void writtenTest()
{
[Link] (" Time 1 Hr 30 aplitude questions, 10 logical reasoning, 10
technical, 10 english");
}
void interviewProcess()
{
[Link] (" Technical round");
[Link] ("HR round");
}
void packageDetails()
{
[Link] ("4.5 Lac per annum");
}
}
class AbstractExample
{
public static void main (String [] args)
{
VCEstd vs; // super class ref. var
CTS ct= new CTS (007, "bond");
TCS tc = new TCS (007, "bond");
vs=tc; // super class ref var can refer to any sub class object
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
/* Java program to create & import a package */
package vce;
import [Link].*;
public class CreatePack
{
public int rno=007;
public String name="bond";
}
/* Java program to create & import a package */
import [Link];
class ImportPack
{
public static void main(String[] args)
{
CreatePack cp=new CreatePack();
[Link]([Link]+"\t"+[Link]);
}
}
Strings
class strappend{
public static void main(String args[]){
[Link](append("abc","xyz"));
}
static String append(String str1,String str2){
char ch[]=[Link]();
char ch2[]=[Link]();
int len1= [Link];
int len2= [Link];
int tot = len1+len2;
char appen[] = new char[tot];
for(int i=0;i<len1;i++){
appen[i]=ch[i];
}
for(int i=len1,j=0;i<tot;i++,j++){
appen[i]=ch2[j];
//[Link](new String(appen)+i+j+tot);
}
return new String(appen);
}
}
class StrRev
{
public static void main(String[] args)
{
// StringBuffer sb=new StringBuffer("abc");
StringBuilder sb=new StringBuilder("hi ra ");
if(sb==[Link]())
[Link](sb);
}
}
1. Handling ArithmeticException
public class ExceptionExample1 {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Caught an arithmetic exception: " +
[Link]());
[Link]("Program continues...");
Handling ArrayIndexOutOfBoundsException
CopyRunpublic class ExceptionExample2 {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
[Link](numbers[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of bounds: " + [Link]());
[Link]("Program continues...");
class MyThread extends Thread {
public void run() {
for(int i=1; i<=5; i++) {
[Link](getName() + " - " + i);
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1");
MyThread t2 = new MyThread();
[Link]("Thread-2");
[Link]();
[Link]();
import [Link];
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]); // Create Scanner
object
[Link]("Enter your name: ");
String name = [Link](); // Read a line of text
[Link]("Enter your age: ");
int age = [Link](); // Read an integer
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link](); // Close scanner
2. Using BufferedReader and InputStreamReader
An alternative for input:
import [Link];
import [Link];
import [Link];
public class InputExample {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]([Link]());
[Link]("Name: " + name);
[Link]("Age: " + age);
Serialize an object (write to a file)
import [Link];
import [Link];
import [Link];
public class SerializeExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (FileOutputStream fos = new
FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
[Link](person);
[Link]("Serialization complete");
} catch (IOException e) {
[Link]();
}
3. Deserialize an object (read from a file)
import [Link];
import [Link];
import [Link];
public class DeserializeExample {
public static void main(String[] args) {
try (FileInputStream fis = new
FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis)) {
Person person = (Person) [Link]();
[Link]("Deserialized Person: " +
[Link]() + ", Age: " + [Link]());
} catch (IOException | ClassNotFoundException e) {
[Link]();
1. Creating a Server
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
[Link]("Server listening on port 5000");
Socket clientSocket = [Link](); // Wait for
client
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true);
String message = [Link](); // Read message from
client
[Link]("Received from client: " + message);
[Link]("Hello from server!"); // Send response
} catch (IOException e) {
[Link]();
2. Creating a Client
import [Link].*;
import [Link].*;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new
PrintWriter([Link](), true);
[Link]("Hello from client!"); // Send message to
server
String response = [Link](); // Read response from
server
[Link]("Server response: " + response);
} catch (IOException e) {
[Link]();
Creating a Simple AWT Application
import [Link].*;
public class AWTExample {
public static void main(String[] args) {
Frame frame = new Frame("AWT Example");
Button button = new Button("Click Me");
[Link](button);
[Link](300, 200);
[Link](new FlowLayout());
[Link](true);
Event Handling in AWT
Event handling is how Java responds to user actions like button
clicks, mouse movements, etc.
In AWT, event handling is done using listeners.
How to Handle Events
[Link] Listener Interfaces: For specific events,
e.g., ActionListener for button clicks.
[Link] Listeners: Attach the listener to components.
Example: Button Click Event
import [Link].*;
import [Link].*;
public class ButtonClickExample extends Frame implements
ActionListener {
Button btn;
public ButtonClickExample() {
btn = new Button("Click Me");
add(btn);
setSize(300, 200);
setLayout(new FlowLayout());
// Register event listener
[Link](this);
setVisible(true);
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
public static void main(String[] args) {
new ButtonClickExample();
<!DOCTYPE html>
<html>
<head>
<title>My Java Applet</title>
</head>
<body>
<applet code="[Link]" width="300"
height="100"></applet>
</body>
</html>
[Link] in an applet viewer:
appletviewer [Link]
Note: Modern browsers no longer support Java applets. Use
appletviewer or legacy environments for testing.
Example: Interactive Applet with Button
import [Link].*;
import [Link].*;
import [Link].*;
public class ButtonApplet extends Applet implements ActionListener
{
String message = "Click the button!";
Button btn;
public void init() {
btn = new Button("Click Me");
add(btn);
[Link](this);
public void actionPerformed(ActionEvent e) {
message = "Button was clicked!";
repaint();
public void paint(Graphics g) {
[Link](message, 50, 50);
}
}