Sie sind auf Seite 1von 73

INTRO

Java is an object-oriented pro programming interface (API) tha can be used to create application to Macintosh and Windows, and i of as a platform in itself. Java als

The term Java actual refers to m Java encompasses several parts,

A high level language glance looks very similar t own.

Java bytecode - a com language source code to b

JA

The basic features that make Java

Platform Inde nde pe nce


o

The Write-Once-Ru different platforms languages.

Obje Orie d ct nte


o o

Object oriented thr including main(). An extensive class

Com r/ Inte te Com pile rpre r bo

DIFFERENCE

Java is a true object-oriented la object-oriented extension.

Java does not support typedefs, there are no provisions for includi

Perhaps the single biggest differ support pointers. Pointers are inh not exist in Java, neither does t found in Java.

Java does not include str these other forms. Java does

no

The concept of inheritance is used objective is to reduce the redun similar attributes and operations

A class defines the abstract characteristics (its attributes behaviors or methods or featu traits shared by all dogs, for e Classes provide modularity and s class should typically be recogniz domain, meaning that the charac Also, the code for a class sho properties and methods defined b Objectives: Creating Classes in Java 2

describe software objects an oriented programming approach.

A Java package is a mechanism packages can be stored in compre download faster as a group rathe use packages to organize classes functionality.

Java source files can include a pa the package for the classes the so

A package provides a uniq Classes in the same packa A package can contain the o Classes o Interfaces o Enumerated types o Annotations

A Java interface defines a set o which implements an interface defined within the interface (as su Interfaces: Why are they useful? Interfaces are ideally used given A number of classes share yet cannot be related th appropriate). Further to the above po number of classes (which A design problem requires Example of an interface in The example that follows is an in some common functionality but a I can take two objects and deter 2), then I can easily write a meth

APP

All applets have the following fou public public public public void void void void init(); start(); stop(); destroy();

They have these methods becaus methods.

In the superclass, these are simp public void init() {}

Subclasses may override these m

JAV

JavaServer Pages (JSP) is a Ja dynamically generate HTML, XML client request. The technology all embedded into static content.

The JSP syntax adds additional XM invoke built-in functionality. Addit JSP tag libraries that act as exten libraries provide a platform indep server.

JSPs are compiled into Java Servl a servlet in Java code that is then byte code for the servlet directly. Sun.

Advantages of JSP?

vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate the HTML. Plus, by separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content. vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including externally-defined pieces into a static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like. vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access server-side resources like databases, catalogs, pricing information, and the like. vs. Static HTML. Regular HTML, of course, cannot contain dynamic information. JSP is so easy and convenient that it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amounts of dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuable instances.

What is a Servlet? Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet". Servlets make use of the Java standard extension classes in the packages javax.servlet (the basic Servlet framework) and javax.servlet.http (extensions of the Servlet framework for Servlets that answer HTTP requests). Since Servlets are written in the highly portable Java language and follow a standard framework, they provide a means to create sophisticated server extensions in a server and operating system independent way. Typical uses for HTTP Servlets include:

Processing and/or storing data submitted by an HTML form. Providing dynamic content, e.g. returning the results of a database query to the client. Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

The Basic Servlet Architecture A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. In this tutorial we'll be discussing only HTTP Servlets which extend the javax.servlet.http.HttpServlet class. In order to initialize a Servlet, a server application loads the Servlet class (and probably other classes which are referenced by the Servlet) and creates an instance by calling the no-args constructor. Then it calls the Servlet's init(ServletConfig config) method. The Servlet should performe one-time setup procedures in this method and store the ServletConfig object so that it can be retrieved later by calling the Servlet's getServletConfig() method. This is handled by GenericServlet. Servlets which extend GenericServlet (or its subclass HttpServlet) should call super.init(config) at the beginning of the init method to make use of this feature. The ServletConfig object contains Servlet parameters and a reference to the Servlet's ServletContext. The init method is guaranteed to be called only once

during the Servlet's lifecycle. It does not need to be thread-safe because the service method will not be called until the call to init returns. When the Servlet is initialized, its service(ServletRequest req, ServletResponse res) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) so it should be implemented in a thread-safe manner. Techniques for ensuring that the service method is not called concurrently, for the cases where this is not possible, are described in section 4.1. When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down) the destroy() method is called. There may still be threads that execute the service method when destroy is called, so destroy has to be thread-safe. All resources which were allocated in init should be released in destroy. This method is guaranteed to be called only once during the Servlet's lifecycle. A typical Servlet lifecycle

Servlets vs CGI The traditional way of adding functionality to a Web Server is the Common Gateway Interface (CGI), a language-independent interface that allows a server to start an external process which gets information about a request through environment variables, the command line and its standard input stream and writes response data to its standard output stream. Each request is answered in a separate process by a separate instance of the CGI program, or CGI script (as it is often called because CGI programs are usually written in interpreted languages like Perl). Servlets have several advantages over CGI:

A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.

A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request. There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data. A Servlet can be run by a Servlet Engine in a restrictive Sandbox (just like an Applet runs in a Web Browser's Sandbox) which allows secure use of untrusted and potentially harmful Servlets.

A Java Bean is a reusable softwar application builder tool. The ide components, and quickly wire t actually writing any new code.

Software components must, in with the rest of the world. java.awt.Component class, which standard methods like paint(), s to inherit a particular base class do provide support for some or al

Support for introspectio application builder discov associated with a java bea Support for properties. Th

JDBC

The JDBC API is a Java API that c stored in a Relational Database.

JDBC helps you to write java appl activities:

1. Connect to a data source, 2. Send queries and update s 3. Retrieve and process the r query The following simple code steps: 4. 5.

Connection con = Driver ( "jdbc:myDriver

INTROD
Overview

Remote Method Invocation (RMI Machines (JVMs). JVMs can be invoke methods belonging to a pass objects that a foreign virtu dynamic loading of new classes a

Developer A writes a serv updates this service, addi Developer B wishes to us inconvenient for A to supp

Java RMI provides a very easy s Developer B can let RMI handle the new classes in a web directo

PROGRAMS

1. /*Program for Matrix Addition*/

import java.io.*; class MatrixAdd { int a[][],b[][],c[][]; DataInputStream d; public MatrixAdd() { a=new int[2][2]; b=new int[2][2]; c=new int[2][2]; d= new DataInputStream(System.in); } public void input() throws IOException { System.out.println("Enter value in first matrix"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { a[i][j]=Integer.parseInt(d.readLine()); System.out.println(); } } System.out.println("Enter value in second matrix"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { b[i][j]=Integer.parseInt(d.readLine()); System.out.println(); } } } public void add() { for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { c[i][j]= a[i][j]+b[i][j]; } }

} public void display() { System.out.println("Sum Of Matrix"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { System.out.print(c[i][j]+ "\t" ); } System.out.println(); } } public static void main(String args[]) throws IOException { MatrixAdd m= new MatrixAdd(); m.input(); m.add(); m.display(); } }

OUTPUT

C:\jdk1.4\bin>javac MatrixAdd.java C:\jdk1.4\bin>java MatrixAdd Enter value in first matrix 1 2 3 4 Enter value in second matrix 5 6 1 2 Sum Of Matrix 6 8 4 6

2. /* Interface*/ /* Program to implement Interface*/ interface inter1 { public void display(); } class test { public void test1() { System.out.println("This is the test1 method of class test"); } } public class intcla extends test implements inter1 { public void display() { System.out.println("This is the display method of interface1"); } public void empl() { System.out.println("This is the empl method of class intcla"); } public static void main(String args[]) { intcla c = new intcla(); c.empl(); c.display(); c.test1(); }

OUTPUT C:\jdk1.4\bin>javac intcla.java C:\jdk1.4\bin>java intcla This is the empl method of class intcla This is the display method of interface1 This is the test1 method of class test

3. /* Programme to check Palindrome*/ import java.io.*; public class PalinDrome { public static void main(String args[]) throws IOException { String str; boolean chk=false; int i=0,l=0; DataInputStream d= new DataInputStream(System.in); System.out.println("Enter Your String"); str = d.readLine(); l = str.length(); while(i<l) { if(str.charAt(i)== str.charAt(l-1)) chk = true; else { chk = false; break; } i++; l--; } if(chk) System.out.println("PalinDrome"); else System.out.println("Not PalinDrome"); } }

OUTPUT C:\jdk1.4\bin>java PalinDrome Enter Your String malayalam PalinDrome C:\jdk1.4\bin>java PalinDrome Enter Your String ramayana Not PalinDrome

4. /*Program to find the frequency of character in a word*/ import java.io.*; public class FrCount { public static void main(String args[]) throws IOException { String str, ch; int i=0,l=0; DataInputStream d= new DataInputStream(System.in); System.out.println("Enter String "); str = d.readLine(); System.out.println("Enter the character"); ch = d.readLine(); l= str.length(); int count=0; while(i<l) { if(str.charAt(i)== ch.charAt(0)) count++; i++; } System.out.println("Frequency ="+count); } }

OUTPUT C:\jdk1.4\bin>java FrCount Enter String frequency Enter the character e Frequency =2 C:\jdk1.4\bin>java FrCount Enter String frequency Enter the character a Frequency =0

5. /* Programme for Constructor*/ class ConstLoad { String name; int age; public ConstLoad() { System.out.println("Default Constructor"); } public ConstLoad(String name) { this.name=name; System.out.println("Name : "+name); } public ConstLoad (int age) { this.age=age; System.out.println("Age :"+age); } public void ConstLoad() { System.out.println("Method"); } } public class Constructor { public static void main(String args[]) { ConstLoad c=new ConstLoad(); ConstLoad c1=new ConstLoad("XYZ"); ConstLoad c2=new ConstLoad(22); c.ConstLoad(); } }

OUTPUT C:\jdk1.4\bin>javac Constructor.java C:\jdk1.4\bin>java Constructor Default Constructor Name : XYZ Age :22 Method

6./*Inheritance*/ class Inher { public void check() { System.out.println(" Test Inheritance"); } } public class Inheritance extends Inher { public static void main(String args[]) { Inheritance in=new Inheritance(); in.check(); } } OUTPUT C:\jdk1.4\bin>java Inheritance Test Inheritance

7. /*Function Overloading*/ class FuncLoad { public int addIt(int a,int b) { return(a+b); } public double addIt(double a,double b,double c) { return(a+b+c); } } public class FuncOver { public static void main(String args[]) { int s1; double s2; FuncLoad fl=new FuncLoad(); s1= fl.addIt(2,7); s2= fl.addIt(2.3,1.5,7.0); System.out.println(s1); System.out.println(s2); } }

OUTPUT C:\jdk1.4\bin>javac FuncOver.java C:\jdk1.4\bin>java FuncOver 9 10.8

8. /*Function Overriding*/ class Base { void override() { System.out.println("I am in Base class"); } } class Derived extends Base { void override() { super.override(); System.out.println("I am overridden in derived class"); } } class FunOverride { public static void main(String args[]) { Derived d=new Derived(); d.override(); } }

OUTPUT C:\jdk1.4\bin>javac FunOverride.java C:\jdk1.4\bin>java FunOverride I am in Base class I am overridden in derived class

9. /* Matrix Multiplication*/ import java.io.*; public class MatrixMul1 { boolean chk=false; int a[][],b[][],c[][],n=0,m=0,p=0,q=0; DataInputStream din; public MatrixMul1() { din=new DataInputStream(System.in); } // enter the number of row&coloumn for two matrices public void rowcolumn()throws IOException { //din=new DataInputStream(System.in); System.out.println("Enter the number of rows of first matrix:"); n=Integer.parseInt(din.readLine()); System.out.println("Enter the number of columns of first matrix:"); m=Integer.parseInt(din.readLine()); System.out.println("Enter the number of rows of second matrix:"); p=Integer.parseInt(din.readLine()); System.out.println("Enter the number of columns of second matrix:"); q=Integer.parseInt(din.readLine()); a=new int[n][m]; b=new int[p][q]; c=new int[n][q]; } public void input()throws IOException { // a=new int[n][m]; //b=new int[p][q]; //c=new int[n][q]; // Enter values in first matrix System.out.println("Enter the elements in first matix"); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=Integer.parseInt(din.readLine()); System.out.print("\t");

} System.out.println(); } //Enter values in second matrix System.out.println("Enter the elements in second matix"); for(int i=0;i<p;i++) { for(int j=0;j<q;j++) { b[i][j]=Integer.parseInt(din.readLine()); System.out.print("\t"); } System.out.println(); } } // check for multiplication public boolean check() { if(m==p) { System.out.println("Multiplication may be possible"); chk=true; } else { System.out.println("Multiplication may not be possible"); chk=false; } return(chk); } //multiplication of two matrices public void mul() { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { c[i][j]=0; for(int k=0;k<p;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); }

} } } // Now display the result public void display() { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(c[i][j]+"\t"); } System.out.println(); } } public static void main(String []args)throws IOException { MatrixMul1 mult=new MatrixMul1(); mult.rowcolumn(); boolean ck=mult.check(); if(ck) { mult.input(); mult.mul(); mult.display(); } } }

OUTPUT C:\jdk1.4\bin>javac MatrixMul1.java C:\jdk1.4\bin>java MatrixMul1 Enter the number of rows of first matrix: 3 Enter the number of columns of first matrix: 2 Enter the number of rows of second matrix: 5 Enter the number of columns of second matrix: 1 Multiplication may not be possible C:\jdk1.4\bin>java MatrixMul1 Enter the number of rows of first matrix: 3 Enter the number of columns of first matrix: 3 Enter the number of rows of second matrix: 3 Enter the number of columns of second matrix: 3 Multiplication may be possible Enter the elements in first matix 1 1 1 1 1 1 1 1 1 Enter the elements in second matix 1 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3 3 3

10./*Multithreading*/ import java.*; class th1 extends Thread { public void run() { for(int i=0;i<100;i++) { try{ System.out.println("Value of I in class FIRST "+i); Thread.sleep(1000); }catch(Exception e){} } } } class th2 extends Thread { public void run() { for(int j=0;j<100;j++) { try{ System.out.println("Value of J in class SECOND "+j); Thread.sleep(1000); }catch(Exception e){} } } } class th3 extends Thread { public void run() { for(int j=0;j<100;j++) { try{ System.out.println("Value of J in class THIRD "+j); Thread.sleep(1000); }catch(Exception e){} } } } public class thread { public static void main(String args[])

{ th1 t1=new th1(); th2 t2=new th2(); th3 t3=new th3(); t3.setPriority(9); t1.start(); t2.start(); t3.start(); } }

OUTPUT

C:\jdk1.4\bin>javac thread.java C:\jdk1.4\bin>java thread Value of J in class THIRD 0 Value of I in class FIRST 0 Value of J in class SECOND Value of J in class THIRD 1 Value of I in class FIRST 1 Value of J in class SECOND Value of J in class THIRD 2 Value of I in class FIRST 2 Value of J in class SECOND Value of J in class THIRD 3 Value of I in class FIRST 3 Value of J in class SECOND Value of J in class THIRD 4 Value of I in class FIRST 4 Value of J in class SECOND Value of J in class THIRD 5 Value of I in class FIRST 5 Value of J in class SECOND Value of J in class THIRD 6 Value of I in class FIRST 6 Value of J in class SECOND Value of J in class THIRD 7 Value of I in class FIRST 7 Value of J in class SECOND

0 1 2 3 4 5 6 7

Value of J in class THIRD 8 Value of I in class FIRST 8 Value of J in class SECOND 8 Value of J in class THIRD 9 Value of I in class FIRST 9 Value of J in class SECOND 9 Value of J in class THIRD 10 Value of I in class FIRST 10 Value of J in class SECOND 10 Value of J in class THIRD 11 Value of J in class SECOND 11 Value of I in class FIRST 11 Value of J in class THIRD 12 Value of J in class SECOND 12 Value of I in class FIRST 12 Value of J in class THIRD 13 Value of J in class SECOND 13 Value of I in class FIRST 13 Value of J in class THIRD 14 Value of J in class SECOND 14 Value of I in class FIRST 14

11. /* Creation of Package*/ package mypack; import java.io.*; public class TestPack { DataInputStream d; String name; int age; public TestPack() { name=""; age=0; d=new DataInputStream(System.in); } public void input() throws Exception { System.out.println("Information: "); System.out.println("Enter Your Name: "); name=d.readLine(); System.out.println("Enter Your Age: "); age=Integer.parseInt(d.readLine()); } public void show() { System.out.println("Information: "); System.out.println("Name: "+name); System.out.println("Age: "+age); } }

import mypack.TestPack; public class TestPackTest { public static void main(String arg[]) throws Exception { TestPack t1=new TestPack(); t1.input(); t1.show(); } }

OUTPUT C:\xyz>javac -d c:\xyz TestPack.java C:\xyz>javac TestPackTest.java C:\xyz>java TestPackTest Information: Enter Your Name: Gyan Prakash Enter Your Age: 18 Information: Name: Gyan Prakash Age: 18

12. /* Program to create an applet*/ import java.awt.*; import java.applet.*; /* <html><body><applet code="AppletTest.class" width=500 height=600></applet></body></html>*/ public class AppletTest extends Applet { public void init() { setBackground(Color.RED); setForeground(Color.GREEN); } public void start() { } public void stop() { } public void destroy() { } public void paint(Graphics g) { g.drawString("THIS IS MY FIRST APPLET",20,50); } }

OUTPUT C:\jdk1.4\bin>javac AppletTest.java C:\jdk1.4\bin>appletviewer AppletTest.java

13. /*Mouse Movement*/ import java.awt.*; import java.awt.event.*; import java.applet.*; /* <html><body><applet code="Mouse.class" width=500 height=600></applet></body></html>*/ public class Mouse extends Applet implements MouseMotionListener,MouseListener { int x,y; public void Setxy(int a,int b) { x=a; y=b; repaint(); } public void init() { //Button b; setLayout(new FlowLayout()); addMouseListener(this); addMouseMotionListener(this); setSize(500,500); setVisible( true); } public void mouseReleased(MouseEvent me) { Setxy(me.getX(), me.getY()); } public void mouseMoved(MouseEvent me) { } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { }

public void mouseDragged(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { } public void paint(Graphics g) { for(int i=0;i<800;i=i+50) { for(int j=0;j<800;j=j+50) { g.drawLine(i,j,x,y); } } } }

OUTPUT C:\jdk1.4\bin>javac Mouse.java C:\jdk1.4\bin>appletviewer Mouse.java

14./*MultiButton*/ import java.awt.*; import java.awt.event.*; public class MultiButton extends Frame implements ActionListener { String s1[]={"1","2","3","4","5","6","7","8","9"}; Button b[]=new Button[s1.length]; public MultiButton(String s) { super(s); setLayout(new GridLayout(3,3)); for(int i=0;i<s1.length;i++) { b[i]=new Button(s1[i]); b[i].addActionListener(this); add (b[i]); } setSize(500,500); setVisible(true); } public void actionPerformed(ActionEvent ae) { for(int i=0;i<s1.length;i++) { if(ae.getSource()==b[i]) b[i].setVisible(false); else b[i].setVisible(true); } } public static void main(String args[]) { new MultiButton("Frame"); } }

OUTPUT C:\jdk1.4\bin>javac MultiButton.java C:\jdk1.4\bin>java MultiButton

15. /* Pragram to create Typewritter*/ import java.awt.*; import java.awt.event.*; class TextShift extends Frame implements KeyListener,ActionListener { TextArea t1,t2; Button b; public TextShift (String s) { super(s); setLayout(new FlowLayout(0)); b=new Button("CLOSE"); t1=new TextArea(30,50); t2=new TextArea(30,70); t1.addKeyListener(this); t2.addKeyListener(this); b.addActionListener(this); add(b); add(t1); add(t2); setSize(500,500); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b) { dispose(); } } public void keyTyped(KeyEvent k) { if(k.getSource()==t1) { String s1=t1.getText(); t2.setText(s1); } } public void keyReleased(KeyEvent k) {

} public void keyPressed(KeyEvent k) { } public static void main(String args[]) { new TextShift("Frame"); } } OUTPUT C:\jdk1.4\bin>javac TextShift.java C:\jdk1.4\bin>java TextShift

16. /*Program to create the picture of heart using applet*/ import java.awt.geom.*; import java.applet.*; import java.awt.*; /*<html><body> <applet code="heart.class" width=800 height=600> </applet></body></html>*/ public class heart extends Applet { public void paint(Graphics g) { // int x[]={ 200,50,300,200}; // int y[]={ 50,250,250,50}; // g.drawPolygon(x,y,4); //g.setColor(Color.black); // g.fillPolygon(x,y,4); // g.setColor(Color.red); //g.drawLine(0,0,100,100); //g.drawLine(100,100,100,50); //g.drawLine(100,50,0,0); //g.fillLine(Color.red); Graphics2D g2d=(Graphics2D)g; setBackground(Color.black); g2d.setColor(Color.red); CubicCurve2D c1=new CubicCurve2D.Float(400,200,200,50,300,400,400,400); //g2d.fillCubicCurve(400,200,200,50,300,400,300,400); CubicCurve2D c2=new CubicCurve2D.Float(400,200,600,50,500,400,400,400); g2d.draw(c1); g2d.draw(c2); g2d.fill(c1); g2d.fill(c2); g.setColor(Color.green); g.drawOval(320,210,40,40); g.drawOval(450,200,40,40); g.setColor(Color.magenta); g.drawOval(330,220,20,20); g.fillOval(330,220,20,20); g.drawOval(460,210,20,20);

g.fillOval(460,210,20,20); g.drawArc(350,280,90,50,0,180); g.drawArc(350,275,90,50,0,180); g.drawArc(350,280,90,50,180,360); g.drawArc(350,275,90,50,180,360); g.setColor(Color.green); g2d.drawLine(200,400,600,200); //g.draw3DRect(0,0,50,60,true);

//img=getImage(getCodeBase(),c:\\abc.jpeg); //g.drawImage(img,10,10,60,50,this); //g.draw3DRect(80,80,100,100,true); } }

OUTPUT C:\jdk1.4\bin>javac heart.java C:\jdk1.4\bin>appletviewer heart.java

17. /* Programme for Frame*/ import java.awt.*; import java.awt.event.*; public class MyFrame extends Frame implements ActionListener { Button b; public MyFrame(String s) { super(s); setLayout(new FlowLayout()); b=new Button("CLOSE"); b.addActionListener(this); add(b); setSize(500,500); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b) dispose(); } public static void main(String args[]) { new MyFrame("Frame"); } }

OUTPUT C:\jdk1.4\bin>javac MyFrame.java C:\jdk1.4\bin>java MyFrame

18. /*Client-Server chatting program*/

/*Server Program------------*/ import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; class ReadThread extends Thread { TextArea ta; Socket cs; public ReadThread(Socket c,TextArea t) { cs=c; ta=t; } public void run() { try{ while(true) { BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream())); ta.append("\n"+in.readLine()); } } catch(Exception e) { System.out.println(e); } } } public class SGUI extends Frame implements ActionListener { TextArea t; TextField f; Button b1,b2; ServerSocket ss=null; Socket cs=null;

public SGUI (String s) { super(s); try { ss=new ServerSocket (2222); cs=ss.accept(); } catch(Exception e) { System.out.println(e); } setLayout(new FlowLayout(0)); b1=new Button("Send"); b2=new Button("Close"); t=new TextArea(20,50); f=new TextField(30); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); add(t); add(f); ReadThread rd=new ReadThread(cs,t); rd.start(); setSize(500,500); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { try { PrintWriter pw=new PrintWriter(cs.getOutputStream()); pw.println(f.getText()); pw.flush(); f.setText(" "); } catch(Exception e) { System.out.println(e);

} } else { dispose(); } } public static void main(String args[]) { new SGUI("SGUI"); } }

/*Client Program------------*/ import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; class ReadThread extends Thread { TextArea ta; Socket cs; public ReadThread(Socket c,TextArea t) { cs=c; ta=t; } public void run() { try{ while(true) { BufferedReader in=new BufferedReader(new

InputStreamReader(cs.getInputStream())); ta.append("\n"+in.readLine()); } } catch(Exception e) { System.out.println(e); } } } public class CGUI extends Frame implements ActionListener { TextArea t; TextField f; Button b1,b2; Socket cs=null; public CGUI(String s) { super(s); try { cs=new Socket(InetAddress.getLocalHost(),2222); } catch(Exception e) { System.out.println(e); } setLayout(new FlowLayout(0)); b1=new Button("Send"); b2=new Button("Close"); t=new TextArea(20,50); f=new TextField(30); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); add(t); add(f); ReadThread rd=new ReadThread(cs,t); rd.start(); setSize(500,500); setVisible(true);

} public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { try { PrintWriter pw=new PrintWriter(cs.getOutputStream()); pw.println(f.getText()); pw.flush(); f.setText(" "); } catch(Exception e) { System.out.println(e); } } else { dispose(); } } public static void main(String args[]) { new CGUI("CGUI"); } }

OUTPUT C:\jdk1.3\bin>javac SGUI.java C:\jdk1.3\bin>java SGUI C:\jdk1.3\bin>javac CGUI.java C:\jdk1.3\bin>java CGUI

19. /* Program to implement database application*/ import java.sql.*; class TestCon { public static void main(String args[]) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("Jdbc:Odbc:dat"); Statement st=con.createStatement(); st.execute("insert into table1 values('ram')"); st.close(); con.close(); } } OUTPUT C:\jdk1.4\bin>javac TestCon.java C:\jdk1.4\bin>java TestCon

20. /* Use of RMI Package*/ import java.rmi.*; import java.net.MalformedURLException; //Client implementation public class HelloClient { //main method public static void main(String []helloClient) { try{ //get a reference to the stub HelloInterface server = (HelloInterface)Naming.lookup("rmi://localhost:1099/Server"); //Call the remote method String msg = server.getMessage(); System.out.println(msg); }catch(RemoteException ex) { System.out.println("Error " +ex.getMessage()); } catch(MalformedURLException ex) { System.out.println("Error " +ex.getMessage()); } catch(NotBoundException ex) { System.out.println("Error " +ex.getMessage()); } } }

import java.rmi.*; //Remote Interface // public interface HelloInterface extends Remote { //remote method. Returns a string object // public String getMessage() throws RemoteException; }

import java.rmi.*; import java.rmi.server.*; import java.net.MalformedURLException; import java.lang.*; //server class // public class HelloServerImpl extends UnicastRemoteObject implements HelloInterface{ //constructor // public HelloServerImpl() throws RemoteException { System.out.println("Creating server Object"); } //remote method called by clients // public String getMessage() throws RemoteException { return "Hello World"; } //main method public static void main(String []helloWorld) { try { //create a server object // HelloServerImpl helloServer = new HelloServerImpl(); //bind the server // Naming.rebind("Server",helloServer); System.out.println("Server Ready"); }catch(RemoteException ex) { System.out.println("Error " +ex.getMessage()); } catch(MalformedURLException ex) { System.out.println("Error " +ex.getMessage()); } } }

OUTPUT

Server

Client

21. /* Implementation of Sevlet*/ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class serv extends HttpServlet { PrintWriter pr; public void doGet(HttpServletRequest hsr,HttpServletResponse hsp)throws ServletException,IOException { PrintWriter pr=hsp.getWriter(); pr.println("<html><body><font size=30pt color=red>Hello friends</font> \n<font size=20pt color=green>This is my first Servlet</font>"); pr.println("</body></html>"); } }

22./*Java Servlet*/ //first servlet program import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class hello extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { PrintWriter pr=res.getWriter(); String name=req.getParameter("user"); pr.println("<html><body><font size=30pt color=red>Hello\nThis is my first Servlet</font>"); pr.println("<br><font color=green size=50pt>Your Name is "+name); pr.println("</body></html>"); } }

23. /* Use of Swing Package*/ import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Swng extends JFrame implements ActionListener { JComboBox cb; JTextField tf1,tf2; JButton b1,b2,b3; Container c; Object o[]={"USA","UK","RSA","UAE","KSA"}; public Swng(String s) { super(s); c=getContentPane(); setLayout(new FlowLayout()); cb=new JComboBox(o); tf1=new JTextField(10); tf2=new JTextField(10); b1=new JButton("ADD"); b2=new JButton("REMOVE"); b3=new JButton("CLOSE"); cb.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); add(cb);add(tf1);add(tf2);add(b1);add(b2);add(b3); setSize(600,600); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==cb) tf1.setText(String.valueOf(cb.getSelectedItem())); if(ae.getSource()==b1) cb.addItem(tf2.getText()); if(ae.getSource()==b2) cb.removeItem(cb.getSelectedItem()); if(ae.getSource()==b3) dispose(); } public static void main(String []arg) { new Swng("Swing Test"); }}

OUTPUT

24. /* Java Server Pages*/ <%-<html> <body> <h1> This is current time: which is not refereshable </h1> <%! out.print(new java.util.Date()); %> </body> </html> --%> <%@ page import="java.text.*,java.util.*" %> <%! DateFormat fmt=new SimpleDateFormat("hh:mm:ss aa"); String now=fmt.format(new Date()); %> The Time is <%=now%> which is not refreshable

25. /* Program to write Hello World using JSP*/ <%@ page language="java" contentType="text/html" %> <% String message="hello world"; %> <html> <title> welcome </title> <body bgcolor="pink"> <%= message %> </body> </html>

Das könnte Ihnen auch gefallen