Sunday, December 16, 2012

Synchronous and Asynchronous Exceptions


     The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.

An asynchronous exception in java can occur at any point in the execution of a program.

Checked Vs Unchecked Exception

Checked Exception  in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn't see try or catch block handling a Checked Exception, it throws Compilation error. All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Unchecked Exception  in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Difference :- Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.






Saturday, December 1, 2012

System.out.println


System – is a final class and cannot be instantiated. Therefore all its members (fields and methods) will be static and we understand that it is an utility class. System class are standard input, standard output, and error output streams.

out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host.

println – Method of PrintStream class. println prints the argument passed to the standard console and a newline. 

Can a top level class be private or protected


No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

main() method in java


The main function is important function in Java programming language. 
The main method is the first method, which the Java Virtual Machine executes. When you execute a class with the Java interpreter, the run time system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application. It can be said that the main method is the entry point in the Java program and java program can't run without this method.

Public static void main (String args[])
Public is an Access Specifier.

static is a keyword which illustrates that method shared along all the classes.
void illustrates that this method will not have any return type.
main is the method which string has an argument. 
Public specifier makes the method visible outside the Class and because of the static nature of the method, JVM can call this main method without instantiating the class.

Friday, November 30, 2012

Path and Classpath


PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executable.


Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes (i.e. .class files).



Path refers to the system while classpath refers to the Developing Envornment.

We keep all "executable files"(like .exe files) and "batch files"(like .bat) in path variable. And we keep all jar files and class files in classpath variables.



For example,assume that Java is installed in C:\jdk1.5.0\ and your code is in C:\Sample\example.java, then your PATH and CLASSPATH should be set to:

PATH = C:\jdk1.5.0\bin;%PATH%

CLASSPATH = C:\Sample










Sunday, August 12, 2012

Paint in Java

Painting Editor/ Drawing Pad in JAVA


/**
 * MakeCodeEasy
 */
import java.awt.*;
import java.awt.event.*;

public class Painting implements MouseMotionListener,MouseListener
{
    Frame f;
    int x,y;
    int px;
    int py;
    int count=0;
    public Painting()
    {
   
    f=new Frame();
           f.setSize(400,400);
           f.setVisible(true);
    
               f.addMouseMotionListener(this);
               f.addMouseListener(this);
               
   
           WindowCloser wc=new WindowCloser();
          f.addWindowListener(wc);
    }
   
    public void mouseDragged(MouseEvent e1)
    {
    }
    
    public void mouseMoved(MouseEvent e2)
    {
        if(count==0)
        {
        x=e2.getX();
            y=e2.getY();
            Graphics g=f.getGraphics();
                 g.setColor(Color.blue);
                 g.drawLine(x,y,x,y);
            px=x;
                 py=y;
                 count=1;
        }
        else
        {
                 x=e2.getX();
            y=e2.getY();
            Graphics g=f.getGraphics();
                 g.setColor(Color.blue);
                 g.drawLine(px,py,x,y);
            px=x;
                 py=y;
        }
     }
    
    public void mouseClicked(MouseEvent e3)
     {
     
     }
     
     public void mouseEntered(MouseEvent e4)
     {
     }
     
     public void mouseExited(MouseEvent e5)
     {
      count=0;
     }
     
     public void mousePressed(MouseEvent e6)
     {
      count=0;
     }
     
     public void mouseReleased(MouseEvent e7)
     {
     }
     
    
    public static void main(String args[])
    {
    Painting pnt=new Painting();
    }
    
}

Output :-

    

Thursday, August 9, 2012

FileSpliter in JAVA


Divide a file into multiple parts

import java.util.*;
import java.io.*;

class Spliter
{
public static void main(String args[]) throws Exception
{
 long size;
 
 System.out.println("Enter the file name You want to spilit");
 
 Console con=System.console();
 String str=con.readLine();
 
 File f=new File(str);
 
 
  if(f.exists())
  {
  size=f.length();
  System.out.println(size+" byte");
 
  con.printf("Enter Destination FIle Size :-");
  double l=Integer.parseInt(con.readLine());
 
  int num=(int)(Math.ceil(size/l));
  System.out.println("Number of files = "+(num));
  FileInputStream fis=new FileInputStream(f);
 
 
  int ch,j=1;
  String arr[]=new String[num]; 
  for(int i=0;i<num;i++,j++)
  {
         arr[i]=j+f.getName();
         File f1=new File(arr[i]);
                  FileOutputStream fos=new FileOutputStream(f1);
          
         int k=1;
                                    label1:           
         while((ch=fis.read())!=-1)
         {
          if(k<l)
          {
              fos.write(ch);
                        k++;
                  }
                  else if(k>=l)
                  {
                  fos.write(ch);
                break label1;
                  }
             }
     fos.close();
  }
  fis.close();
 
  }
}
}

Steps :-                                                  Compile


RUN


OutPut






    Tuesday, August 7, 2012

    Calculator in JAVA


    Basic Calculator in JAVA

    /**
     * Basic Calculator
     * @author : Makecodeeasy
     */

    import java.awt.*;

    import java.awt.event.*;

    public class Calc implements ActionListener 

    {
       TextField tf;
       public Calc()
       {
        //FlowLayout fl=new FlowLayout(FlowLayout.LEFT,0,0);
       
        Font fnt=new Font("Arial",Font.BOLD,20);
       
        GridLayout gl1=new GridLayout(5,0);
       
        Frame f=new Frame();
        f.setLayout(gl1);
        f.setSize(250,250);
          WindowCloser wc=new WindowCloser();
        f.addWindowListener(wc);
        
        ScrollPane sp=new ScrollPane(ScrollPane.SCROLLBARS_NEVER);
        tf=new TextField();
        tf.setFont(fnt);
        //tf.setBackground(Color.yellow);
        sp.add(tf);
        f.add(sp);
        
        GridLayout gl2=new GridLayout(0,4);
        Panel p1=new Panel();
        p1.setLayout(gl2);
        Button b1=new Button("1");  b1.addActionListener(this);
        Button b2=new Button("2");  b2.addActionListener(this);
        Button b3=new Button("3");  b3.addActionListener(this); 
        Button b4=new Button("+");  b4.addActionListener(this);
        b1.setFont(fnt);
        b2.setFont(fnt);
        b3.setFont(fnt);
        b4.setFont(fnt);
        p1.add(b1);
        p1.add(b2);
        p1.add(b3);
        p1.add(b4);
        f.add(p1);
        
        Panel p2=new Panel();
        p2.setLayout(gl2);
        Button b5=new Button("4");   b5.addActionListener(this);
        Button b6=new Button("5");   b6.addActionListener(this);
        Button b7=new Button("6");   b7.addActionListener(this);
        Button b8=new Button("-");   b8.addActionListener(this);
        b5.setFont(fnt);
        b6.setFont(fnt);
        b7.setFont(fnt);
        b8.setFont(fnt);
        p2.add(b5);
        p2.add(b6);
        p2.add(b7);
        p2.add(b8);
        f.add(p2);
        
        Panel p3=new Panel();
        p3.setLayout(gl2);
        Button b9=new Button("7");    b9.addActionListener(this);
        Button b10=new Button("8");   b10.addActionListener(this);
        Button b11=new Button("9");   b11.addActionListener(this);
        Button b12=new Button("*");   b12.addActionListener(this);
        b9.setFont(fnt);
        b10.setFont(fnt);
        b11.setFont(fnt);
        b12.setFont(fnt);
        p3.add(b9);
        p3.add(b10);
        p3.add(b11);
        p3.add(b12);
        f.add(p3);
        
        Panel p4=new Panel();
        p4.setLayout(gl2);
        Button b13=new Button("C");    b13.addActionListener(this);
        Button b14=new Button("0");    b14.addActionListener(this);
        Button b15=new Button("/");    b15.addActionListener(this);
        Button b16=new Button("=");    b16.addActionListener(this);
        b13.setFont(fnt);
        b14.setFont(fnt);
        b15.setFont(fnt);
        b16.setFont(fnt);
        p4.add(b13);
        p4.add(b14);
        p4.add(b15);
        p4.add(b16);
        f.add(p4);
        
        f.setVisible(true);
       }
       
        public static int count=0;
         int temp;
          int temp1,sum,sub,div,mul;
        String op,result;
       public void actionPerformed(ActionEvent e)
       {
        String str=e.getActionCommand();
       

       
        if(str.equals("1"))
        {
        tf.setText("1");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
       
        }
        else if(str.equals("2"))
        {
        tf.setText("2");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("3"))
        {
        tf.setText("3");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("4"))
        {
        tf.setText("4");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("5"))
        {
        tf.setText("5");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("6"))
        {
        tf.setText("6");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("7"))
        {
        tf.setText("7");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("8"))
        {
        tf.setText("8");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("9"))
        {
        tf.setText("9");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("0"))
        {
        tf.setText("0");
        if(count==0)
        {
         temp=Integer.parseInt(str);
         count=1;
        }
        else
        {
        temp1=Integer.parseInt(str);
        count=0;
        }
        }
        else if(str.equals("+"))
        {
        tf.setText("+");
           op=str;
        }
        else if(str.equals("-"))
        {
        tf.setText("-");
        op=str;
        }
        else if(str.equals("/"))
        {
        tf.setText("/");
        op=str;
        }
        else if(str.equals("*"))
        {
        tf.setText("*");
        op=str;
        }
        else if(str.equals("="))
        {
           if(op.equals("+"))
           {
            sum=temp+temp1;
            result=sum+"";
            tf.setText(result);
            temp=sum;
            count=1;
           }
           else if(op.equals("-"))
           {
            sub=temp-temp1;
            result=sub+"";
            tf.setText(result);
            temp=sub;
            count=1;
           }
           else if(op.equals("*"))
           {
            mul=temp*temp1;
            result=mul+"";
            tf.setText(result);
            temp=mul;
            count=1;
           }
           else if(op.equals("/"))
           {
            try
            {
              div=temp/temp1;
              result=div+"";
             tf.setText(result);
             temp=div;
            count=1;
            }
            catch(Exception e1)
            {
            tf.setText("Can't divide by Zero");
            }
           
           }
        }
        else if(str.equals("C"))
        {
        tf.setText("0");
        count=1;
        }
       
       }
        
         public static void main(String args[])
         {
          Calc cal=new Calc();
         }
        
        
    }

    Output :- 


    Saturday, August 4, 2012

    Window Closing in Java AWT

    Working of close button of Awt window



    /*
     * MakeCodeEasy :- Rahul Jain
     */


    import java.awt.*;
    import java.awt.event.*;


    public class WindowCloser extends WindowAdapter
    {
        public void windowClosing(WindowEvent e)
        {
      Window w=e.getWindow();
      w.setVisible(false);
      w.dispose();           //release the memory
      System.exit(1);
        }    
    }



    Notepad (Editor) in Java

    Simple Editor by JAVA AWT

    /** 
     * MakeCodeEasy :- Rahul Jain
     */


    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;


    public class Editor implements ActionListener
    {
       Frame f;
       MenuBar mb;
       Menu m1,m2,m3;
       Label l1,l2;
       TextField t1,t2;
       Button b1,b2,b3,b4;
       MenuItem nw,op,sv,svs,ext,fnd,fndr;
       TextArea ta;
       FileDialog fd;
       String name,path,n;
       int count=0;
        Frame f2;
        boolean flag;
       
        public Editor() 
        {
        f=new Frame("Editor");
        f.setSize(500,500);
       
        WindowCloser wc=new WindowCloser();
           f.addWindowListener(wc);
       
        mb=new MenuBar();
        m1=new Menu("File");
        m2=new Menu("Tools");
        ta=new TextArea();
        f.add(ta);
       
        nw=new MenuItem("New");
        op=new MenuItem("Open");
        sv=new MenuItem("Save");
        svs=new MenuItem("Save As");
        ext=new MenuItem("Exit");
        fnd=new MenuItem("Find");
        fndr=new MenuItem("Find & Replace");
       
        
        fd=new FileDialog(f,"Save As",FileDialog.SAVE);
       
        nw.addActionListener(this);
        op.addActionListener(this);
        sv.addActionListener(this);
        svs.addActionListener(this);
        ext.addActionListener(this);
        fnd.addActionListener(this);
        fndr.addActionListener(this);
        
        m1.add(nw); 
        m1.add(op); 
        m1.add(sv);
        m1.add(svs);
        m1.addSeparator(); 
        m1.add(ext); 
       
        m2.add(fnd);
        m2.add(fndr);
       
        GridLayout gl=new GridLayout(3,0);
        f2=new Frame("Find");
        f2.setSize(300,200);
        f2.setLayout(gl);
       
        Label l1=new Label("Find");
        TextField tf=new TextField(10);
        Panel p=new Panel();
        Button b1=new Button("Find Next");
        Button b2=new Button("Close");
        b2.addActionListener(new ActionListener()
        {
        public void actionPerformed(ActionEvent ae1)
        {
        f2.setVisible(false);
        f2.dispose();
        }
        });
       
       
        p.add(b1);
        p.add(b2);
        f2.add(l1);
        f2.add(tf);
        f2.add(p);
       
       
        
        mb.add(m1);
        mb.add(m2);
        f.setMenuBar(mb);
        f.setVisible(true);
        }
        
        public void actionPerformed(ActionEvent e)
        {
        try
        {
        //String str=e.getActionCommand();
        MenuItem mi=(MenuItem)e.getSource();
       
        if(mi==nw)
        {
        ta.setText("");
        sv.setEnabled(true);
        }
       
       
        else if(mi==op)
        {
         fd=new FileDialog(f,"Open",FileDialog.LOAD);
         fd.setVisible(true);
         name=fd.getFile();
         path=fd.getDirectory();
         n=path+name+"";
             File fl=new File(path,name);
               FileInputStream fis=new FileInputStream(fl);
               int ch;
               ta.setText("");
               while((ch=fis.read())!=-1)
                {
                   ta.appendText((char)ch+"");
                }
               sv.setEnabled(true);
               fis.close();
               f.setTitle(fd.getFile()+"-Notepad");
               
          }
             
           
          
         
        else if(mi==sv) 
        {
        fd=new FileDialog(f,"Save",FileDialog.SAVE);
        if(flag==false)
        {
             fd.setVisible(true);
             name=fd.getFile();
             path=fd.getDirectory();
             String strr=ta.getText();
             File f=new File(path,name);
         //f.createNewFile();
         String str1=ta.getText();
         FileOutputStream fos=new FileOutputStream(f);
           char arr[];
         arr=strr.toCharArray();
         for(int i=0;i<arr.length;i++)
         { 
          fos.write(arr[i]);
         }
           fos.close();
        }
           else
           {
            System.out.println(n);
             /* name=fd.getFile();
              path=fd.getDirectory();
              File f=new File(path,name);*/
              String strr1=ta.getText();
              File f=new File(n);
              FileOutputStream fos=new FileOutputStream(f);
              char arr[];
          arr=strr1.toCharArray();
          for(int i=0;i<arr.length;i++)
          { 
          fos.write(arr[i]);
          }
           fos.close();
           }  
       
       
        }
        else if(mi==svs)
        {
        fd=new FileDialog(f,"Save As",FileDialog.SAVE);
        fd.setVisible(true);
        name=fd.getFile();
        path=fd.getDirectory();
        File f=new File(path,name);
        String str1=ta.getText();
        FileOutputStream fos=new FileOutputStream(f);
        char arr[];
        arr=str1.toCharArray();
        for(int i=0;i<arr.length;i++)
       
          fos.write(arr[i]);
        }
          fos.close();
        
       
       
        }
        else if(mi==ext)
        {
           f.setVisible(false);
               f.dispose();           //release the memory
               System.exit(1);
        }
        else if(mi==fnd)
        {
           f2.setVisible(true);
       
       
       
       
        }
        else if(mi==fndr)
        {
       
        }
        }
        catch(Exception ex)
        {
       
        }
             
        }
       
       public void textValueChanged(TextEvent te)
             {
            sv.setEnabled(true);
            flag=true;
             }
        
        public static void main(String args[])
        {
        Editor ed=new Editor();
        }
    }


    Compile the Program :- javac Editor.java
    Run the Program:- java Editor


    Output:- 


    Note :- In Current program close button will not work.
                For working of close button see our next post
                Window closing in Java Awt

                

    ShareThis