Sunday, 6 July 2014

Excetion Propagation (Stack Trace)

class Propagation
{
    void show() throws Exception
    {
        int a = 10/0;            //    unchecked exception
    }
    void disp() throws Exception
    {
        show();
    }
    public static void main(String...s)
    {
        Propagation ob = new Propagation();                // this concept is known as object propagation.
        try
        {
            ob.disp();
        }
        catch(Exception e)
        {
            System.out.println(e);
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }
}

Printing a Circular Matrix(Spiral Matrix)

import java.io.*;
class Circular
    {
        public static void main(String args[])throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the number of elements : ");
            int n=Integer.parseInt(br.readLine());

            int A[][]=new int[n][n];
            int k=1, c1=0, c2=n-1, r1=0, r2=n-1;

            while(k<=n*n)
                {
                    for(int i=c1;i<=c2;i++)
                    {
                            A[r1][i]=k++;
                    }

                    for(int j=r1+1;j<=r2;j++)
                    {
                            A[j][c2]=k++;
                    }

                    for(int i=c2-1;i>=c1;i--)
                    {
                            A[r2][i]=k++;
                    }

                    for(int j=r2-1;j>=r1+1;j--)
                    {
                            A[j][c1]=k++;
                    }

                 c1++;
                 c2--;
                 r1++;
                 r2--;
                }

            System.out.println("The Circular Matrix is:");
            for(int i=0;i<n;i++)
                {
                    for(int j=0;j<n;j++)
                        {
                                System.out.print(A[i][j]+ "\t");
                        }
                     System.out.println();
                }
        }
}

Printing boundary of a matrix

import java.io.*;

class boundary
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int r,c;
        System.out.println("Enter row:");
        r=Integer.parseInt(br.readLine());
        System.out.println("Enter column:");
        c=Integer.parseInt(br.readLine());
        int[][] ar=new int[r][c];
        System.out.println("Enter value in array:");
        for(int i=0; i<r; i++)
        {
            for(int j=0; j<r; j++)
            {
                ar[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0; i<r; i++)
        {
            for(int j=0; j<r; j++)
            {
                System.out.print(ar[i][j] +" ");
            }
               System.out.println("\n");
        }
        for(int i=0; i<r; i++)
        {
            for(int j=0; j<r; j++)
            {
                if(i==0||j==0)
                {
                    System.out.print(ar[i][j] +"  ");
                }
                else if(i==r-1 || j==c-1)
                {

                    System.out.print(ar[i][j] +"  ");
                }
                else
                {
                    System.out.print("\t\t");
                }
            }System.out.println();
        }
    }
}

Tuesday, 10 June 2014

Sorting A 2D matrix.

import java.lang.*;
import java.io.*;
class Matrixkr
{

public static void main(String args[])    throws IOException
{
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);

int temp=0;
System.out.println("enter no of rows");
int r=Integer.parseInt(br.readLine());
System.out.println("enter no of columns");
int c=Integer.parseInt(br.readLine());
int ar[][]=new int[r][c];
System.out.println("enter the elements");
       for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
    ar[i][j]=Integer.parseInt(br.readLine());
}
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
    System.out.print(ar[i][j]+" ");
}
System.out.println();
}

for(int x=0;x<r;x++)
{
for(int y=0;y<c;y++)
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(ar[i][j]>ar[x][y])
{
temp=ar[x][y];
ar[x][y]=ar[i][j];
ar[i][j]=temp;
}

}

}

}

}
System.out.println("after sorting");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(ar[i][j]+" ");
}
System.out.println();
}
}
}




Printing Pascal Triangle.

import java.util.Scanner;
class Pascal
{
static int factorial(int n)
{
  int sum = n;
  for(int k=n-1;k>=1;k--)
    sum*=k;
  if(sum!=0)
    return sum;
  else
    return 1;
}
public static void main(String...args)
{
  int s,lines;
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter no of lines:");
  lines = sc.nextInt();
  for(int i=0;i<lines;i++)
  {
    for(int j=lines;j>i;j--)
      System.out.print(" ");
    for(int k=0;k<=i;k++)
    {
      s = factorial(i)/(factorial(k)*factorial(i-k));
      System.out.print(s+" ");
    }
    System.out.println();
  }
}
}

Small example of Interface.

interface A
{
int a=10;
void show();
}
class Interface implements A
{
public void show()
{
System.out.println("Show in class");
}
public static void main(String...args)
{
A i = new Interface();
i.show();
}
}

Example to prove that static each class object has the same static member(single copy of static member is maintained).

class Diff
{
static int m = 0;
int n = 0;
Diff()
{
  m = m+1;
  n = 10;
  }
public static void main(String...args)
{
  Diff ob1 = new Diff();
Diff ob2 = new Diff();
  System.out.println("Non static 1:"+ob1.m);
  System.out.println("Non static 2:"+ob2.m);
  System.out.println("Static 1:"+ob1.n);
  System.out.println("Static 2:"+ob1.n);
}
}

Inheriting Abstract Class and overriding their methods.

abstract class Player
{
abstract void play();
abstract void stop();
abstract void pause();
}
class GenericPlayer extends Player
{
void play()
{
  System.out.println("Generic: Can play .avi .dat files");
  }
void stop()
{
  System.out.println("Music stopped");
}
void pause()
{
  System.out.println("Music paused");
}
}
class DvdPlayer2 extends GenericPlayer
{
  void play()
{
  System.out.println("Dvd Player: Can play .avi .dat .mpg files");
}
public static void main(String...srgs)
{
Player pl = new DvdPlayer();
  Player pl1 = new GenericPlayer();
  pl.play();
  pl1.play();
}
}

Calculator By inheritance.

import java.util.Scanner;
import java.lang.Math;
class Calc
{
static int a,b;
static Scanner sc = new Scanner(System.in);
//////////////////////////////////////////
static void input1()
{
  System.out.println("Enter a no:");
  a = sc.nextInt();
  System.out.println("Enter a no:");
  b = sc.nextInt();
}
static void input2()
{
  System.out.println("Enter a no:");
  a = sc.nextInt();
}
/////////////////////////////////////////
static int add(int a,int b)
{
  return a+b;
}
static int sub(int a,int b)
{
return a-b;
}
static int mul(int a,int b)
  {
  return a*b;
}
static int div(int a,int b)
{
  return a/b;
}
static int sqr(int a)
{
  return a*a;
}
static double sqroot(double a)
{
  return Math.sqrt(a);
}
}
class Calculator extends Calc
{
static double c;
static void input3()
{
  System.out.println("Enter a no:");
c = sc.nextDouble();
}
  static double sine(double d)
{
  return Math.sin(Math.toRadians(d));
}
static double cosine(double d)
{
  return Math.cos(Math.toRadians(d));
}
static double tann(double d)
{
  return Math.tan(Math.toRadians(d));
  }
static double asine(double d)
{
    return Math.asin(d);
}
static double acosine(double d)
{
return Math.acos(d);
}
static double atann(double d)
{
  return Math.atan(d);
}
public static void main(String...args)
  {
  System.out.println("----Menu----");
  System.out.println("1.Add \n2.Sub \n3.Mul \n4.Div \n5.Sqr \n6.Sqr Root \n7.Sin \t\t8.Cos \t\t9.Tan \n10.Asin \t11.Acos \t12.Atan");
    int m = sc.nextInt();
  switch(m)
    {
  case 1:
    input1();
    System.out.println("\n"+a+"+"+b+"="+add(a,b));
    break;
  case 2:
    input1();
    System.out.println("\n"+a+"-"+b+"="+sub(a,b));
    break;
  case 3:
    input1();
    System.out.println("\n"+a+"*"+b+"="+mul(a,b));
    break;
  case 4:
    input1();
    System.out.println("\n"+a+"/"+b+"="+div(a,b));
    break;
  case 5:
      input2();
    System.out.println("\nSquare of "+a+"="+sqr(a));
    break;
  case 6:
    input2();
    System.out.println("\nSquare root of "+a+"="+sqroot(a));
    break;
    case 7:
    input3();
    System.out.println("\nSine("+c+")="+sine(c));
    break;
  case 8:
    input3();
    System.out.println("\nCos("+c+")="+cosine(c));
    break;
  case 9:
    input3();
    System.out.println("\nTan("+c+")="+tann(c));
    break;
  case 10:
    input3();
    System.out.println("\nAsin("+c+")="+asine(c));
    break;
  case 11:
    input3();
    System.out.println("\nACos("+c+")="+acosine(c));
    break;
  case 12:
    input3();
    System.out.println("\nAtan("+c+")="+atann(c));
    break;
    default:
    System.out.println("Wrong Entry");
}
}
}

Function Overloading

class Add
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
int add(int a,int b,int c,int d)
{
return a+b+c+d;
}
public static void main(String...args)
{
Add obj = new Add();
System.out.println(obj.add(1,2));
System.out.println(obj.add(1,2,3));
System.out.println(obj.add(1,2,3,4));
}
}

Find area by taking their dimensions through command line argument.

class Area
{
      final double pi=3.14;
      void areaOfCircle(int r)
      {
          double area1=pi*r*r;
          System.out.println("area of circle="+area1);
       }
      void areaOfCylinder(int r,int h)
        {
          double area2=2*pi*r*(r+h);
          System.out.println("area of cylinder="+area2);
        }
    public static void main(String args[])
    {
int r1=Integer.parseInt(args[0]);
int h1=Integer.parseInt(args[1]);
           Area a = new Area();
           a.areaOfCircle(r1);
           a.areaOfCylinder(r1,h1);
    }
}

Find reverse of a number

import java.util.Scanner;
class Reverse
{
         int num;
        void getReverse(int a)
         {
                 num = a;
                 int r=0;
                 int reverse=0;
                 do
                 {
                            r=num%10;
                            reverse=reverse*10+r;
                            num=num/10;
                   }while(num>0);
                    System.out.println("Reverse= "+reverse);
           }
          public static void main(String args[])
           {
                 Scanner sc = new Scanner(System.in);
                 Reverse ob = new Reverse();
                 System.out.println("Enter a no: ");
                 int n = sc.nextInt();
                  ob.getReverse(n);
           }
}

Pattern Printing

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
---------------------------------------
public class Pattern
{
public static void main( String arg[])
{
int ck=0,c=2;
        while(c>0)
{
        if(ck==0)
{
            for(int i=1,r=5;i<=5;i++,r--)
{
            for(int j=1;j<=r;j++)
{
                System.out.print(j + " ");
            }
            System.out.println();
}
            ck++;
        }
else
{
            for(int i=2;i<=5;i++)
{
            for(int j=1;j<=i;j++)
{
                System.out.print(j + " ");
       }
            System.out.println();
        }
        }
        c--;
      }

}
}

Constructor Chaining.

class Const
{
Const()
{
  System.out.println("This is Default Const of class");
}
Const(int a)
{
  this();
  System.out.println("This is Param1 Const of class");
}
Const(int a,int b,int c)
{
  this(c);
  System.out.println("This is Param2 Const of class");
}
public static void main(String []ars)
{
  Const obj = new Const(4,5,8);
}
}

Use of SUPER keyword to invoke the constructor of parent class.

class Parent
{
int a;
Parent()
{
  System.out.println("This is Parent default constructor");
}
Parent(int x)
{
  a = x;
  System.out.println("This is Parent param constructor");
}
}
class Super extends Parent
{
int b;
Super()
{
  System.out.println("This is Super(child) Default constructor");
  }
Super(int z)
{
  super(z); //must be the first line of this constructor..
  System.out.println("This is Super(child) param constructor");
}
public static void main(String []ars)
{
  Super obj = new Super(8);
  Super obj1 = new Super();
  }
}

Print first 10 numbers from fibonacci series.

class Fibbonaci
{
  public static void main(String [] args)
  {
  int a = 0;
int b = 1, temp;
  System.out.print(a + ", " + b + ", ");
  for(int i = 1; i < 10; i++)
  {
    temp = b;
    b = a + b;
    a = temp;
    System.out.print(b + ", ");
  }
}
}

Factorial using recursion.

import java.util.Scanner;
class Factorial
{
static int fact(int num)
{
  if(num == 0)
  return 1;
  else
      return(num * fact(num-1));
}
public static void main(String [] args)
{
  System.out.println("Enter the number: ");
  Scanner sc = new Scanner(System.in);
  int inp = sc.nextInt();
  int ans = fact(inp);
  System.out.println("Factoral: "+ans);
}
}

Program to find first 5 Armstrong Numbers.

class Armstrong
{
public static void main(String []args)
  {
  int k = 0,temp=0,sum=0,i=0;
  while(k<5)
  {
    i = ++temp;
    sum = 0;
    temp = i;
    while(i>0)
    {
      sum = sum+((i%10)*(i%10)*(i%10));
      i=i/10;
    }
    if(temp == sum)
    {
      System.out.println("Armstrong"+(k+1)+"="+temp);
      k++;
    }
  }
}
}

Find whether a number is Prime or not.

import java.util.*;
class Prime
{
  public static void main(String []args)
  {
    int no=0,k=0;
Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  no = sc.nextInt();
  for(int i=2;i<=no/2;i++)
  {
    if(no%i==0)
    {
      k=1;
      break;
    }
    }
  if(k==0)
    System.out.println("It is Prime");
  else
    System.out.println("It is not prime");
}
}

Finding Grades of Students by after taking input from user.

import java.util.*;
class Grade
{
  public static void main(String []args)
{
  int no;
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter Marks[>=0 and <=100]:");
  no = sc.nextInt();
  System.out.println("Grade:");
  if(no<40)
    System.out.println("F");
  else if(no>=40 && no<60)
    System.out.println("C");
  else if(no>=60 && no<80)
    System.out.println("B");
  else if(no>=80 && no<=100)
    System.out.println("A");      //highest
}
}

Using Scanner class to take input from user and find Greater of two number using Ternary Operator.

import java.util.Scanner;
class Find
{
public static void main(String []args)
{
  Scanner sc = new Scanner(System.in);
  int i,j;
  System.out.println("Enter two nos:");
  i = sc.nextInt();
  j = sc.nextInt();
  System.out.println("Largest:"+((i>j)?i:j));
}
}

Dynamic Dispatch

class Base
{
  void show()
{
  System.out.println("This is Base Show");
}
}
class Dynamic extends Base
{
void show()
{
  System.out.println("This is Derived Show");
}
void disp()
  {
  System.out.println("This is Derived Disp");
}
public static void main(String []args)
{
  Base b = new Dynamic();
  b.show(); //storing reference of object of derived class in base class creates dynamic disp.
}
}

Use Of FINAL keyword

class Final
{
  final int a = 5;
public static void main(String [] args)
  {
  final int c; //makes c constant variable
  c = 10;
  Final obj = new Final();
  System.out.println(obj.a);
  }
}

Inheritance Example

class A
{
  int a = 10;
void show()
{
  System.out.println("Base class Var="+a);
}
}
class Inherit
{
int a = 20;
  void show()
{
  System.out.println("Inheriting class Var="+a);
}
public static void main(String []args)
{
  Inherit ob = new Inherit();
  ob.show();
}
}

Function Overloading

class Overload
{
  static void show(int a)
{
  System.out.println("Overloaded int A="+a);
}
static void show(float a)
{
  System.out.println("Overloaded Float A="+a);
}
public static void main(String []args)
{
  show(4);            //No need to call by object as method is static
  show(5.0f);
  }
}

This & Super - Use

class A
{
int a = 10;
}
class ThisSup extends A
{
int a = 20;
void show()
  {
    System.out.println("Base class Var="+super.a);
  }
  void disp()
{
  int a=99;
  System.out.println("Local Var="+a);
  System.out.println("This class Var="+this.a);
}
public static void main(String []args)
  {
  ThisSup ob = new ThisSup();
  ob.show();   ////base class variable
  ob.disp();
  System.out.println("Inheriting class Var="+ob.a);
  }
}

Typecasting Example


class Typecast
{
      static int a = 10;
      static long b = 20;
      public static void main(String []args)
      {
            a = (int)b;       ////explicit
            b = a;              //implicit
      }
}