Core Java Java Fundamentals Program: Demonstrate Command Line arguments and count of them.
class CmdArgs1 { public static void main(String m[]) { for(String s : m) System.out.println(s); System.out.println("count of args = " + m.length); } } Program: Accept any two values from user, and make a sum of them. Use command line arguments.
class CmdArgs2 { public static void main(String ar[]) { int x,y; if(ar.length==2) { x = Integer.parseInt (ar[0]); y = Integer.parseInt (ar[1]); System.out.println ("sum of two values = " + (x + y)); } else System.out.println ("Invalid args"); } } Program: -
Accept the radius of the circle using scanner class. Calculate area and perimeter of the circle. Print results. import java.util.Scanner; class CirArea { public static static void void main(String main(String ar[]) { Scanner sr = new Scanner (System.in); double r,a,p;
System.out.println ("enter radius"); r = sr.nextDouble(); a = Math.PI * Math.pow(r, 2); p = 2 * Math.PI * r; System.out.println("Area of the circle = " + a); System.out.println("Perimeter System.out.println("Perim eter of the circle = " + p); } } Program: -
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; class ArrayEx { public static void main(String[] ar) throws IOException { int n,x[],sum=0,avg; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter size of array"); n = Integer.parseInt(br.readLine()); System.out.println("enter elements in array"); x = new int[n]; for(int i = 0;i < n;i++) { x[i] = Integer.parseInt(br.readLine()); sum += x[i]; } avg = sum / n; System.out.println("sum = " + sum + " average = " + avg); for(int m : x) System.out.print(m + "\t"); } } Program: -
System.out.println ("enter radius"); r = sr.nextDouble(); a = Math.PI * Math.pow(r, 2); p = 2 * Math.PI * r; System.out.println("Area of the circle = " + a); System.out.println("Perimeter System.out.println("Perim eter of the circle = " + p); } } Program: -
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; class ArrayEx { public static void main(String[] ar) throws IOException { int n,x[],sum=0,avg; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter size of array"); n = Integer.parseInt(br.readLine()); System.out.println("enter elements in array"); x = new int[n]; for(int i = 0;i < n;i++) { x[i] = Integer.parseInt(br.readLine()); sum += x[i]; } avg = sum / n; System.out.println("sum = " + sum + " average = " + avg); for(int m : x) System.out.print(m + "\t"); } } Program: -
class ArrayEx { public static void main(String[] m) { int x[] = {45,11,19,34,12},sum=0; {45,11,19,34,12},sum=0; double avg; for(int i = 0; i < x.length; i++) i ++) sum += x[i]; avg = (double)sum / (double)x.length; System.out.println("sum of array values = " + sum + "\naverage = " + avg); System.out.println("the array values"); for(int a : x) System.out.print(a + "\t"); } } Classes and Objects Program: -
class DataEnc { private int a=10; protected String nm = "prasad"; double pi = 3.142; 3.142; // default is public void disp() { System.out.println("a = " + a + "\nnm = " + nm + "\npi = " + pi); } } Program: class ClsObj { public static void main(String m[]) { DataEnc d = new DataEnc(); //System.out.println(d.a); System.out.println(d.nm); System.out.println(d.pi); d.disp(); } }
Program: -
import java.io.*; class ClsObj { int s,a,p; BufferedReader br; static void sop(String msg) { System.out.println(msg); } public static void main(String m[]) throws IOException { ClsObj c = new ClsObj(); c.br = new BufferedReader(new InputStreamReader(System.in)); sop("enter side of square"); c.s = Integer.parseInt(c.br.readLine()); c.a = c.s * c.s; c.p = 4 * c.s; sop("Area of the square = " + c.a); sop("Perimeter of the square = " + c.p); } } Program: import java.io.*; class ClsObj { BufferedReader br; double b,h,a; static void sop(String msg) { System.out.println(msg); } public static void main(String[] m) throws IOException { ClsObj c = new ClsObj(); c.br = new BufferedReader(new InputStreamReader(System.in)); sop("enter b,h");
c.b = Double.parseDouble(c.br.readLine()); c.h = Double.parseDouble(c.br.readLine()); c.a = 0.5 * c.b * c.h; sop("Area of the traingle = " + Math.round(c.a)); } } Program: -
import java.util.*; class ClsObj { void readInput() { sr = new Scanner(System.in); sop("enter book name and cost"); bnm = sr.nextLine(); bcst = sr.nextDouble(); } void showBookDet() { sop("Book name = " + bnm); sop("Book Cost = " + bcst); } void sop(String msg) { System.out.println(msg); } public static void main(String m[]) { ClsObj c = new ClsObj(); c.readInput(); c.showBookDet(); } String bnm; double bcst; Scanner sr; } Program: -
class ClsObj { int m;
ClsObj() { m = 20; sop("constructor executed"); } void showVal() { sop("m value = " + m); } protected void finalize() { sop("finalize method executed"); System.runFinalization(); } void sop(String msg) { System.out.println(msg); } public static void main(String m[]) { ClsObj c = new ClsObj(); c.showVal(); c.finalize(); } } Program: -
class ClsObj { String nm; ClsObj(String nm) { this.nm = nm; } void showVal() { sop("entered name = " + nm); } void sop(String msg) { System.out.println(msg); } public static void main(String m[]) { ClsObj c = new ClsObj("prasad"); c.showVal(); } } Program: -
import java.io.*; class ClsObj { int n; ClsObj(int n) { this.n = n; } void findEveOdd() { if(n%2==0) sop(n + " even number"); else sop(n + " odd number"); } void sop(String msg) { System.out.println(msg); } public static void main(String ... m) throws IOException{ DataInputStream ds = new DataInputStream(System.in); System.out.println("enter number"); ClsObj c = new ClsObj(Integer.parseInt(ds.readLine())); c.findEveOdd(); } }
Strings Program: -
class StrEx { String s1,s2; void demoStrings() { s1 = "hello"; // primitive type s2 = new String("India"); //non-primitive type
sop("s1 string = " + s1 + " size of string = " + s1.length()); sop("s2 string = " + s2 + " size of string = " + s2.length()); } void sop(String s) { System.out.println(s); } public static void main(String ... ar) { (new StrEx()).demoStrings(); } } Program: -
import java.io.*; class StrEx { String s; DataInputStream ds; void getData() throws IOException { ds = new DataInputStream(System.in); sop("enter one string\n"); s = ds.readLine(); } void printPat() { for(int i=0;i
Program: -
class StrEx { StringBuffer sb; void demoStrings() { sb = new StringBuffer("Welcome"); sop(sb); sb.append(" India"); sop(sb); sb.insert(7," to"); sop(sb); sop(sb.reverse()); } void sop(Object s) { System.out.println(s); } public static void main(String ... ar) { (new StrEx()).demoStrings(); } } Program: -
class StrEx { StringBuilder sb; void demoStrings() { sb = new StringBuilder("Welcome"); sop(sb); sb.append(" India"); sop(sb); sb.insert(7," to"); sop(sb); sop(sb.reverse()); }
void sop(Object s) { System.out.println(s); } public static void main(String ... ar) { (new StrEx()).demoStrings(); } } Program: -
import java.util.*; class StrEx { String s; StringTokenizer stk; void demoStrings() { s = "empno$ename$sal;\n1001;rama rao@10000"; stk = new StringTokenizer(s,"@;$"); while(stk.hasMoreTokens()) sop(stk.nextToken() + " "); } void sop(String s) { System.out.print(s); } public static void main(String ... ar) { (new StrEx()).demoStrings(); } }
Inheritance Program: -
class SupCls {
//overriden method void display() { System.out.println("display method from supcls"); } } class InhEx extends SupCls { //overrides method void display() { System.out.println("display method from inhex"); } public static void main(String...m) { InhEx h = new InhEx(); h.display(); } } Program: -
class SupCls { //overriden method void display() { System.out.println("display method from supcls"); } } class InhEx extends SupCls { //overrides method void display() { super.display(); System.out.println("display method from inhex"); } public static void main(String...m) { InhEx h = new InhEx(); h.display(); } } Program: -
class SupCls { SupCls(String s) { System.out.println("supcls constructor\nname = " + s); } } class InhEx extends SupCls { InhEx(String nm) { super(nm); System.out.println("inhex constructor"); } public static void main(String...m) { new InhEx("Prasad"); } } Program: -
abstract class AbsCls { abstract void print(String s) ; } class InhEx extends AbsCls { void print(String s) { System.out.println("in " + s + " last 3 chars = " + s.substring(s.length()-3)); } public static void main(String...m) { (new InhEx()).print("welcome"); } } Program: -
final class FinCls { final void print() { System.out.println("fincls print method"); } } class InhEx extends FinCls {
void print() { System.out.println("inhex print method "); } public static void main(String...m) { final int a = 34; (new InhEx()).print(); a = 10; } } Program: -
interface Intf1 { void abc1(); } interface Intf2 { void abc2(); } class Cls { void print() { System.out.println("cls print method"); } } class InhEx extends Cls implements Intf1,Intf2 { public void abc1() { System.out.println("Intf1 abc1 method "); } public void abc2() { System.out.println("Intf2 abc2 method "); } public static void main(String...m) { InhEx h = new InhEx(); h.abc1(); h.abc2(); h.print(); } } PolyMorphism
Program: -
import java.util.*; class PolyEx { double a; void area(double r) { a = Math.PI * Math.pow(r,2); } void area(double l,double b) { a = l * b; } String showRst(String shp) { return shp + " area = " + a; } void sop(String msg) { System.out.println(msg); } public static void main(String[] ar) { Scanner sr = new Scanner(System.in); PolyEx p = new PolyEx(); p.sop("Enter radius"); p.area(sr.nextDouble()); p.sop(p.showRst("Circle")); p.sop("enter l and b"); p.area(sr.nextDouble(),sr.nextDouble(),56); p.sop(p.showRst("Rectangle")); } } Program: -
import java.util.*; class SupCls { protected String rst; void mtdOvd(String s1,String s2){ s1 = s1.concat(" ").concat(s2); rst = s1; }
} class PolyEx extends SupCls { void mtdOvd(int r) { if(r >= 0) rst = r + " is positive number"; else rst = r + " is negitive number"; } void showRst() { sop(rst); } void sop(String msg) { System.out.println(msg); } public static void main(String[] ar) { Scanner sr = new Scanner(System.in); PolyEx p = new PolyEx(); p.sop("Enter 2 strings"); p.mtdOvd(sr.nextLine(),sr.nextLine()); p.showRst(); p.sop("enter one number"); p.mtdOvd(sr.nextInt()); p.showRst(); } } Program: -
import java.util.*; class PolyEx { String rst; int n1,r,arm; PolyEx(int n) { arm = 0; n1 = n; while(n1 > 0) { r = n1 % 10;
arm += Math.pow(r,3); n1 /= 10; } if(n == arm) rst = n + " armstrong"; else rst = n + " not armstrong"; } PolyEx(double x,double y) { rst = "The division of two values = " + (x / y); } void showRst() { sop(rst); } static void sop(String msg) { System.out.println(msg); } public static void main(String[] ar) { Scanner sr = new Scanner(System.in); sop("enter two values"); PolyEx p = new PolyEx(sr.nextDouble(),sr.nextDouble()); p.showRst(); sop("enter one number"); p = new PolyEx(sr.nextInt()); p.showRst(); } }
Exception Handlings Program: -
import java.io.*; class TryCatchEx { int x[] = {34,11,28,19,10},idx; BufferedReader br; void demoTryCatch() { try {
br = new BufferedReader(new InputStreamReader(System.in)); sop("enter index of array"); idx = Integer.parseInt(br.readLine()); sop("x[" + idx + "] = " + x[idx]); }catch(IOException e1) { sop("Error1 = " + e1); }catch(IndexOutOfBoundsException e2) { sop("index is out of range\n" + e2.getMessage()); }catch(NumberFormatException e3) { sop("enter proper input"); e3.printStackTrace(); }catch(Exception e4) { sop("Error4 = " + e4); }finally { sop("finally is executed"); } } void sop(String s) { System.out.println(s); } public static void main(String[] ar) { (new TryCatchEx()).demoTryCatch(); } } Program: -
import java.io.*; class TryCatchEx { String nm; BufferedReader br=null; void demoTryCatch() { try { //br = new BufferedReader(new InputStreamReader(System.in)); sop("enter name"); nm = br.readLine(); sop("ur name = " + nm); }catch(NullPointerException e1) { sop("may be instance not created check ur self");
}catch(Exception e2) { sop("Error2 = " + e2); } } void sop(String s) { System.out.println(s); } public static void main(String[] ar) { (new TryCatchEx()).demoTryCatch(); } } Program: -
import java.io.*; class NameException extends Exception { String nm; NameException(String nm) { this.nm = nm; } public String toString() { if(nm.equals("venu") || nm.equals("srinu")) return "Mr " + nm + " ur the best friend for me"; else return "Mr " + nm + " ur the not a best friend for me"; } } class TryCatchEx { String nm; BufferedReader br; void demoUsrDefException() throws NameException,Exception { br = new BufferedReader(new InputStreamReader(System.in)); sop("enter name"); nm = br.readLine(); throw new NameException(nm); } void sop(String s) { System.out.println(s); } public static void main(String[] ar)
throws NameException,Exception{ (new TryCatchEx()).demoUsrDefException(); } } Packages Program: -
package mypack; import java.util.*; public class Inputs { Scanner sr; public Inputs() { sr = new Scanner(System.in); } public int readInt() { return sr.nextInt(); } public String readStr() { return sr.nextLine(); } public void sop(String s) { System.out.println(s); } } Program: -
import mypack.Inputs; class TestPack { String nm; Inputs inp; void demoUsrPack() { inp = new Inputs();
inp.sop("enter one string\n"); nm = inp.readStr(); for(int i=nm.length()-1;i>=0;i--) inp.sop(nm.charAt(i) + ""); } public static void main(String...ar) { (new TestPack()).demoUsrPack(); } } MultiThreading Program: -
class Thread1 extends Thread { Thread1() { start(); } public void run() { try { for(int i = 1;i<=5;i++) { System.out.println("thread1 : " + i); sleep(1000); } }catch(InterruptedException e) { } } } class Thread2 implements Runnable{ Thread t; Thread2() { t = new Thread(this); t.start(); } public void run() { try { for(int j = 1;j<=5;j++) { System.out.println("thread2 : " + j); t.sleep(500); } }catch(InterruptedException e) {
} } } class ThreadEx { public static void main(String[] m) { new Thread1(); new Thread2(); } } Program: -
class Thread1 extends Thread { Thread2 t; Thread1(Thread2 t) { this.t = t; start(); } public synchronized void run() { try { for(int i = 1;i<=5;i++) { System.out.println("thread1 : " + i); } t.notify(); }catch(Exception e) { } } } class Thread2 extends Thread{ Thread2() { start(); } public synchronized void run() { try { wait(2); for(int j = 1;j<=5;j++) System.out.println("thread2 : " + j); }catch(InterruptedException e) { } }
} class ThreadEx { public synchronized static void main(String[] m) { new Thread1( new Thread2()); } } Program: -
class ThreadEx { Thread t; void demoPriority() { t = Thread.currentThread(); sop("Current thread info = " + t); sop("Thread name = " + t.getName()); sop("Thread priority = " + t.getPriority()); t.setName("prasad"); t.setPriority(9); sop("Current thread info = " + t); } void sop(Object o) { System.out.println(o); } public static void main(String[] m) { (new ThreadEx()).demoPriority(); } } Collections Program1: -
import java.util.*; class CollEx { Vector v; Enumeration e; void demoVect() {
v = new Vector(); v.add(new Integer(100)); v.add(new String("hello")); sop("capacity = " + v.capacity() + "\ncount of ele = " + v.size()); for(int i=0;i
import java.util.*; class CollEx { Hashtable hs; void demoHashtable() { hs = new Hashtable(); hs.put("unm","scott"); hs.put("pwd","tiger"); sop("hashtable instance = " + hs); sop("count elements = " + hs.size()); Collection c = hs.values(); Object data[] = c.toArray(); //this method assigning a values in array object for(int i=0;i
} void sop(Object o) { System.out.println(o); } public static void main(String ar[]) { (new CollEx()).demoHashtable(); } } Program : -
import java.util.*; class CollEx { Stack s; void demoStack() { s = new Stack(); s.push(10); s.push(20); s.push(30); sop("elements in stack" + s); s.pop(); sop("after pop on element in stack is " + s); } void sop(String s) { System.out.println(s); } public static void main(String...p) { (new CollEx()).demoStack(); } } ABSTRACT WINDOW TOOL KIT Program: -
import java.awt.*;
import java.applet.*; public class AwtEx1 extends Applet { void sop(String s) { System.out.println(s); } public void init() { sop("init fired"); } public void start() { sop("start fired"); } public void paint(Graphics g) { sop("paint fired"); g.drawString("Sample Applet",50,80); } public void stop() { sop("stop fired"); } public void destroy() { sop("destroy fired"); } }/*
*/ Html Code:
Program: -
import java.awt.*; import java.applet.*;
public class AwtEx1 extends Applet { public void paint(Graphics g) { g.drawLine(10,150,150,10); g.drawOval(71,60,100,100); g.fillRect(80,82,83,50); } }/*
*/ Program 3: import java.awt.*; import java.applet.*; public class AwtEx1 extends Applet { Font f; Color c1,c2; public void start() { f = new Font("Courier New",Font.BOLD,22); c1 = new Color(230); c2 = new Color(100,120,80); setBackground(c2); } public void paint(Graphics g) { g.setColor(Color.yellow); g.fillOval(50,60,100,50); g.setFont(f); g.setColor(c1); g.drawString("Oval Shape",50,140); } }/*
*/ Program: -
import java.awt.*; import java.applet.*; public class AwtEx1 extends Applet { Image img; public void start() {
img = getImage(getCodeBase(),"drawing.gif"); } public void paint(Graphics g) { g.drawImage(img,10,10,this); } }/*
*/ Program: -
import java.awt.*; import java.applet.*; import java.awt.event.*; public class AwtEx1 extends Applet implements MouseMotionListener { String msg=""; public void init() { addMouseMotionListener(this); } public void mouseMoved(MouseEvent e1) { msg = "mouse moved : " + e1.getX() + "-" + e1.getY(); repaint(); } public void mouseDragged(MouseEvent e2) { msg = "mouse dragged "; repaint(); } public void paint(Graphics g) { g.setFont(new Font("Comic Sans Ms",Font.ITALIC,25)); g.drawString(msg,90,100); } }/*
*/ Program: -
import java.awt.*;
import java.applet.*; import java.awt.event.*; public class AwtEx extends Applet implements MouseMotionListener{ int x,y; String msg="",msg1=""; public void init() { addMouseMotionListener(this); } public void mouseMoved(MouseEvent me1) { msg1="Prasad"; x = me1.getX(); y = me1.getY(); msg = x + "-" + y; repaint(); } public void mouseDragged(MouseEvent me2) { msg = "Mouse dragged"; msg1=""; repaint(); } public void paint(Graphics g) { g.setFont(new Font("Arial",Font.BOLD,25)); g.drawString(msg1,x,y); g.drawString(msg,180,100); } }/*
*/
Program: -
import java.awt.*; import java.applet.*; import java.awt.event.*; public class AwtEx1 extends Applet implements ActionListener {
String msg=""; Label l1,l2; TextField t1,t2; Button b1,b2; public void init() { l1 = new Label("User Name : "); l2 = new Label("Password : "); t1 = new TextField(20); t2 = new TextField(20); t2.setEchoChar('*'); b1 = new Button("Login"); b2 = new Button("Clear"); b1.addActionListener(this); b2.addActionListener(this); add(l1);add(t1);add(l2);add(t2); add(b1);add(b2); } public void actionPerformed(ActionEvent e) { if(e.getSource()==b1) { if(t1.getText().equals("mss") && t2.getText().equals("vizag")) msg = "Login Success"; else msg = "Invalid Login"; }else if(e.getSource() == b2) { t1.setText(""); t2.setText(""); t1.requestFocus(); msg=""; } repaint(); } public void paint(Graphics g) { g.setFont(new Font("Comic Sans Ms",Font.BOLD,25)); g.drawString(msg,70,130); } }/*
*/ Program: -
import java.awt.*; import java.applet.*; import java.awt.event.*; public class AwtEx1 extends Applet implements ItemListener { String msg1="",msg2="Ur selected Fe-Male"; Checkbox r1,r2,chk; CheckboxGroup g1; public void init() { g1 = new CheckboxGroup(); r1 = new Checkbox("Cash",g1,false); r2 = new Checkbox("Card",g1,false); chk = new Checkbox("Male / Fe-Male"); r1.addItemListener(this); r2.addItemListener(this); chk.addItemListener(this); add(r1);add(r2);add(chk); } public void itemStateChanged(ItemEvent ie) { if(ie.getSource()==r1) { msg1 = "Ur selected Cash"; }else if(ie.getSource() == r2) { msg1 = "Ur selected Card"; }else if(ie.getSource() == chk) { if(chk.getState() == true) msg2 = "Ur selected Male"; else msg2 = "Ur selected Fe-Male"; } repaint(); } public void paint(Graphics g) { g.setFont(new Font("Comic Sans Ms",Font.BOLD,25)); g.drawString(msg1,70,90); g.drawString(msg2,70,120); } }/*
*/
Program: -
import java.awt.*; import java.applet.*; import java.awt.event.*; public class AwtEx1 extends Applet implements ItemListener { Label l; Choice ch; List lst; public void init() { l = new Label("Choose City : "); ch = new Choice(); ch.addItem("Hyderabad"); ch.addItem("Vijaywada"); ch.addItem("Visakhapatnam"); ch.addItemListener(this); lst = new List(5,true); add(l);add(ch);add(lst); } public void itemStateChanged(ItemEvent ie) { lst.addItem(ch.getSelectedItem()); } }/*
*/ IOStreams: Program: import java.io.*; class IOEx { File f; void demoFile() { f = new File("c:/sample.txt");
if(f.exists()) { sop("is it writable = " + (f.canWrite()?"yes":"no")); sop("size of file = " + f.length() + " bytes"); }else sop("file or dir not found"); } void sop(String s) { System.out.println(s); } public static void main(String...m) { (new IOEx()).demoFile(); } } Program: -
import java.io.*; class IOEx { FileInputStream fis; FileOutputStream fos; byte b[]; int i; void demoFileIOStream() throws IOException { b = new byte[500]; sop("enter info to stop $ symbol"); for(i=0;i
sop("file created and reading info"); fis = new FileInputStream("c:/kingdom.txt"); while((i=fis.read())!=-1) System.out.print((char)i); fis.close(); } void sop(String s) { System.out.println(s); } public static void main(String...m) throws IOException{ (new IOEx()).demoFileIOStream(); } } Program: -
import java.io.*; class IOEx { RandomAccessFile raf; byte b[]; int i; void demoRndAcc() throws IOException { b = new byte[500]; sop("enter info to stop $ symbol"); for(i=0;i