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

Java Programs

The document contains 5 examples demonstrating different Java concepts: 1) Classes and objects - defines a Student class with properties and methods to print student details. 2) Inheritance and polymorphism - defines an Animal class and subclasses Pig and Dog that override the animalSound method. 3) Interfaces and packages - defines a Results interface and classes implementing it to calculate areas of shapes. 4) Layout managers - shows examples of FlowLayout, BorderLayout and GridLayout. 5) Tic tac toe game - implements a tic tac toe game between a human and computer player using various Java concepts.

Uploaded by

Barathkumar K
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)
14 views

Java Programs

The document contains 5 examples demonstrating different Java concepts: 1) Classes and objects - defines a Student class with properties and methods to print student details. 2) Inheritance and polymorphism - defines an Animal class and subclasses Pig and Dog that override the animalSound method. 3) Interfaces and packages - defines a Results interface and classes implementing it to calculate areas of shapes. 4) Layout managers - shows examples of FlowLayout, BorderLayout and GridLayout. 5) Tic tac toe game - implements a tic tac toe game between a human and computer player using various Java concepts.

Uploaded by

Barathkumar K
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/ 53

Ex .

no:1 /* CLASSES AND OBJECTS*/


--------------------------------------------
public class Student

String name;

int rollno;

int age;

void info()

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

System.out.println("Roll Number: "+rollno);

System.out.println("Age: "+age);

public static void main(String[] args)

Student student = new Student();

// Accessing and property value student.name = "Ramesh";

student.rollno = 253;

student.age = 25;

// Calling method

student.info();

}
OUTPUT

Name: Ramesh

Roll Number: 253

Age: 25
Ex .no:2 /* INTERITANCE AND POLYMORPHISM*/
---------------------------------------------------------------
class Animal

public void animalSound()

System.out.println("The animal makes a sound");

}}

class Pig extends Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");

}}

class Dog extends Animal {

public void animalSound() {

System.out.println("The dog says: bow wow");

}}

class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();

myPig.animalSound();

myDog.animalSound();

}}
OUTPUT:

The animal makes a sound

The pig says: wee wee

The dog says: bow wow


Ex .no:3 /* INTERFACE AND PACKAGE*/
-----------------------------------------------------

interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)
{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}

Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594
Ex .no:4 /*FLOW,BORDER AMD GRID LAYOUT*/
-----------------------------------------------------
FLOW:
----------
import java.awt.*;
import java.applet.*;
public class FlowLayoutDemo extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,5,5));
for(int i=1;i<12;i++)
{
add(new Button("Toys"+i));
}
}
}
OUTPUT:
-------------
BORDER:

--------------

import java.awt.*;

import java.applet.*;

public class BorderLayoutDemo extends Applet

public void init()

setLayout(new BorderLayout(5,5));

Button b1=new Button("North");

Button b2=new Button("south");

Button b3=new Button("East");

Button b4=new Button("West");

Button b5=new Button("Center");

add(b1,"North");

add(b2,"South");

add(b3,"East");

add(b4,"West");

add(b5,"Center");

}
OUTPUT:
-------------
GRID:

---------

import java.awt.*;

import java.applet.*;

public class GridLayoutDemo extends Applet

Button b1,b2,b3,b4;

GridLayout g=new GridLayout(2,2);

public void init()

setLayout(g);

b1=new Button("Xavier");

b2=new Button("Cathrin");

b3=new Button("Benjamin");

b4=new Button("John");

add(b1);

add(b2);

add(b3);

add(b4);

}
OUTPUT:
-------------
Ex .no :5 TIC TAC TOE
---------------------
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.applet.*;
public
class TicTacToe extends Applet {
/**
* White's current position. The computer is white.
*/
int white;

/**
* Black's current position. The user is black.
*/
int black;

/**
* The squares in order of importance...
*/
final static int moves[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};

/**
* The winning positions.
*/
static boolean won[] = new boolean[1 << 9];
static final int DONE = (1 << 9) - 1;
static final int OK = 0;
static final int WIN = 1;
static final int LOSE = 2;
static final int STALEMATE = 3;

/**
* Mark all positions with these bits set as winning.
*/
static void isWon(int pos) {
for (int i = 0 ; i < DONE ; i++) {
if ((i & pos) == pos) {
won[i] = true;
}
}
}

/**
* Initialize all winning positions.
*/
static {
isWon((1 << 0) | (1 << 1) | (1 << 2));
isWon((1 << 3) | (1 << 4) | (1 << 5));
isWon((1 << 6) | (1 << 7) | (1 << 8));
isWon((1 << 0) | (1 << 3) | (1 << 6));
isWon((1 << 1) | (1 << 4) | (1 << 7));
isWon((1 << 2) | (1 << 5) | (1 << 8));
isWon((1 << 0) | (1 << 4) | (1 << 8));
isWon((1 << 2) | (1 << 4) | (1 << 6));
}

/**
* Compute the best move for white.
* @return the square to take
*/
int bestMove(int white, int black) {
int bestmove = -1;

loop:
for (int i = 0 ; i < 9 ; i++) {
int mw = moves[i];
if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
int pw = white | (1 << mw);
if (won[pw]) {
// white wins, take it!
return mw;
}
for (int mb = 0 ; mb < 9 ; mb++) {
if (((pw & (1 << mb)) == 0) && ((black & (1 << mb)) == 0)) {
int pb = black | (1 << mb);
if (won[pb]) {
// black wins, take another
continue loop;
}
}
}
// Neither white nor black can win in one move, this will do.
if (bestmove == -1) {
bestmove = mw;
}
}
}
if (bestmove != -1) {
return bestmove;
}

// No move is totally satisfactory, try the first one that is open


for (int i = 0 ; i < 9 ; i++) {
int mw = moves[i];
if (((white & (1 << mw)) == 0) && ((black & (1 << mw)) == 0)) {
return mw;
}
}

// No more moves
return -1;
}

/**
* User move.
* @return true if legal
*/
boolean yourMove(int m) {
if ((m < 0) || (m > 8)) {
return false;
}
if (((black | white) & (1 << m)) != 0) {
return false;
}
black |= 1 << m;
return true;
}

/**
* Computer move.
* @return true if legal
*/
boolean myMove() {
if ((black | white) == DONE) {
return false;
}
int best = bestMove(white, black);
white |= 1 << best;
return true;
}

/**
* Figure what the status of the game is.
*/
int status() {
if (won[white]) {
return WIN;
}
if (won[black]) {
return LOSE;
}
if ((black | white) == DONE) {
return STALEMATE;
}
return OK;
}

/**
* Who goes first in the next game?
*/
boolean first = true;

/**
* The image for white.
*/
Image notImage;
/**
* The image for black.
*/
Image crossImage;

/**
* Initialize the applet. Resize and load images.
*/
public void init() {
notImage = getImage(getClass().getResource("images/not.gif"));
crossImage = getImage(getClass().getResource("images/cross.gif"));
}

/**
* Paint it.
*/
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.black);
int xoff = d.width / 3;
int yoff = d.height / 3;
g.drawLine(xoff, 0, xoff, d.height);
g.drawLine(2*xoff, 0, 2*xoff, d.height);
g.drawLine(0, yoff, d.width, yoff);
g.drawLine(0, 2*yoff, d.width, 2*yoff);

int i = 0;
for (int r = 0 ; r < 3 ; r++) {
for (int c = 0 ; c < 3 ; c++, i++) {
if ((white & (1 << i)) != 0) {
g.drawImage(notImage, c*xoff + 1, r*yoff + 1, this);
} else if ((black & (1 << i)) != 0) {
g.drawImage(crossImage, c*xoff + 1, r*yoff + 1, this);
}
}
}
}

/**
* The user has clicked in the applet. Figure out where
* and see if a legal move is possible. If it is a legal
* move, respond with a legal move (if possible).
*/
public boolean mouseUp(Event evt, int x, int y) {
switch (status()) {
case WIN:
case LOSE:
case STALEMATE:
play(getClass().getResource("audio/return.au"));
white = black = 0;
if (first) {
white |= 1 << (int)(Math.random() * 9);
}
first = !first;
repaint();
return true;
}

// Figure out the row/colum


Dimension d = getSize();
int c = (x * 3) / d.width;
int r = (y * 3) / d.height;
if (yourMove(c + r * 3)) {
repaint();

switch (status()) {
case WIN:
play(getClass().getResource("audio/yahoo1.au"));
break;
case LOSE:
play(getClass().getResource("audio/yahoo2.au"));
break;
case STALEMATE:
break;
default:
if (myMove()) {
repaint();
switch (status()) {
case WIN:
play(getClass().getResource("audio/yahoo1.au"));
break;
case LOSE:
play(getClass().getResource("audio/yahoo2.au"));
break;
case STALEMATE:
break;
default:
play(getClass().getResource("audio/ding.au"));
}
} else {
play(getClass().getResource("audio/beep.au"));
}
}
} else {
play(getClass().getResource("audio/beep.au"));
}
return true;
}

public String getAppletInfo() {


return "TicTacToe by Arthur van Hoff";
}
}
OUTPUT:
Ex .no :6 FRAME, MENU AND DIALOG
------------------------------------------
DIALOG:
------------
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DialogDem extends Applet implements ActionListener
{
Button b;
TextField t;
public void init()
{
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
Frame f=new Frame("dialogdemo");
f.resize(width,height);
f.show();
Dialog d=new Dialog(f,"first dialog",false);
d.setLayout(new GridLayout(2,2));
d.setSize(200,200);
b=new Button("display");
d.add(b);
b.addActionListener(this);
t=new TextField(20);
d.add(t);
d.show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
t.setText("welcome to java");
}
}
}
OUTPUT:
-------------
MENU :
----------
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class menueg extends Applet implements ActionListener
{
Frame f;
TextArea text1;
MenuItem mi1,mi2,mi3,mi4;
public void init()
{
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
f=new Frame("demo frame");
f.setSize(width,height);
text1=new TextArea(" ",80,40);
f.add(text1);
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu file=new Menu("file");
mi1=new MenuItem("open");
file.add(mi1);
mi1.addActionListener(this);
mi2=new MenuItem("close");
file.add(mi2);
mi2.addActionListener(this);
mb.add(file);
Menu font=new Menu("font");
mi3=new MenuItem("color");
font.add(mi3);
mi3.addActionListener(this);
mi4=new MenuItem("size");
font.add(mi4);
mi4.addActionListener(this);
mb.add(font);
f.show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==mi1)
{
text1.append("open menu option selected"+"\n");
}
if(e.getSource()==mi2)
{
text1.append("close menu option selected"+"\n");
}
if(e.getSource()==mi3)
{
text1.append("color menu option selected"+"\n");
}
if(e.getSource()==mi4)
{
text1.append("size menu option selected"+"\n");
}
}

}
OUTPUT:
-------------
Ex.no:07 : SWING CONCEPT
------------------------------

import javax.swing.*;

public class FirstSwingExample {

public static void main(String[] args) {

JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height

f.setLayout(null);//using no layout managers

f.setVisible(true);//making the frame visible

}
OUTPUT:

---------------
Ex.no : 8 /*Implementing Exception Handling*/

class MyException extends Exception


{
String s1;
MyException(String s2)
{
s1=s2;
}

public String toString()


{
return("output string=" +s1);
}
}
public class newclass
{
public static void main(String[] args)
{
try
{
throw new MyException("custom message");
}
catch(MyException exp)
{
System.out.println(exp);
}
}
}

Output:

output string=custom message


Ex.no : 9 /*Implementing Multithreading*/

class MultithreadingDemo extends Thread


{
public void run()
{
try
{

System.out.println("thread"+Thread.currentThread().getId()+"isrunning");

}
catch(Exception e)
{
System.out.println("Exception is caught");

}
}
}
public class multithreading
{
public static void main(String[] args)
{
int n=8;
for(int i=0;i<8;i++)
{
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();

}
}

}
Output:

thread10isrunning
thread9isrunning
thread13isrunning
thread14isrunning
thread16isrunning
thread12isrunning
thread15isrunning
thread11isrunning
Ex.no:10 : I/O - STREAM FILE HANDLING
----------------------------------------------
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class copy05
{
public static void main(String args[])throws IOException
{
FileInputStream in=null;
FileOutputStream out=null;
try
{
in=new FileInputStream("G://sawc//abi.txt");
out=new FileOutputStream("G://sawc//outagain.txt");
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
}
finally
{
if(in!=null)
{
in.close();
}
if(out!=null)
{
out.close();
}
System.out.print("\n The string has been copied into new string...");
System.out.print("\n The IO handling is performed...");
}
}
}

OUTPUT:

---------------

C:\jdk1.2.1\bin>javac copy05.java

C:\jdk1.2.1\bin>java copy05

The string has been copied into new string...

The IO handling is performed...


Ex.no:11:

IMPLEMENTATION OF JAVA NETWORKING CONCEPTS

----------------------------------------------------------------------------------

/* Client Server using UDP Socket */

Client side Implementation

Import java .io.IOException;

Import java.net.DatagramPacket;

Import java .net.DatagamSocket;

Import java.net.InetAddress;

Import java .util .Scanner;

Public class udpBaseClient_2

Public static void main(String args[ ]) throws IOException

Scanner sc=new Scanner(System.in);

DatagramSocket ds=new DatagramSocket();

InerAddress ip=InetAddress.getLocalHost();

Byte buf[ ]=null;

While(true)

String inp=sc.nextLine();

Buf=inp.getBytes();

DatagramPAcket DpSend=new DatagramPacket(buf,buf.length,ip,1234);

ds.send(DpSend);
if(inp.equals(“bye”))

break;

Output:

Hello
I am client
……
……

Bye
Server Side Implementation

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import networking.udpBaseClient;

public class udpBaseServer_2


{
public static void main(String[] args) throws IOException
{
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[65535];
DatagramPacket DpReceive = null;

while (true)
{
DpReceive = new DatagramPacket(receive, receive.length);
ds.receive(DpReceive);
System.out.println("Client:-" + data(receive));
if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye.....EXITING");
break;
}
receive = new byte[65535];
}
}
public static StringBuilder data(byte[] a)
{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}

}
Output:
Client;hello

Client;i am client

Client-bye

Client sent by exiting


/*Client Server using TCP Socket*/

Client Side Implementation

import java.net.*;
class Clientdemo1
{
public static void main(String [ ] args)
{
try
{
String server=args[0];
int port=Integer.parseInt(args[1]);
Socket s=new Socket(server,port);
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream (is);
int i=dis.readInt( );
System.out.println(i);
s.close();
}
catch(Exception e)
{
System.out.println("exception:"+e);
}
}
}

Output :

C:\jdk1.2.1\bin>java Clientdemo1 127.0.0.1 4321


2742809
Server Side Implementation

import java.io.*;
import java.net.*;
class Serverdemo1
{
public static void main(String [ ] args)
{
try
{
int port=Integer.parseInt(args[0]);
ServerSocket ss=new ServerSocket(port);
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
DataOutputStream dos= new DataOutputStream(os);
dos.writeInt(2742809);
s.close();
}
catch(Exception e)
{
System.out.println("Exception :"+e);
}
}
}

Output:
C:\jdk1.2.1\bin>java Serverdemo1 4321
Ex.no:12:

IMPLEMENTATION OF JAVA SERVLETS

-----------------------------------------------------------
Client side program

<HTML>

<HEAD><TITLE> Results of a student</title></head>

<body>

<center><h3> University Examination Results </h3></center>

<form method = "GET" action="http://localhost:8080/examples/servlet/DisplayResult">

Enter Register Number : <input type ="text" name="regno" value= " ">

<input type ="submit" value="GetResult">

</form>

</body>

</html>
Servlet Program

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class DisplayResult extends HttpServlet {

Connection con;

Statement st;

ResultSet rs;

public void init()

try

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con =

DriverManager.getConnection("jdbc:odbc:MyDb","","");

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

st= con.createStatement();

catch(Exception e)

{
System.out.println(e);

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

ResultSet rs;

String qr="";

try

out.println("<html>");

out.println("<body>");

out.println("<head>");

out.println("<title> Results </title>");

out.println("</head>");

out.println("<body>");

out.print("<h3>Results of " + request.getParameter("regno")+"</H3>");

rs=st.executeQuery("select * from rtable where


rno='"+request.getParameter("regno")+"'");

out.println("<h3><pre> <FONT COLOR='BLUE'> Subject Name Grade


</FONT></H3></pre>");

if(rs.next())

{
out.print("<h4> Database Technology : " + rs.getString(2)+"</h4>");

out.print("<h4> Compiler Design : " + rs.getString(3)+"</h4>");

out.print("<h4> Object Oriented Analysis and Design ; " +


rs.getString(4)+"</h4>");

out.print("<h4> Web Technology : " + rs.getString(5)+"</h4>");

out.print("<h4> Information Security : " + rs.getString(6)+"</h4>");

out.print("<h4> High Speed Networks : " + rs.getString(7)+"</h4>");

else

out.println("<h1>Invalid Register Number</h1>");

} }

catch(Exception e)

out.println("<h1>"+qr+"<br>"+e+"</h1>");

finally

out.println("</body>");

out.println("</html>");

out.close();

}
OUTPUT : Client side Application
Servlet Output
Ex.no:13:

IMPLEMENTATION OF RMI

--------------------------------------------
RMI server program.
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
RMI client program.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
OUTPUT :
Ex.no:14:

IMPLEMENTATION OF JAVA BEANS

-----------------------------------------------------

// Java program to illustrate the


// getName() method on boolean type attribute
public class Test {
private boolean empty;
public boolean getName()
{
return empty;
}
public boolean isempty()
{
return empty;
}
}

Implementation
// Java Program of JavaBean class
package geeks;
public class Student implements java.io.Serializable
{
private int id;
private String name;
public Student()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}

// Java program to access JavaBean class


package geeks;
public class Test {
public static void main(String args[])
{
Student s = new Student(); // object is created
s.setName("Welcome"); // setting value to the object
System.out.println(s.getName());
}
}

Output:
Welcome

You might also like