Upload
ridam
View
52
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Java Lab Final
Citation preview
1. To simply run a java program.
class Example
{
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
Output:
2. 2.1 a one dimensional array declaration
class Array {
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Output:
2.2 one dimensional array declaration
class AutoArray {public static void main(String args[]) {int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,};System.out.println("April has " + month_days[3] + " days.");}}
Output:
3. Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
4. WAP for creating a class & its object./* WAP that uses the Box class. Call this file BoxDemo.java*/class Box {double width;double height;double depth;}class BoxDemo // This class declares an object of type Box. {public static void main(String args[]) {Box mybox = new Box();double vol; // assign values to mybox's instance variablesmybox.width = 10;mybox.height = 20;mybox.depth = 15; // compute volume of boxvol = mybox.width * mybox.height * mybox.depth; // compute volume of boxSystem.out.println("Volume is " + vol);}}
Output:
5. /* A code to display a call for constructor*/class Box {double width;double height;double depth;Box() // This is the constructor for Box. {System.out.println("Constructing Box");width = 10;height = 10;depth = 10; }double volume() // compute and return volume {return width * height * depth; }}class BoxDemo6 {public static void main(String args[]) {Box mybox1 = new Box(); // declare, allocate, and initialize Box objectsdouble vol;vol = mybox1.volume(); // get volume of first boxSystem.out.println("Volume is " + vol);}}
Output:
• 6. // Demonstrate method overloading.Test( ) is overloaded two times. The first version takes no parameters, the second takes one integer parameter.
class OverloadDemo {void test() {System.out.println("No parameters");}void test(int a) // Overload test for one integer parameter. {System.out.println("a: " + a);}}class Overload {public static void main(String args[]) {OverloadDemo ob = new OverloadDemo();double result;// call all versions of test()ob.test();ob.test(10);}}
Output:
7. WAP to show MethodOverriding
class A { int j = 1; int f( ) { return j; }}class B extends A { int j = 2; int f( ) { return j; }}class MethodOverriding { public static void main(String args[]) { B b = new B(); System.out.println(b.j); // refers to B.j prints 2 System.out.println(b.f()); // refers to B.f prints 2 A a = (A) b; System.out.println(a.j); // now refers to a.j prints 1 System.out.println(a.f()); // overridden method still refers to B.f() prints 2 ! } }
Output:
8. /*WAP to show Inheritance*/
/* Single Inhetitance To Find Area Of Rectangle */class Dimensions{int length;int breadth;}
class Rectangle extends Dimensions{int a;void area(){a = length * breadth;}
}
class AreaInheritance{public static void main(String args[]){Rectangle Rect = new Rectangle();Rect.length = 7;Rect.breadth = 16;Rect.area();System.out.println("The Area of rectangle of length "+Rect.length+" and breadth "+Rect.breadth+" is "+Rect.a);}}
Output:
9. wap to show Multilevel Inheritance
class A{ int i=10,j=20; void xyz() { System.out.println(i+j); } void lmn() { System.out.println("lmn"); }}class B extends A{ int k=40,l=45; void abc() { System.out.println(i+j+k); lmn(); }}class C extends B{}class MultilevelInherit{ public static void main(String args[]) { C a1= new C(); a1.abc(); }}
Output:
10. WAP to show an Interface
interface Area
{
final static float pi=3.14F;
float compute (float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area;
area = rect;
System.out.println("Area of Rectangle ="+area.compute(10,20));
area = cir;
System.out.println("Area of Circle ="+area.compute(10,0));
}
}
Output
11. WAP to implement a package
Step 1: Create a package
package FirstPack;
public class Test
{
public void view()
{
System.out.println("I am from Package");
}
}
Step 2. Save this package by creating a new folder by the name of “FirstPack” as package name and save the code as Test.java in notepad as D:\Java\bin\FirstPack\Test.java. This will create a new directory to store the package.
Step3. Create another code that imports the file stored in the package “FirstPack” using import statements as follows:
import FirstPack.Test;
public class MainPack
{
public static void main(String args[])
{
Test ob =new Test();
ob.view();
}
}
Step 4. Save it as MainPack.java
Step 5. GOTO cmd prompt and type the following command :
D:\Java\bin>javac FirstPack\Test.java
Test.class file will be created. After wards run the following command for importing the package into the main class “MainPack”
D:\Java\bin>javac MainPack.java
D:\Java\bin>java MainPack
Output:
12. WAP to create a simple thread
public class Threads{
public static void main(String[] args){
Thread th = new Thread();
System.out.println("Numbers are printing line by line after 5 seconds : ");
try{
for(int i = 1;i <= 10;i++)
{
System.out.println(i);
th.sleep(5000);
}
}
catch(InterruptedException e){
System.out.println("Thread interrupted!");
e.printStackTrace();
}
}
}
Output:
13. WAP to demonstrate 3 threads using the thread class.
import java.io.*;
class A extends Thread
{
public void run()
{
for (int i=1;i<5;i++)
{
System.out.println(" i="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for (int j=1;j<5;j++)
{
System.out.println(" j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for (int k=1;k<5;k++)
{
System.out.println(" k="+k);
}
System.out.println("Exit from C");
}
}
class ThreadExample
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
OutPut:
14. WAP to show Multithreading
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t=new Thread(this,"Demo Thread");
System.out.println("Child Thread :"+t);
t.start();
}
public void run()
{
try{
for(int i=5;i>0;i--)
{
System.out.println("Child Thread"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child interrupted");
}
System.out.println("exiting Child thread");
}
}
class ThreadDemo
{
public static void main(String arg[])
{
try{
for(int i=5;i>0;i--)
{
System.out.println("main Thread"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("main thread exiting.............");
}
}
Output:
15. WAP to show Exception Handling using finally
import java.lang.Exception;
class MyException extends Exception
{
MyException (String message)
{
super (message);
}
}
class TestmyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z= (float) x/ (float) y;
if (z<0.01)
{
throw new MyException("Number is too small");
}
}
catch (MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
Output:
16.1 WAP to construct one String from another.
class MakeString
{
public static void main(String args[])
{
char c[] = {'J','A','V','A'};
String s1= new String(c);
String s2= new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
16.2 WAP for a String Comparison:
class StringEqualsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "Hello";
System.out.println(s1+"equals"+s2+"->"+s1.equals(s2));
System.out.println(s1+"equals"+s3+"->"+s1.equals(s3));
System.out.println(s1+"equals"+s4+"->"+s1.equals(s4));
System.out.println(s1+"equalsIgnoreCase"+s4+"->"+s1.equalsIgnoreCase(s4));
}
}
Output:
16.3 wap to to search inside of a String using various index methods
class IndexofDemo
{
public static void main (String args[])
{
String s=("Now is the time for all good men"+"for come out to aid the country");
System.out.println(s);
System.out.println("indexOf(t)=" +s.indexOf('t'));
System.out.println("lastIndexOf(t)=" +s.lastIndexOf('t'));
System.out.println("indexOf(the)=" +s.indexOf("sthe"));
System.out.println("lastIndexOf(the)=" +s.lastIndexOf("the"));
System.out.println("indexOf(t,10)="+s.indexOf('t', 10));
System.out.println("lastIndexOf(t,60)="+s.lastIndexOf('t', 60));
System.out.println("indexOf(the,10)="+s.indexOf("the", 10));
System.out.println("lastIndexOf(the,60)="+s.lastIndexOf("the", 60));
}
}
Ouput:
17. WAP to write and into a file in Java using I/O.
To write into a file……..
import java.io.*;
public class IOwrite
{
// Main method
public static void main (String args[])
{
// Stream to write file
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream ("myfile.txt");
// Print a line of text
new PrintStream(fout).println ("hello world!");
// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}
To read from a file
We create a FileInputStream object, read the text, and display it to the user.
import java.io.*;
public class IOread{
// Main methodpublic static void main (String args[]){
// Stream to read fileFileInputStream fin;
try{ // Open an input stream fin = new FileInputStream ("myfile.txt");
// Read a line of text System.out.println( new DataInputStream(fin).readLine() );
// Close our input stream fin.close();}// Catches any error conditionscatch (IOException e){
System.err.println ("Unable to read from file");System.exit(-1);
}}
}
Output:
18. WAP to show networking using Client-Server Socket programming in java.
18.1 write a Code to create a Server socket
import java.io.*;
import java.net.*;
import java.net.Socket;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Output for Server socket:
18.2 Write a Code to create a Client Socket:
import java.io.*;
import java.net.*;
import java.net.Socket;
class TCPClient
{
public static void main(String argv[]) throws IOException
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream
(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Output for Client Socket:
Output for Networking Between Client and Server Socket.
19. To create a simple Applet
import java.awt.*;
import java.applet.Applet;
public class Applet1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello",30,30);
g.drawString("I am smart",40,40);
g.drawString("I am good",50,50);
g.drawString("I am a good Dancer",60,60);
g.drawString("Have fun n enjoy this class",70,70);
g.drawString("God bless u all",80,80);
}
}
/*
<applet code= "Applet1.class" width = 500 height = 500>
</applet>
*/
Output:
Run file as
C:\java\bin> javac Applet1.java
C:\java\bin>appletviewer Applet1.java
20. WAP to draw a rectangle and fill color into it using an Applet.
import java.awt.*;
import java.applet.*;
public class Applet2 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.drawString("God bless u all",200,200);
g.drawRect(50,50,100,100);
g.setColor(Color.GREEN);
g.fillRect(50,50,100,100);
g.setColor(Color.RED);
g.fillOval(50,50,100,100);
}
}
/*
<applet code= "Applet2.class" width = 500 height = 500>
</applet>
*/
Output:
21.1 To create a basic window using Swing in Java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Example1 extends JFrame {
public Example1() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example1 ex = new Example1();
ex.setVisible(true);
}
});
}
}
Output:
21.2 WAP to create a simple window and add a button to it using Swings in Java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Example2 extends JFrame {
public Example2() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(quitButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example2 ex = new Example2();
ex.setVisible(true);
}
});
}
}
Output:
21.3 Code to add a Tooltip and add a button to a window created using Swing
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Example3 extends JFrame {
public Example3() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("A Panel container");
JButton button = new JButton("Button");
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
panel.add(button);
setTitle("Tooltip");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example3 ex = new Example3();
ex.setVisible(true);
}
});
}
}
Output: