Java Programs
Java Programs
String name;
int rollno;
int age;
void info()
System.out.println("Name: "+name);
System.out.println("Age: "+age);
student.rollno = 253;
student.age = 25;
// Calling method
student.info();
}
OUTPUT
Name: Ramesh
Age: 25
Ex .no:2 /* INTERITANCE AND POLYMORPHISM*/
---------------------------------------------------------------
class Animal
}}
}}
}}
class Main {
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}}
OUTPUT:
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.*;
setLayout(new BorderLayout(5,5));
add(b1,"North");
add(b2,"South");
add(b3,"East");
add(b4,"West");
add(b5,"Center");
}
OUTPUT:
-------------
GRID:
---------
import java.awt.*;
import java.applet.*;
Button b1,b2,b3,b4;
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 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;
}
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;
}
}
OUTPUT:
-------------
Ex.no:07 : SWING CONCEPT
------------------------------
import javax.swing.*;
}
OUTPUT:
---------------
Ex.no : 8 /*Implementing Exception Handling*/
Output:
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
----------------------------------------------------------------------------------
Import java.net.DatagramPacket;
Import java.net.InetAddress;
InerAddress ip=InetAddress.getLocalHost();
While(true)
String inp=sc.nextLine();
Buf=inp.getBytes();
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;
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
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 :
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:
-----------------------------------------------------------
Client side program
<HTML>
<body>
Enter Register Number : <input type ="text" name="regno" value= " ">
</form>
</body>
</html>
Servlet Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
Connection con;
Statement st;
ResultSet rs;
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);
response.setContentType("text/html");
ResultSet rs;
String qr="";
try
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
if(rs.next())
{
out.print("<h4> Database Technology : " + rs.getString(2)+"</h4>");
else
} }
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;
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;
-----------------------------------------------------
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;
}
}
Output:
Welcome