0% found this document useful (0 votes)
46 views34 pages

File

The document contains several code examples showing how to write programs in Java. Examples include printing messages, checking if a number is even or odd, creating classes and calling methods, working with threads and priorities, handling exceptions, using strings and string buffers, working with arrays and matrices, and networking examples like getting the host name and IP address.

Uploaded by

Samuel Davis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
46 views34 pages

File

The document contains several code examples showing how to write programs in Java. Examples include printing messages, checking if a number is even or odd, creating classes and calling methods, working with threads and priorities, handling exceptions, using strings and string buffers, working with arrays and matrices, and networking examples like getting the host name and IP address.

Uploaded by

Samuel Davis
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 34

/* Write a program in java and print a massage. */ class Msg { public static void main(String args[]) { System.out.

println("Java is better than C++"); } }

Output :

Java is better then C++

/* Write a program input a number and find no. is even or odd with the help of conditional operater */ import java.io.*; class EvenOdd { public static void main(String arg[])throws IOException { int n; DataInputStream in= new DataInputStream(System.in); System.out.print("Enter a no :"); n=Integer.parseInt(in.readLine()); System.out.println((n%2==0)?"Even":"Odd");

Output : Enter a no :4 Even

/* write a program to create a class and then call its methods by its object */ class Circle { private double radius; public void setRadius(double x) { if(x <= 0) throw new IllegalArgumentException("Radius can not be zero or negative"); radius=x; } public double getRadius() { return radius; }

} class CircleTest2 { public static void main(String args[]) { Circle c1; c1 = new Circle(); c1.setRadius(-2.6); double p; p = Math.PI* 2 *c1.getRadius(); System.out.println("Peri = "+p);

} Output Peri = 16.336281798666924

/* Write a program of an applet use of font properties */

import java.awt.*; import java.applet.*; public class color extends Applet { Color textcolor; Font f=new Font("Courier",Font.BOLD +Font.ITALIC,30); String s="Colorful Applet"; String Param; public void init() { setBackground(Color.red); Param=getParameter("Mycolor"); if(Param !=null) { if(Param.equals("red"))textcolor=Color.red; if(Param.equals("green"))textcolor=Color.green; if(Param.equals("yellow"))textcolor=Color.yellow; } else textcolor=Color.blue; } public void paint(Graphics g) { g.setColor(textcolor); g.setFont(f); g.drawString(s,40,40); }

} /*<applet code="color.class" width=400 height=300> <Param name=mycolor value="blue"> </applet> */

/* write a program to create a canvas on applet

*/

import java.awt.*; import java.applet.*; public class Frame10 extends Applet { public void init() { setLayout(new FlowLayout(FlowLayout.RIGHT)); setBackground(Color.yellow); Canvas c=new Canvas(); c.setBackground(Color.blue); c.setSize(100,50); add(c); } } /* <applet code=Frame10.class width=150 height=160 > </applet> */

/* write a program in applet and use the method of applet init(), start(), stop(), destroy() */ import java.awt.*; import java.applet.*; public class MethodeTxt extends Applet { String out; public void init() { setBackground(Color.yellow); setForeground(Color.red); System.out.println("Init method"); out="init"; } public void start() { System.out.println("Start method"); out="start->"; } public void stop() { System.out.println("Stop method"); out="start->"; } public void destroy() { System.out.println("Destroy method"); out="Destroy->"; } public void paint(Graphics g) { System.out.println("Paint method"); out="paint->"; g.drawString(out,100,10); }

/*<applet code=MethodTest.class width=200 height=200 > </applet> */

Output

Output on DOS prompt

Init method Start method Paint method Stop method

/* Write a program of applet to print a massage on applet */ import java.awt.*; import java.applet.*; public class Msgs extends Applet { public void paint(Graphics g) { g.drawString("Welcome to applet",30,30); } } /*<applet code=Msgs.class width=50 height=80 > </applet> */

Output

/* write a program and set the priority of a thread

*/

class A extends Thread { public void run() { System.out.println("Thread first is started"); for(int i=1;i<=10;i++) { System.out.println("i :"+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { System.out.println("Second thread is starting"); for(int j=1;j<11;j++) { System.out.println("j :"+j); } System.out.println("Exit from B"); } } class DaemonPriority { public static void main(String arg[]) { System.out.println("Main begin"); A f=new A(); f.setPriority(10); B f1=new B(); f1.setPriority(1); f.start(); f1.start();

Output

Main begin Thread first is started i :1 Second thread is starting i :2 j :1 i :3 j :2 i :4 j :3 j :4 j :5 j :6 j :7 j :8 j :9 j :10 i :5 Exit from B i :6 i :7 i :8 i :9 i :10 Exit from A

/* To create a program call the SetDaemon() method after the thread creation and before execution is started */ class DaemonSet1 { public static void main(String { First f=new First(); if(f.isDaemon()) System.out.println("This else System.out.println("This f.setDaemon(true); if(f.isDaemon()) System.out.println("This else System.out.println("This f.setDaemon(false); f.start(); } } class First extends Thread { public void run() { System.out.println("This for(int i=1;i<=10;i++)

args[])

is Daemon thread"); is not daemon thread");

is daemon thread"); is not daeomon thread");

is the begin of thread");

System.out.println("i :"+i); System.out.println("Over first thread"); }

Output This is not daemon thread This is daemon thread This is the begin of thread i :1 i :2 i :3 i :4 i :5 i :6 i :7 i :8 i :9 i :10 Over first thread

/* Write a program of array in java in which we create a matrix and print diagonal elements from left */ class Array4 { public static void main(String args[]) { int a[][]={ {1,2,3}, {4,5,6}, {7,8,9} }; System.out.println("The actual matrix is:"); for(int i=0;i<a.length;i++) { for(int j=0;j<a.length;j++) { System.out.print("\t"+a[i][j]); } System.out.println("\t"); } System.out.println("The diagonal series is of numbers from left:"); for(int i=0;i<a.length;i++) { for(int j=0;j<a.length;j++) { if(i==j) System.out.println(a[i][j]); } } System.out.println("The diagonal series is of numbers from left:"); for(int i=0;i<a.length;i++) { for(int j=0;j<a.length;j++)

if(i<j) System.out.println(+a[i][j]);

System.out.println("The diagonal series is of numbers from left:"); for(int i=0;i<a.length;i++) { for(int j=0;j<a.length;j++) { if(i>j) System.out.print("\t"+a[i][j]); } System.out.println("\t"); } System.out.println("The diagonal series is of numbers from right:"); for(int i=0;i<a.length;i++) { for(int j=0;j<a.length;j++) { if(i+j==2) System.out.println(a[i][j]); } } }

Output The actual matrix is: 1 2 3 4 5 6 7 8 9 The diagonal series is of numbers from left:

The diagonal series is of numbers from left: 2 3 6 The diagonal series is of numbers from left: 4 7 8 The diagonal series is of numbers from right: 3 5 7

/* Write a program of Exception handling */ class ExTest3 { public static void main(String args[]) { int x,y,r; try {

} catch(ArithmeticException ex) { System.out.println("Divisor can not be zero"); } catch(RuntimeException ex) { System.out.println("I/O Error"); } System.out.println("End of main....");

x = Integer.parseInt(args[0]); y = Integer.parseInt(args[1]); r = x/y; System.out.println("Result : "+r);

Output

G:\Pro\coll\File>java ExTest3 Result : 6 End of main.... G:\Pro\coll\File>java ExTest3 Divisor can not be zero End of main.... G:\Pro\coll\File>java ExTest3 I/O Error End of main.... G:\Pro\coll\File>java ExTest3 I/O Error End of main....

12 2

12 0

12

vfhdg dfj

/* A program of String */ import static java.lang.System.*; class StrTest1 { public static void main(String args[]) { String s1 = new String("Unisoft Technologies"); String s2 = ",Dehradun"; //out.println(s1[3]); //String s3 = s1.concat(s2); String s3 = s1+s2; out.println(s1); out.println(s2); out.println(s3); }

Output

Unisoft Technologies ,Dehradun Unisoft Technologies,Dehradun

/* A program of StringBuffer and reverse the String */

import static java.lang.System.*; class BufferTest1 { public static void main(String args[]) { StringBuffer s1 = new StringBuffer("Amit Kumar Sharma"); StringBuffer s2 = s1; s1.append(",Dehradun"); out.println(s1); out.println(s2); s2.reverse(); out.println(s1); out.println(s2); }

Output Amit Kumar Sharma,Dehradun Amit Kumar Sharma,Dehradun nudarheD,amrahS ramuK timA nudarheD,amrahS ramuK timA

/* Write a program in thread use join() and Sleep method and also call second class of start() method from First class */

class Alpha extends Thread { public void run() { System.out.println("Alpha Started..."); Beta b1 = new Beta(); b1.start(); for(int i=1;i<=5;i++) { System.out.println("Alpha : "+i); try {

if(i==3) b1.join(); Thread.sleep(1000);

} catch(Exception e){} } System.out.println("Alpha Ended..."); } class Beta extends Thread { public void run() { System.out.println("Beta Started..."); for(int i=5;i>0;i--) { System.out.println("Beta : "+i); try }

{ } catch(Exception e){} } System.out.println("Beta Ended..."); } } Thread.sleep(1000);

class ThreadTest5 { public static void main(String args[])throws Exception { System.out.println("Main Started..."); Alpha a1 = new Alpha(); a1.start(); for(int i=1;i<=5;i++) { System.out.println("Main : "+i); if(i==5) a1.join(); Thread.sleep(1000); } System.out.println("Main Ended..."); } }

Output Main Started... Main : 1 Alpha Started... Alpha : 1 Beta Started... Beta : 5 Beta : 4 Main : 2 Alpha : 2 Alpha : 3 Main : 3 Beta : 3 Main : 4 Beta : 2 Beta : 1 Main : 5 Beta Ended... Alpha : 4 Alpha : 5 Alpha Ended... Main Ended...

/* Write a program use all data types */ class DataType { public static void main(String args[]) { /*boolean b=true; char ch = 'a'; ch = '\u10FA'; ch=65; System.out.println(ch); long l = 12345678324324324L; System.out.println(l); float f = 2.5F; System.out.println(f);*/ byte b=(byte)128; System.out.println(b);

Output : true A 12345678324324324 2.5 -128

/* Write a program and print host name and IP address */ import java.net.*; import java.io.*; import static java.lang.System.*; class Networking1 { public static void main(String args[])//throws Exception { try { InetAddress ia=InetAddress.getLocalHost(); out.println("Host and address"+ia); out.println("Host name:"+ia.getHostName()); String s=ia.toString(); out.println("IP address:"+s.substring(s.indexOf("/"+1))); } catch(Exception e) { } } }

Output: Host and addressabc/127.0.0.1 Host name:abc IP address:/127.0.0.1

/* Write a program enter a host name and print its IP address */ import java.net.*; import java.io.*; import static java.lang.System.*; class Networking2 { public static void main(String args[])//throws Exception { try { out.print("Enter the host name:"); String s=new DataInputStream(System.in).readLine(); InetAddress i=InetAddress.getByName(s); out.println("IP address :"+i); } catch(Exception e) { out.println("Please input correct host name"); } } }

Output : Enter the host name:abc IP address :abc/127.0.0.1

\/* Write a program of swing and print a massage on applet */ import java.awt.*; import javax.swing.*; public class Swing1 extends JApplet { public void init() { Container c=getContentPane(); JLabel jl=new JLabel("This is swing Version of a Label"); c.add(jl); } } /* <applet code=Swing.class width=200 height=200> </applet> */

/* Write a program of swing and use GridLayoyt on applet */

import java.awt.*; import javax.swing.*; public class Swing2 extends JApplet { public void init() { Container c=getContentPane(); c.setLayout(new GridLayout(3,1)); ImageIcon ii1=new ImageIcon("a.png"); JLabel ji1=new JLabel("A Left",ii1,JLabel.LEFT); JLabel ji2=new JLabel("A Center",ii1,JLabel.CENTER); JLabel ji3=new JLabel("A Right",ii1,JLabel.RIGHT); c.add(ji1); c.add(ji2); c.add(ji3);

} /* <applet code=Swing2.class width=200 height=200> </applet> */

/* Create a form and set Flow Layout and also create a button on this Form */ import java.awt.*; import java.awt.event.*; class ButtonFrame extends Frame { Button b; ButtonFrame() { setTitle("Button Frame"); FlowLayout f=new FlowLayout(); b=new Button("Exit Program"); add(b); setSize(600,400); setVisible(true); } public static void main(String args[]) { new ButtonFrame(); }

/* a program to create a form set Button in Grid Layout

*/

import java.awt.*; import java.awt.event.*; class LayoutFrame2 extends Frame { Button b1,b2,b3,b4,b5; LayoutFrame2() { setTitle("LayoutFrame1"); setLayout(new GridLayout(3,2,10,10)); b1 = new Button("Button : 1"); b2 = new Button("Button : 2"); b3 = new Button("Button : 3"); b4 = new Button("Button : 4"); b5 = new Button("Button : 5"); add(b1);add(b2);add(b3);add(b4);add(b5); setSize(600,400); setVisible(true); } public static void main(String args[]) { new LayoutFrame2(); } }

/* a program to create a form set Button in Border Layout

*/

import java.awt.*; import java.awt.event.*; class LayoutFrame3 extends Frame { Button b1,b2,b3,b4,b5; LayoutFrame3() { setTitle("Border Layout"); setLayout(new BorderLayout()); b1=new b2=new b3=new b4=new b5=new Button("Button Button("Button Button("Button Button("Button Button("Button : : : : : 1"); 2"); 3"); 4"); 5");

add(b1,"North"); add(b2,"South"); add(b3,"East"); add(b4,"West"); add(b5); setSize(600,400); setVisible(true);

} public static void main(String args[]) { new LayoutFrame3(); } }

/* A program of event handling */

import java.awt.*; import java.awt.event.*; class ColorFrame1 extends Frame implements ActionListener { Button b1,b2,b3,b4; ColorFrame1() { setTitle("Color Frame"); setLayout(new FlowLayout()); b1=new b2=new b3=new b4=new add(b1); add(b2); add(b3); add(b4); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); Button("Red"); Button("Green"); Button("Blue"); Button("Exit");

} public static void main(String args[]) { new ColorFrame1(); } public void actionPerformed(ActionEvent ae) {

setSize(600,400); setVisible(true);

if(ae.getSource()==b1) setBackground(Color.red); if(ae.getSource()==b2) setBackground(Color.green); if(ae.getSource()==b3) setBackground(Color.blue); if(ae.getSource()==b4) System.exit(0);

} }

/* Use of this

*/

import static java.lang.System.*; class Alpha { int x,y,z; Alpha(int x, int y, int z) { this.x=x; this.y=y; this.z=z; } void print() { System.out.println("x = "+x+", y = "+y+", z = "+z); } void sum() { int x; x = this.x+y+z; System.out.println("Sum = "+x); }

} class StaticTest5 { public static void main(String args[]) { Alpha a1 = new Alpha(1,2,3); Alpha a2 = new Alpha(4,5,6); Alpha a3 = new Alpha(7,8,9);

a1.sum(); a2.sum(); a3.sum(); } }

You might also like