Posts

Showing posts from 2014

Custom Exception example for BankAccount

class BankAccount {      int accountNumber;     double accountBalance;     public BankAccount(int accountNumber, double accountBalance) {         this.accountNumber = accountNumber;         this.accountBalance = accountBalance;     }     public int getAccountNumber() {         return accountNumber;     }     public double getAccountBalance() {         return accountBalance;     }           public boolean withdraw (double amount) throws WithdrawLimitException     {         if( amount > accountBalance) {                      throw new WithdrawLimitException("Withdrawing Amount is more than Balance amount.. ");                       ...

Application class for Generic Stack Implementation

class MyThread extends Thread {       MyGenericStack<Integer> iobj;     String thname;       public MyThread(MyGenericStack<Integer> iobj, String n) {         this.iobj = iobj;         thname=n;     }           public void run() {          int no=1001;        for (int i=0;i<40;i++)         {             if (thname.equals("1")) {                         if (iobj.push(new Integer(no))==true) {                     System.out.println("Thread : "+ thname + " has pushed... " + (no++) );                 }             }             else if (t...

Generic Stack Class with Synchronized methods

import java.util.ArrayList; public class MyGenericStack<E> {     E obj;         int capacity;     ArrayList<E> list;     public MyGenericStack(int c) {         capacity=c;         list= new ArrayList<E>(capacity);             }                  public synchronized boolean push(E o){             try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e);     }              if (list.size()<20) {              list.add(o);            notifyAll();            return true;        }                 return false;     }     ...

enum example 2

public class testdays {      public enum DaysofWeek {SUN,MON,TUE,WED,THU,FRI,SAT};         public static void main(String[] args) {                 DaysofWeek dw= DaysofWeek.MON;              System.out.println("Days of Week : "+ DaysofWeek.valueOf("MON") );                       System.out.println(dw);                DaysofWeek[] dws = DaysofWeek.values();                 for(DaysofWeek dd:dws)         {             System.out.println(dd);         }             } }

Static Import

import static java.lang.Math.*; import java.util.Date; import static java.lang.System.*; public class StaticImportdemo {     public static void main(String[] args) {               out.println(new Date());         out.println(sqrt(25));         out.println(PI);         out.println(abs(-245.56));         out.println(random());                 out.println(pow(2, 8));                     } }

JFrame with writing in File using FileWriter and anonymous class example

import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileWriter; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; public class FrameDemo  extends JFrame  { JButton btstore; JTextField jtf, jtf2; FileWriter fw ;     FrameDemo()     {         jtf = new JTextField(20);         jtf2 = new JTextField(10);         btstore = new JButton("Store");         setLayout(new FlowLayout());                 add(jtf); add(jtf2);         add(btstore);               btstore.addActionListener(                 new ActionListener() {           ...

enum type having private constructor

public enum SeasonTest {     WINTER(2), SUMMER(3), FALL(4), SPRING(1);       private int st;       SeasonTest(int t) { st=t; }       public int getSeason() { return st; }     public static void main(String[] args) {                 for (SeasonTest ss : SeasonTest.values()) {             System.out.println(ss + " : " + ss.getSeason());         }         SeasonTest s = SeasonTest.SPRING;         System.out.println(s.getSeason());               SeasonTest s1 = SeasonTest.SPRING;         switch(s1) {             case SPRING  : System.out.println("Spring"); break;             case SUMMER :   System.out.println("Summer"); break;       ...

Annotation

import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Date; /**  *  * @author bhavesh  */ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) public @interface NewAnnotation {         public String name();     public int myno() default 10;     //public Date mydate =new Date();                 } /**  *  * @author bhavesh  */ class A {     public void test()     {             } } class B extends A {     @Override     public void test()     {             } } // Use of annotation called NewAnnotation .... @NewAnnotation(name="ISTAR")       public class ClassAnnotationTest { ...

Enumeration enum

/**  *  * @author bhavesh  *          Season.java  */ public enum Season {         WINTER(2),MONSOON(3), SUMMER(4);         private int count;         private Season(int count)     {         this.count=count;     }         public int getMaxDays()     {         return count;     }     } /**  *  * @author bhavesh                 MainEnumTest.java  */ public class MainEnumTest {       public static void main(String[] args) {                 Season s1 = Season.MONSOON;                 s1= Season.SUMMER;         s1 = Season.valueOf("WINTER");         S...

Interface with class and interface as member

/**  *  * @author bhavesh  */ public interface MyOuterInterface {     // static class     public  class myinn {                 private int var;                 public void setVar(int v) {                         var =v;         }         public int getVar()  {  return var; }     }         // static interface     public interface myint {             }     } // Use of above interface with its inner class  example /**  *  * @author bhavesh  */ public class MainOuterClass {        public static void main(String[] args) {                  MyOuterExa...

Static and Non Static Inner class example

/**  *  * @author bhavesh  */ public class OuterClass {       private static int ox;     private int oy;     public class MyInner1     {         private int x;               public void test()         {             System.out.println(new OuterClass.MyInner2().y);                       System.out.println(oy);         }     }       public class MyInner2 {         private int y;           }       public static class Nested1 {         private int z;               public void test2() {            //return Nested2.w;            ...

Anonymous Class example

interface MyShape { static double pi = 3.14; public double area() ; public void setValue(int v); } public class AnonymousExample { public static void main(String args[]) { MyShape s = new MyShape() { int myv; public void setValue(int vv) { myv = vv; } public double area()  { return myv * myv ; } }; s.setValue(20); System.out.println(s.area()); } }

HashMap TreeMap

import java.util.*; class Student  { private int stid; private String sname; private double pert; Student(int id, String s, double p) { stid= id; sname = s; pert =p; } public int getStid() { return stid; } public String getSname() { return sname; } public double getPert() { return pert; } } public class MyMapExample { public static void main(String args[]) { Student s1 = new Student(303,"Mohin",78.90); Student s2 = new Student(203,"Dipen",88.90); Student s3 = new Student(1003,"Jay",98.90); HashMap<Integer,Student> hhmap = new HashMap<Integer,Student>(); hhmap.put(s1.getStid(),s1); hhmap.put(s2.getStid(),s2); hhmap.put(s3.getStid(),s3); Set<Integer> ttset = hhmap.keySet(); Iterator<Integer> itto = ttset.iterator(); while (itto.hasNext() ) { Integer i= itto.next(); System.out.print( i + " : "); Student s = hhmap.get(i) ; System.out.pri...

ArrayList HashSet LinkedHashSet TreeSet

import java.util.*; public class MyCollectionExample { public static void main(String args[]) { ArrayList<Integer> alist = new ArrayList<Integer>(); alist.add(301); // alist.add(new Integer(301));  autoboxing  alist.add(Integer.valueOf(301)); alist.add(3425); alist.add(123); alist.add(4560); alist.add(123); alist.add(203); alist.add(new Integer(301)); System.out.println("Array List elements : ") ; for (int i=0; i<alist.size(); i++) { System.out.println(alist.get(i)); } // Set example HashSet<Integer> hset = new HashSet<Integer>(); hset.add(301); //   autoboxing  alist.add(Integer.valueOf(301)); hset.add(3425); hset.add(123); hset.add(4560); hset.add(123); hset.add(203); hset.add(new Integer(301)); System.out.println("Set  elements : ") ; //System.out.println(hset.size()); // Print elements of Set using Iterator object // create i...

Applet with Runnable Interface

import java.applet.Applet; import java.awt.*; import java.util.Random; public class MyApplet extends Applet implements Runnable { int x=40, y=40; Color mycolor = new Color(0,255,255); public void init() { } public void start() { Thread myt = new Thread(this); myt.start(); } public void update(Graphics g) { g.setColor(mycolor); g.fillOval(x,y,60,60); } public void run() { Random myrno = new Random(); //for (int i=0; ; i++) { while (true) { try  { mycolor = new Color(myrno.nextInt(255),myrno.nextInt(255),myrno.nextInt(255)); x = myrno.nextInt(300); y = myrno.nextInt(400); Thread.sleep(1000); repaint(); } catch (Exception e) { } } } }

Frame with Menus , Dialog , Panels arranged in BorderLayout

import java.awt.*; import java.awt.event.*; /*class WindowDemo extends Window { WindowDemo(Frame myf) { super(myf); setSize(200,100); setVisible(true); setBackground(Color.red); } }*/ public class TestFrameWindow extends Frame implements ActionListener { private Button btclose,btok; private Panel pes, pws,pnr, psu,pce; private Font myf; private List mylist ; private TextArea ta; private Dialog dlg; private MenuBar mb; private Menu filem, editm, helpm, workspace; private MenuItem exitmi, openmi, openallmi; TestFrameWindow() { mb = new MenuBar(); setMenuBar(mb); filem = new Menu("File"); editm = new Menu("Edit"); helpm = new Menu("Help"); workspace = new Menu("WorkSpace.."); mb.add(filem); mb.add(editm); mb.add(helpm); exitmi = new MenuItem("Exit"); MenuShortcut shrtct = new MenuShortcut(KeyEvent.VK_X,true); exitmi.setShortcut(shrtct); exitmi.addActionL...

Various MouseEvent example in an Java Applet

import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; import java.awt.event.*; public class TestApplet extends Applet implements MouseListener { int px, py; public void init() { setBackground(Color.red); this.addMouseListener(this); } public void paint(Graphics g) { g.setColor(Color.white); g.drawString("Welcome Applet", px,py); } public void mouseExited(MouseEvent me)  { showStatus("Mouse Exited"); } public void mouseEntered(MouseEvent me)  { showStatus("Mouse Entered"); } public void mousePressed(MouseEvent me)  { showStatus("Mouse Pressed"); } public void mouseReleased(MouseEvent me)  { showStatus("Mouse Released"); } public void mouseClicked(MouseEvent me)  { px = me.getX(); py = me.getY();   repaint();   showStatus("Mouse Clicked"); } }

WindowEvent example

import java.awt.*; import java.awt.event.*; public class TestWindowEvent extends Frame implements WindowListener { public TestWindowEvent() { setSize(400,500); setVisible(true); this.addWindowListener(this); } public void windowDeactivated(WindowEvent we) { System.out.println("Deactivated" ); } public void windowActivated(WindowEvent we) { System.out.println("Activated" ); } public void windowDeiconified(WindowEvent we) { System.out.println("Deiconifid" ); } public void windowIconified(WindowEvent we) { System.out.println("Iconified" ); } public void windowClosed(WindowEvent we) { System.out.println("Closed" ); } public void windowOpened(WindowEvent we) { System.out.println("Opened" ); } public void windowClosing(WindowEvent we) { System.exit(0); } public static void main(String args[]) { new TestWindowEvent(); ...

Frame with ActionEvent

import java.awt.*; import java.awt.event.*; public class TestEventFrame extends Frame implements ActionListener { Button bt, clearbt,addbt; TextField tf1, tf2, tf3; Label lno1, lno2; public TestEventFrame() { //creating components bt = new Button("Close"); clearbt = new Button("Clear"); addbt = new Button("Add"); tf1 = new TextField(3); tf2 = new TextField(3); tf3 = new TextField(3); tf3.setEditable(false); lno1 = new Label("No1 :"); lno2 = new Label("No2 :"); //Adding Components add(lno1); add(tf1); add(lno2); add(tf2); add(tf3); add(bt); add(addbt); add(clearbt); //registering listener bt.addActionListener(this); addbt.addActionListener(this); clearbt.addActionListener(this); //setting properties of Frame setSize(400,500); setVisible(true); setTitle("First Frame"); setLayout(new FlowLayout()); } public void actionPerforme...

Simple Swing Frame with closing functionality

import javax.swing.*; public class SwingWindowEvent extends JFrame { public SwingWindowEvent() { setSize(400,500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { new SwingWindowEvent(); } }

Simple GUI AWT Frame

import java.awt.*; class MyFrame extends Frame { private Button myb; MyFrame() { myb = new Button("OK"); setLayout(new FlowLayout()); add(myb); setSize(200,300); setTitle("First Frame"); setVisible(true); } } public class MyFirstFrame  { public static void main(String args[]) { // MyFrame f = new MyFrame(); new MyFrame(); } }

Multiple Exception Example

import java.util.Scanner; public class MultipleTestException { /* exception example  */  public static void main(String args[])  {   int no1=0, no2=0 ;  try  {  no1 = Integer.parseInt(args[0]);  no2 = Integer.parseInt(args[1]);  System.out.println("After 2nd argument" );  }  catch (ArrayIndexOutOfBoundsException ae)  {   System.out.println(ae);  }  catch (NumberFormatException ne) {   System.out.println(ne);  }  finally  {     System.out.println("Resources are released");  }   System.out.println("sum  : " + (no1 + no2) );   try  {   System.out.println("Division  : " + (no1 / no2) );   }   catch (ArithmeticException ae)   {    System.out.println(ae.getMessage());    //System.out.println("Divide by Zero");   }  System.out.println("Difference  : " + (no1 - no2) ); ...

Exception Example

import java.util.Scanner; public class TestException { /* exception example  */  public static void main(String args[])  {  Scanner sin = new Scanner(System.in);  System.out.println("Enter no1 :");   int no1 = sin.nextInt();   System.out.println("Enter no2 :");   int no2 = sin.nextInt();   System.out.println("sum  : " + (no1 + no2) );   try  {   System.out.println("Division  : " + (no1 / no2) );   }   catch (ArithmeticException ae)   {    System.out.println("Divide by Zero");   }  System.out.println("Difference  : " + (no1 - no2) );  System.out.println("Multiplication  : " + (no1 * no2) );  } }