Tuesday, 31 January 2017

Inheritance In Java

Inheritance in Java

Inheritance in java is a mechanism in which one class or object acquires all the properties(methods and fields) and behaviors of parent class or object.
extends is the keyword used to inherit the properties of a class.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

- For Code Reusability.
- For Method Overriding (so runtime polymorphism can be achieved).

Point to be remember regarding Inheritance.

- Constructor and initilization block (SIB,IIB) are not inherit to sub class
- Every constructor should have the first statement either super() or this() calling statement
- If we are not keeping the super() or this() as a first statement in constructor ,compiler will keep super().
- Parent class also have super() keyword to Object class.

Following example demonstrate inheritance , constructor, this() and super() keyword.
class A
{
    A(double d)
    {
        this();
        System.out.println("A(double)");   
    }
    A()
    {
        System.out.println("A()");
    }
    void test()
    {
        System.out.println("test()");
    }
}
class B extends A
{
    B()
    {
        super(9.3);
        System.out.println("B()");
    }
}
public class Demo
{
    public static void main(String args[])
    {
        B b=new B();
        b.test();
    }   
}

Output:
A()
A(double)
B()
test()


Programs for Practice on Inheritance

Program # 1

class A
{
    int i;
}
class B extends A
{
    int j;
    public static void main(String[] args)
    {
        B obj1=new B();
        System.out.println(obj1.i);
        System.out.println(obj1.j);
    }
}

Output:
0
0

Program # 2
Note: inside class D there are 3 members

class C
{
    int i;
    void test()
    {
        System.out.println("Test");
    }
}
class D extends C
{
    int j;
}
class E
{
    public static void main(String[] args)
    {
        D d1=new D();
        d1.i=10;
        d1.j=20;
        d1.test();
        System.out.println(d1.i);
        System.out.println(d1.j);
    }
}

Output:
Test
10
20

Program # 3
class F
{
    int i;
    static int j;
    void test1()
    {
        System.out.println("Test1");
    }
    static void test2()
    {
        System.out.println("Test2");
    }
}
class G extends F
{
    int k;
    static void test3()
    {
        System.out.println("Test3");
    }
    public static void main(String[] args)
    {
      F.j=10;
      F.test2();
      G.test2();
      G.test3();
      System.out.println(G.j);
      F f1=new F();
      f1.i=20;
      f1.test1();
      G g1=new G();
      g1.i=30;
      g1.k=50;
      g1.test1();
    }
}

Output:
Test2
Test2
Test3
10
Test1
Test1

Program # 4

class H
{
    int x;
}
class I extends H
{
    int y;
}
class J extends I
{
    int z;
}
class Manager
{
    public static void main(String[] args)
    {
        H h1=new H();
        I i1=new I();
        J j1=new J();
        System.out.println(h1.x);
        System.out.println(i1.x);
        System.out.println(j1.x);
        System.out.println(i1.y);
        System.out.println(j1.y);
        System.out.println(j1.z);
    }
}

Note: while creating the object of J all class H,I and J will load in memory

Output:
all 0

Program # 5
class K
{
    K()
    {
    //super();  //compiler keep super() internally
        System.out.println("K()");
    }
}
class L extends K
{
    L()
    {
    //super();  //compiler keep super() internally
        System.out.println("L()");
    }
}
class Manager
{
    public static void main(String[] args)
    {
        K k1=new K();
        System.out.println("------");
        L l1=new L();
        System.out.println("------");
    }
}
Note:
- constructor and initilization block (SIB,IIB) are not inherit to sub class
- every constructor should have the first statement either super() or this() calling statement
- if we are not keeping the super() or this() as a first statement in constructor ,compiler will keep super().
- even a parent class have super() statement to Object class.

Output:
K()
------
K()
L()
------

Program # 6
Note: Total 4 constructor are executing in this program.

class M extends Object
{
    M()
    {
        super();
        System.out.println("M()");
    }
}
class N extends M
{
    N()
    {
        super();
        System.out.println("N()");
    }
}
class O extends N
{
    O()
    {
        super();
        System.out.println("O()");
    }
}
class Manager2
{
    public static void main(String[] args)
    {
        M m1=new M();
        System.out.println("------");
        N l1=new N();
        System.out.println("------");
        O o1=new O();
        System.out.println("------");
    }
}


Output:
M()
------
M()
N()
------
M()
N()
O()
------

Program # 7

class P
{
    P()
    {
        System.out.println("P()");
    }
}
class Q extends P
{
    Q()
    {
        System.out.println("Q()");
    }
}
class R extends Q
{
    R()
    {
        System.out.println("R()");
    }
}
class S extends R
{
    S()
    {
        System.out.println("S()");
    }
}
class T extends S
{
    T()
    {
        System.out.println("T()");
    }
    public static void main(String[] args)
    {
        P m1=new P();
        System.out.println("------");
        Q l1=new Q();
        System.out.println("------");
        R o1=new R();
        System.out.println("------");
        S s1=new S();
        System.out.println("------");
        T t1=new T();
        System.out.println("------");
    }
}


Output:
R()
S()
------
P()
Q()
R()
S()
T()
------

Program # 8
class A
{
    A()
    {
        System.out.println("A()");
    }
    A(int i)
    {
        System.out.println("A(int)");
    }
}
class B extends A
{
    B()
    {
        System.out.println("B()");
    }
    B(int i)
    {
        System.out.println("B(int)");
    }
}
class Manager
{
    public static void main(String[] args)
    {
      A m1=new A();
      System.out.println("------");
      A l1=new A(20);
      System.out.println("------");
      B o1=new B();
      System.out.println("------");
      B s1=new B(30);
      System.out.println("------");
    }
}


Output:
A()
------
A(int)
------
A()
B()
------
A()
B(int)
------

Program # 9
class E
{
    E()
    {
        System.out.println("E()");
    }
}
class F extends E
{
    F(int i)
    {
        System.out.println("F(int)");
    }
}
class Manager2
{
    public static void main(String[] args)
    {
      E m1=new E();
      System.out.println("------");
      F l1=new F(20);
    }
}

Output:
E()
------
E()
F(int)

Program # 10
class G
{
    G(int i)
    {
        System.out.println("G(int)");
    }
}
class H extends G
{
    H()
    {
        //super(10); if remove this super(10) will give compiler error
        System.out.println("H()");
    }
}
class Manager3
{
    public static void main(String[] args)
    {
      G g1=new G(90);
      System.out.println("------");
      H h1=new H();
    }
}

Output:
H.java:11: cannot find symbol
symbol : constructor G()
location: class G
{
^
1 error
------------------
G(int)
------
G(int)
H()

Program # 11
class I
{
    I(double j)
    {
        System.out.println("I(double)");
    }
}
class J extends I
{
    J()
    {
        super(9.9);
        System.out.println("J()");
    }
    J(double d){
        super(d);
        System.out.println("J(double)");
    }
}
class Manager4
{
    public static void main(String[] args)
    {
      I i1=new I(9.9);
      System.out.println("----------");
      J j1=new J();
      System.out.println("----------");
      J j2=new J(3.4);
    }
}

Output:
I(double)
----------
I(double)
J()
----------
I(double)
J(double)

Program # 12
class K
{
    K()
    {
        System.out.println("K()");
    }
    {
        System.out.println("K-IIB");
    }
}
class L extends K
{
    L()
    {
        System.out.println("L()");
    }
    {
        System.out.println("L-IIB");
    }
}
class Manager5
{
    public static void main(String[] args)
    {
        K k1=new K();
        System.out.println("----------");
        L l1=new L();
        System.out.println("----------");
    }
}

Output:
K-IIB
K()
----------
K-IIB
K()
L-IIB
L()
----------

Program # 13
class M
{
    M()
    {
        System.out.println("M()");
    }
    {
        System.out.println("M-IIB-1");
    }
    {
        System.out.println("M-IIB-2");
    }
}
class N extends M
{
    N()
    {
        System.out.println("N()");
    }
    {
        System.out.println("N-IIB-1");
    }
    {
        System.out.println("N-IIB-2");
    }
}
class Manager6
{
    public static void main(String[] args)
    {
      M k1=new M();
      System.out.println("----------");
      N l1=new N();
      System.out.println("----------");
    }
}

Output:
M-IIB-1
M-IIB-2
M()
----------
M-IIB-1
M-IIB-2
M()
N-IIB-1
N-IIB-2
N()
----------

Program # 14
class O
{
    {
        System.out.println("O-IIB");
    }
    O()
    {
        System.out.println("O()");
    }
}
class P extends O
{
    P()
    {
        System.out.println("P()");
    }
    {
        System.out.println("P-IIB");
    }
    P(int i)
    {
        this();//IT will call constructor of same class
        System.out.println("P(int)");
    }
}
class Manager7
{
    public static void main(String[] args)
    {
        O m1=new O();
        System.out.println("------");
        P o1=new P();
        System.out.println("------");
        P s1=new P(30);
        System.out.println("------");
    }
}

Output:
O-IIB
O()
------
O-IIB
O()
P-IIB
P()
------
O-IIB
O()
P-IIB
P()
P(int)
------

Saturday, 28 January 2017

Abstraction in Java

Abstraction in Java

It is the process of hiding the implementation details and showing only functionality to the user.

For example sending sms, you just type the text and send the message. You don't know the internal processing about the message sending and delivery.

Abstraction lets you focus on what the object does instead of how it does.


There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)

Example:
abstract class Shape
{
    abstract void draw();
}
class Circle extends Shape
{
    void draw()
    {
        System.out.println("circle is drawing");
    }
}
class Square extends Shape
{
    void draw()
    {
        System.out.println("square is drawing");
    }
}
class Demo
{
   public static void main(String args[])
    {
        Shape s1=new Circle();
        s1.draw();
        Shape s2=new Square();
        s2.draw();
    }   
}

Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
circle is drawing
square is drawing

Point to be noted :

1. Abstract method : No definition just declaration,all declare method should have abstract keyword
2. If class containing any abstract method ,class should be declare as abstract class.
3. we cant create an object of an abstract class but can create just reference variable.(C c1=null;),
4. null is keyword which is used to initialize any reference variable
5. An abstract method can be use by inheritance and on creation of object.
4. Abstract class also generate .class file on compiling.


Programs for Practice on Abstraction

Program # 1

abstract class E
{
     abstract void test1();
     void test2()
     {
        System.out.println("Test2");
     }
}
class Demo extends E
{
     void test1()
     {
          System.out.println("Test1");
     }
     public static void main(String[] args)
     {
        Demo d1=new Demo();
          d1.test1();
          d1.test2();
          System.out.println("Done");
     }
}

Output::
Test1
Test2
Done

Program # 2
abstract class G
{
     void test1()
     {
          System.out.println("Test1");
     }
     abstract void test2();
     void test3()
     {
        System.out.println("Test3");
     }
}
class H extends G
{
     void test2()
     {
          System.out.println("Test2");
     }
     void test4()
     {
          System.out.println("Test4");
     }
     public static void main(String[] args)
     {
          H h1=new H();
          h1.test1();
          h1.test2();
          h1.test3();
          h1.test4();
          System.out.println("Done");
     }
}

Output::
Test1
Test2
Test3
Test4
Done

Program # 3
abstract class J
{
     abstract void test1();
     abstract int test2();
     abstract int test3(double d);
     void test4()
     {
          System.out.println("Test4");
     }
}
abstract class K extends J
{
     void test1()
     {
          System.out.println("Test1");
     }
}
class L extends K
{
     int test2()
     {
          System.out.println("Test2");
          return 10;
     }
     int test3(double d)
     {
          System.out.println("Test3");
          return 20;
     }
}
class M
{
     public static void main(String[] args)
     {
      L h1=new L();
      h1.test1();
      h1.test2();
      h1.test3(2.3);
      h1.test4();
      System.out.println("Done");
     }
}


Output::
Test1
Test2
Test3
Test4
Done

Program # 4
Note: An abstract method can have all concrete method even though we can not create the object of an abstract class.

abstract class N
{
     void test1()
     {
        System.out.println("Test1");
     }

class O extends N
{
}
class P
{
     public static void main(String[] args)
     {
          N n1=new N();
          n1.test1();
          //O o1=new O();
          //o1.test1();
          System.out.println("Done");
     }
}

Output::
When try to create object of abstract class then following compilation error.
Test.java:15: error: N is abstract; cannot be instantiated
          N n1=new N();
               ^

Program # 5
Note: Whenever object creates constructor executes. We can keep a constructor inside a abstract class but constructor cannot be abstract.
      Constructor can not inherit to base class ,so we can not implement the abstract class hence constructor can not be abstract.
     
abstract class Q
{
     Q()
     {
          System.out.println("Q()");
     }
     abstract void test1();
     abstract void test2();
     void test3()
     {
        System.out.println("Test3");
     }

class R extends Q
{
     R()
     {
          System.out.println("R()");
     }
     void test1()
     {
          System.out.println("Test1");
     }
     void test2()
     {
          System.out.println("Test2");
     }
}
class S
{
     public static void main(String[] args)
     {
          R r1=new R();
          System.out.println("------");
          r1.test1();
          r1.test2();
          r1.test3();
     }
}

Output::
Q()
R()
------
Test1
Test2
Test3


Tuesday, 10 January 2017

Method Overloading and Overriding in Java

Method overloading in java

If a class have multiple methods of same name but different argument list and type known as method overloading.
Advantage : Method overloading increases the readability of the program.

Point to be noted of method overloading.
1.Multiple method with same name but Different argument list and argument type.
2.Return type and access modifier may or may not be different.
4.overload happen in same class
5.invoking done based on signature of method.
6.Binding happens at compile time

Example of a method overloading.
class Demo
{
    void sum(int a, int b)
    {
        System.out.println(a+b);
    }
    void sum(int a, int b, int c)
    {
        System.out.println(a+b+c);
    }
    public static void main(String args[])
    {
        Demo d=new Demo();
        d.sum(2,4);
        d.sum(2,3,4);
    }    
}


In java, method overloading is not possible by changing the only the return type of the method because there may occur ambiguity.
If we try this we will get compile time error saying method already defined.

class Calculation
{
    int sum(int x,int y)
    {
        System.out.println(x+y);
    }
    double sum(int a,int b)
    {
        System.out.println(a+b);
    }  
    public static void main(String args[])
    {
        Calculation obj=new Calculation();
        int result=obj.sum(20,25); // compile time error.
    }
}


Q. Can we overload main() method?

Yes, You can have any number of main methods in a class by method overloading. Let's see the simple example:

class Overloading{  
  public static void main(int a)
  {  
    System.out.println(a);  
  }  
  public static void main(String args[])
  {  
    System.out.println("main() method invoked");  
    main(20);  
  }  
}  



Method Overriding in java

If child class has the same method as declared in the parent class, It is known as method overriding.

- Method overriding is used to provide specific implementation of a method that is already provided by its super class.
- Method overriding is used for runtime polymorphism.

Point to be noted of java overriding:
Method name same,and argument list and argument type should same as in the parent class.
Happens between super(parents) or base( child ) class. must be IS-A relationship (inheritance).
Invoking done based on the data type of the object referred by the reference.
Happens at run time.

Example of method overriding

class Vehicle
{
    void run()
    {
        System.out.println("vehicle is running");
    }
}
class Bike extends Vehicle
{
    void run()
    {
        System.out.println("bike is running");
    }
    public static void main(String args[])
    {
        Bike b=new Bike();
        b.run();
    }    
}


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Bike
bike is running


Example of polymorphism

class C
{
    void test()
    {
        System.out.println("C-test");
    }
}
class D extends C
{
    void test()
    {
        System.out.println("D-test");
    }
}
class Demo
{
    static void method(C c1)
    {
        c1.test();
    }
    public static void main(String args[])
    {
        C obj1=new C();
        D obj2=new D();
        method(obj1);
        method(obj2);
    }    
}


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
C-test
D-test


Difference between method overloading and method overriding in java.
Overloading:
1.Multiple method with same name but Different argument list and argument type.
2.Return type and access modifier may or may not be different
4.Overload happen in same class
5.Invoking done based on signature of method.
6.Binding happens at compile time( Example of compile time polymorphism).

Overriding:
1.Method name same,and argument list and argument type should same as in the parent class.
2.Return type must be same or covariant in method overriding.
3.Happens between super(parents) or base( child ) class. must be IS-A relationship (inheritance).
5.Invoking done based on the data type of the object reffered by the reference.
6.Happens at run time (Example of run time polymorphism).


Programs on Methos overloading and overriding


Program # 1

class A
{
    void test1(int i)
    {
        System.out.println("Test1(int)");
    }
    int test1()
    {
        System.out.println("Test()");
        return 10;
    }
    public void test1(double d)
    {
        System.out.println("Test1(double)");
    }
    void test1(int i,int j)
    {
        System.out.println("test1(int,int)");
    }
}
class Manager
{
    public static void main(String[] args)
    {
        A a1=new A();
        a1.test1(10);
        a1.test1();
        a1.test1(20.9);
        a1.test1(10,11);}
}


OUTPUT:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Manager
Test1(int)
Test()
Test1(double)
test1(int,int)

Program # 2

class D 
{
    static void test() 
    {
        System.out.println("Hello World!");
    }
    public int test()
    {
        return 20;
    }
}


OUTPUT:
mukesh@ubuntu:~/Desktop/javaPrograms$ javac Test.java
Test.java:7: error: method test() is already defined in class D
     public int test()
                ^
1 error

Note: In above program
- compiler error : duplicate methods
- Parameter must be diffrent

Program # 3

abstract class E 
{
    abstract void test();
    void test() 
    {
        int i=10;
    }
}


OUTPUT:
Note: compiler error : duplicate methods

Program # 4

abstract class F
{
    abstract void test();
    abstract void test(int i);
    void test(int i,int j)
    {
        System.out.println("Test1(int,int)");
    }
}
class G extends F
{
    void test()
    {
        System.out.println("Test()");
    }
    void test(int i)
    {
        System.out.println("Test(int)");
    }
    public static void main(String[] args) 
    {
        G g1=new G();
        g1.test();
        g1.test(10);
        g1.test(1,20); 
    }
}


OUTPUT:
Test()
Test(int)
Test1(int,int)


Program # 5

class H
{
    void test1()
    {
        System.out.println("Test1()");
    }
    void test2()
    {
        System.out.println("Test2()");
    }
}
class I extends H
{
    void test2()
    {
        System.out.println("Modified Test2()");
    }
    public static void main(String[] args) 
    {
        I obj=new I();
        obj.test1();
        obj.test2(); }
}

OUTPUT:
Test1()
Modified Test2()


Program # 6

abstract class J
{
    abstract void test(int i);
}  
class K extends J
{
    void test()
    {
        System.out.println("Test()");
    }
    /*void test(int i)
    {
        System.out.println("test(int)");
    }*/
}


OUTPUT:
K.java:6: K is not abstract and does not override abstract method test(int) in J
class K extends J
^
1 error


Program # 7 : While overriding return types of method should be same.

class L
{
    void test1()
    {
        System.out.println("test1()");
    }
}
class M extends L
{
    int test1()
    {
        System.out.println("test1()");
        return 10;
    }
}


OUTPUT:
mukesh@ubuntu:~/Desktop/javaPrograms$ javac Test.java
Test.java:10: error: test1() in M cannot override test1() in L
    int test1()
        ^
  return type int is not compatible with void
1 error

Program # 8

abstract class N
{
    abstract int test1();
}  
class O extends N
{
    void test1()
    {
    }
}


OUTPUT:
Compiler error return type are not same,could not override

Program # 9

abstract class U
{
    public abstract void test1();
}
class V extends U 
{
    void test1()           //error
    //public void test1() //compile success
 {

 }
}


OUTPUT:

V.java:8: test1() in V cannot override test1() in U; attempting to assign weaker access privileges; was public
void test1()
^
1 error


********************************* End *********************************

Saturday, 7 January 2017

Top 25 Java Logical Programs

To 25 Java logical program . Just go through all of them if you are going to appear in a jva written test or interview.

1) Write a program to swap two numbers without using temporary variable.
2) Write a program which takes 1 to 100 number , print "A" if number is divisible by 3 , print "B" if number is divisible by 5 and print "C" if it is divisivle by 3 and 5 both else print "D".
3) Write a program to check the given number is a prime number or not.
4) Write a program to check if number is perfect square or not.
5) Write a program to calculate factorial of a number.
6) Write a program to calculate power of a number.
7) Write a program to reverse a number.
8) Write a java program which will reverse the string.
9) Write a program in java to check if string is palindrome.
10) Write a program to find top two maximum numbers in a array.
11) Write a program to find common elements between two arrays.
12) Write a program to print fibonacci series.
13) Write a program which can extract duplicate element from an array.
14) Write a program to find sum of each digit in the given number using recursion.
15) Write a program to check the given number is binary number or not.
16) Write a program to convert binary to decimal number.
17) Write a program to convert decimal number to binary.
18) Wrie a program to find out duplicate characters in a string.
19) Write a program to create a following pyramid.
20) Write a program to create a following pyramid.
21) Write a program to create a following pyramid.
22) Write a program to draw a following pyramid.
23) Write a program to draw a following pyramid.
24) Write a program for Bubble Sort in java.
25) Write a program for Insertion Sort in java.


1) Write a program to swap two numbers without using temporary variable. 

  class A
  {
      public static void main(String[] args) 
      {
          int i=3 ,j=5;
          System.out.println("value if i & j before : i="+i+" and j= "+j);
          i= i+j;
          j = i - j;
          i = i - j;
          System.out.println("value if i & j After : i="+i+" and j= "+j);
      }
  }
Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java A
value if i & j before : i=3 and j= 5
value if i & j After : i=5 and j= 3

2) Write a program which takes 1 to 100 number , print "A" if number is divisible by 3 , print "B" if number is divisible by 5 and print "C" if it is divisible by 3 and 5 both else print "D". 

class Demo
{
 
      public static void main(String args[]) 
      {
          for( int i=1; i<=100; i++ ) 
          {
              if ( i%3 == 0 && i%5 ==0)
              System.out.println(i+"="+"C");
              else if( i%3 == 0 )
              System.out.println(i+"="+"A");
              else if( i%5 == 0 )
              System.out.println(i+"="+"B");
              else
              System.out.println(i+"="+"D");
 
      }
 
      }
 
  }


3) Write a program to check the given number is a prime number or not. 

  import java.util.*;
 
  public class Demo 
 
  {
      public boolean isPrimeNumber(int number)
      {         
          for(int i=2; i<number; i++)//for(int i=2; i<=number/2; i++)
          {
              if(number % i == 0)
              {
                  return false;
              }
          }
          return true;
      }     
      public static void main(String a[])
      {
          int n;
          System.out.println("Enter a number to check prime");
          Scanner in=new Scanner(System.in);
          n=in.nextInt();
          Demo mpc = new Demo();
          System.out.println("Is "+ n + " prime number? "+mpc.isPrimeNumber(n));
      }
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
Enter a number to check prime
13
Is 13 prime number? true
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
Enter a number to check prime
18
Is 18 prime number? false

4) Write a program to check if number is perfect square or not.
  import java.util.Scanner;
 
  class Demo
  {
      public static void main(String args[])
      {
          int n;
          boolean isSquare = false;
          System.out.println("Enter the number to check perfect square");
          Scanner in=new Scanner(System.in);
          n = in.nextInt();
          
          for(int i=0; i<=n; i++)
          {
              if(n == i*i)
              {
                  isSquare = true;
                  break;
              }
          }
          if(isSquare)
          {
              System.out.println("perfect square");
          }    
          else
          {
              System.out.println("Not a perfect square");
          }
      }
  }
Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
Enter the number to check perfect square
3
Not a perfect square
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo
Enter the number to check perfect square
49
perfect square

5) Write a program to calculate factorial of a number. 

  
import java.util.Scanner;
  class Factorial
  {
     public static void main(String args[])
     {
        int num,fact = 1;
   
        System.out.println("Enter an integer to calculate it's factorial");
        Scanner in = new Scanner(System.in);
   
        num = in.nextInt();
   
        if ( num < 0 )
           System.out.println("Number should be non-negative.");
        else
        {
           for (int i = 1 ; i <= num ; i++ )
              fact = fact*i;
   
           System.out.println("Factorial of "+num+" is = "+fact);
        }
     }
  }

Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Factorial 
Enter an integer to calculate it's factorial
5
Factorial of 5 is = 120

6) Write a program to calculate power of a number. 

  
import java.util.Scanner;
   
  class Demo
  {
     public static void main(String args[])
     {
        int num,pow,result = 1;
        System.out.println("Enter number on which power required");
        Scanner n = new Scanner(System.in);
        num = n.nextInt();
        System.out.println("Enter power");
        Scanner p = new Scanner(System.in);
        pow = p.nextInt();
        for(int i=1; i<=pow; i++ )
        {
              result = result * num ;
        }
        System.out.println("The result is :"+result);
      }
  }

Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo 
Enter number on which power required
3
Enter power
3
The result is :27

7) Write a program to reverse a number. 

import java.util.Scanner;
   
  class ReverseNumber
  {
     public static void main(String args[])
     {
        int n, reverse = 0;
   
        System.out.println("Enter the number to reverse");
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
   
        while( n != 0 )
        {
            reverse = reverse * 10;
            reverse = reverse + n%10;
            n = n/10;
        }
   
        System.out.println("Reverse of entered number is "+reverse);
     }
  }
  
Output:
Enter the number to reverse
324
Reverse of entered number is 423

8) Write a java program which will reverse the string. 

  
import java.util.Scanner;

class ReverseString
  {
      public static void main(String args[])
      {
          String original,reverse="";
          Scanner in = new Scanner(System.in);
          System.out.println("Enter a string");
          original = in.nextLine();
          int len = original.length();
          for( int i = len -1 ; i >=0 ; i-- )
              reverse = reverse + original.charAt(i);

          System.out.println("Reverse of entered string is: "+reverse);
     }
  }


Output:
Enter a string
i love java
Reverse of entered string is: avaj evol i

9) Write a program in java to check if string is palindrome. 

import java.util.Scanner;
   
  class palindrome
  {
     public static void main(String args[])
     {
        String original, reverse = "";
        Scanner in = new Scanner(System.in);
   
        System.out.println("Enter a string to reverse");
        original = in.nextLine();
   
        int length = original.length();
   
        for ( int i = length - 1 ; i >= 0 ; i-- )
           reverse = reverse + original.charAt(i);
              
              if(reverse.equalsIgnoreCase(original))
              {
                  System.out.println("The string is Palindrome");
              }
              else
              {
                  System.out.println("Not Palindrome");
              }
     }
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java palindrome 
Enter a string to reverse
mukesh
Not Palindrome
mukesh@ubuntu:~/Desktop/javaPrograms$ java palindrome 
Enter a string to reverse
aka
The string is Palindrome

10) Write a program to find top two maximum numbers in a array. 

  
public class Demo
 
  {
 
      public static void main(String[] args)
 
      {
 
          int maxNum = 0;
 
          int secondMaxNum = 0;
 
          int[] anArray; 
 
          anArray =new int [10];
 
          anArray[0] = 100; 
 
          anArray[1] = 200; 
 
          anArray[2] = 300; 
 
          anArray[3] = 400;
 
          anArray[4] = 500;
 
          if(anArray.length == 0)
 
          {
 
              System.err.println("anArray is empty");
 
              return;
 
          }
 
          for(int i=0; i < anArray.length; i++)
 
          {
 
              int currNum = anArray[i];
 
              if(maxNum < currNum)
 
              {
 
                  secondMaxNum = maxNum;
 
                  maxNum = currNum;
 
              }
 
              else if(secondMaxNum < currNum)
 
              {
 
                  secondMaxNum = currNum;
 
              }
 
          }
 
              System.out.println("Max. number is "+maxNum);
 
              System.out.println("Second Max. is "+secondMaxNum);
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo 
Max. number is 500
Second Max. is 400

11) Write a program to find common elements between two arrays. 

  public class CommonElementsInArray 
 
  {
 
      public static void main(String a[])
 
      {
 
          int[] arr1 = {4,7,3,9,2};
 
          int[] arr2 = {3,2,12,9,40,32,4};
 
          for(int i=0;i<arr1.length;i++)
 
          {
 
              for(int j=0;j<arr2.length;j++)
 
              {
 
                  if(arr1[i]==arr2[j])
 
                  {
 
                      System.out.println(arr1[i]);
 
                  }
 
              }
 
          }
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java CommonElementsInArray 
4
3
9
2

12) Write a program to print fibonacci series. 

  /*Write a program to find Fibonacci series of a given no. Example : 
 
  Input - 8 Output - 1 1 2 3 5 8 13 21 */ 
 
  class Fibonacci
 
  { 
 
      public static void main(String args[])
 
      { 
 
          int num = Integer.parseInt(args[0]);
 
           //taking no. as command line argument. System.out.println("*****Fibonacci Series*****"); 
 
          int f1, f2=0, f3=1; 
 
          for(int i=1;i<=num;i++)
 
          { 
 
              System.out.print(" "+f3+" "); 
 
              f1 = f2; 
 
              f2 = f3; 
 
              f3 = f1 + f2; 
 
          } 
 
      } 
 
  } 


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Fibonacci 6
 1  1  2  3  5  8
 
13) Write a program which can extract duplicate element from an array. 

import java.util.Scanner;


class Demo
 
  {
 
      public static void main(String[] args)
 
      {
 
          Scanner sc=new Scanner(System.in);
 
          System.out.println("enter the size of array you want");
 
          int num=sc.nextInt();
 
          int array[]=new int[num];
 
          System.out.println("enter the" + num + "elements");
 
          for(int i=0; i < num; i++)
 
          {
 
              array[i]=sc.nextInt();
 
          }
 
          printRepeating(array, array.length);
 
      }
 
      static void printRepeating(int arr[], int size)
 
      {
 
            int i, j;
 
            System.out.println(" Repeating elements are ");
 
            for(i = 0; i < size; i++)
 
          for(j = i+1; j < size; j++)
 
            if(arr[i] == arr[j])
 
          System.out.println( arr[i]);
 
      } 
 
  }


Output:
enter the size of array you want
5
enter the5elements
2
3
2
4
3
 Repeating elements are 
2
3

14) Write a program to find sum of each digit in the given number using recursion. 

  public class MyNumberSumRec {
 
   
 
      int sum = 0;
 
       
 
      public int getNumberSum(int number){
 
           
 
          if(number == 0){
 
              return sum;
 
          } else {
 
              sum += (number%10);
 
              getNumberSum(number/10);
 
          }
 
          return sum;
 
      }
 
       
 
      public static void main(String a[]){
 
          MyNumberSumRec mns = new MyNumberSumRec();
 
          System.out.println("Sum is: "+mns.getNumberSum(223));
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java MyNumberSumRec 
Sum is: 7

15) Write a program to check the given number is binary number or not. 

  import java.util.*;
 
  public class Demo 
 
  {    
 
      public static void main(String a[])
 
      {
 
          boolean notBinary=false;
 
          System.out.println("Enter the number");
 
          Scanner in=new Scanner(System.in);
 
          int num=in.nextInt();
 
          while( num != 0 )
 
          {
 
              int rem=num % 10;
 
              
 
              if(rem >1)
 
              {
 
                  notBinary=true;
 
                  break;
 
              }
 
              num=num/10;
 
          }
 
          if(notBinary)
 
          {
 
              System.out.println("not binary");
 
          }
 
          else
 
          {
 
              System.out.println("is binary");
 
          }
 
              
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo 
Enter the number
1001
is binary
mukesh@ubuntu:~/Desktop/javaPrograms$ java Demo 
Enter the number
1003
not binary

16) Write a program to convert binary to decimal number. 

  public class BinaryToDecimal 
 
  { 
 
      public int getDecimalFromBinary(int binary)
 
      {         
 
          int decimal = 0;
 
          int power = 0;
 
          while(true)
 
          {
 
              if(binary == 0)
 
              {
 
                  break;
 
              } 
 
              else 
 
              {
 
                  int tmp = binary%10;
 
                  decimal += tmp*Math.pow(2, power);
 
                  binary = binary/10;
 
                  power++;
 
              }
 
          }
 
          return decimal;
 
      }     
 
      public static void main(String a[]){
 
          BinaryToDecimal bd = new BinaryToDecimal();
 
          System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
 
          System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
 
          System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java BinaryToDecimal 
11 ===> 3
110 ===> 6
100110 ===> 38
        
        
17) Write a program to convert decimal number to binary. 

  import java.util.Scanner;
 
  class Demo 
 
  {
 
      public static void main(String args[])
 
      {
 
          int binary[] = new int[25];
 
          int index = 0;
 
          Scanner sc=new Scanner(System.in);
 
          System.out.print("Enter the decimal number");
 
          int number=sc.nextInt();
 
          while(number > 0)
 
          {
 
              binary[index++] = number%2;
 
              number = number/2;
 
          }
 
          for(int i = index-1;i >= 0;i--)
 
          {
 
              System.out.print(binary[i]);
 
          }
 
      }     
 
  }


Output:
Enter the decimal number4
100  

18) Write a program to find out duplicate characters in a string. 

  import java.util.Scanner;  
 
    
 
  public class Same_Occurence_String 
 
  {  
 
      public static void main(String[] args) 
 
      {  
 
          Scanner scan=new Scanner(System.in);  
 
          System.out.println("enter the string");  
 
          String g=scan.next();  
 
          System.out.println("enter the character you want to search for");  
 
            String l=  scan.next();  
 
           char[] c= l.toCharArray();  
 
             int  count=0;  
 
             for(int i=0;i<=g.length()-1;i++)
 
          {  
 
             for(int k=0;k<=c.length-1;k++)  
 
             {  
 
                 if(g.charAt(i)==c[k])
 
                 {  
 
                         System.out.println("indexes where duplicate character are"+i);  
 
                         count++;    
 
                     }  
 
                 }  
 
          }  
 
             System.out.println("no. of duplicate character"+count);    
 
      }  
 
  } 


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java Same_Occurence_String 
enter the string
coolstuffsite
enter the character you want to search for
s
indexes where duplicate character are4
indexes where duplicate character are9
no. of duplicate character2

19) Write a program to create a following pyramid.
*
**
***
****
*****
******
*******
import java.util.Scanner;
 
  public class Demo
 
  {
 
         public static void main(String args[])
 
      {    
 
          Scanner sc=new Scanner(System.in);
 
          System.out.println("enter number");
 
          int num=sc.nextInt();
 
          for(int i=0; i<=num; i++)
 
          {
 
              for(int j=0; j<=i; j++)
 
              System.out.print("*");
 
              System.out.println("");
 
          }
 
      }
 
  }


20) Write a program to create a following pyramid.
********
*******
******
*****
****
***
**
*
import java.util.Scanner;
 
  public class Demo
 
  {
 
         public static void main(String args[])
 
      {    
 
          Scanner sc=new Scanner(System.in);
 
          System.out.println("enter number");
 
          int num=sc.nextInt();
 
          for(int i=num; i>=0; i--)
 
          {
 
              for(int j=0; j<=i; j++)
 
              System.out.print("*");
 
              System.out.println("");
 
          }
 
      }
 
  }


21) Write a program to create a following pyramid.
      *
     ***
    *****
   *******
  *********
 ***********
import java.util.Scanner;
 
  class Demo
 
  {
 
      public static void main(String args[])
 
      {
 
          Scanner sc=new Scanner(System.in);
 
          System.out.println("enter number");
 
          int num=sc.nextInt();
 
          for (int i=0; i<num; i++)
 
            {
 
               for (int k=0; k<num-i; k++)
 
               {
 
                  System.out.print(" ");
 
               }
 
               for (int j=0; j<i*2+1; j++)
 
              {
 
                  System.out.print("*");
 
              }
 
               System.out.println("");
 
            }
 
      }
 
  } 


22) Write a program to draw a following pyramid.
     *
    * *
   * * *
  * * * *
 * * * * *
 
  import java.util.Scanner; (flipkart)
 
  class Demo
 
  {
 
      public static void main(String args[])
 
      {
 
          Scanner sc=new Scanner(System.in);
 
          System.out.println("enter number");
 
          int num=sc.nextInt();
 
          for (int i=0; i<num; i++)
 
            {
 
               for (int j=0; j<num-i; j++)
 
               {
 
                  System.out.print(" ");
 
               }
 
              boolean flag=true;
 
               for (int k=0; k<i*2+1; k++)
 
              {
 
                  
 
                  if(flag)
 
                  {
 
                      System.out.print("*");
 
                      flag=false;
 
                  }
 
                  else
 
                  {
 
                      System.out.print(" ");
 
                      flag=true;
 
                  }
 
              }
 
               System.out.println("");
 
            }
 
      }
 
  }
 
  
    
23) Write a program to draw a following pyramid.    
   #&
  ##&&
 ###&&&
####&&&&
$$$$****
 $$$***
  $$**
   $*
    
  public class Demo 
 
  {
 
      public static void main(String args[])
 
      {
 
      for (int i = 1; i <= 5; i++) 
 
      {
 
           for (int s = 5; s > i; s--) 
 
          {
 
              System.out.print(" ");
 
          }
 
          for (int j = 1; j < i; j++) 
 
          {
 
              System.out.print("#");
 
          }
 
          for (int j = 1; j < i; j++) 
 
          {
 
              System.out.print("&");
 
          }
 
              System.out.println("");
 
          }
 
          for (int i = 1; i <= 5; i++) 
 
          {
 
              for (int s = 1; s < i; s++) 
 
              {
 
                  System.out.print(" ");
 
              }
 
              for (int j = 5; j > i; j--) 
 
              {
 
                  System.out.print("$");
 
              }
 
              for (int j = 5; j > i; j--) 
 
              {
 
                  System.out.print("*");
 
              }
 
              System.out.println("");
 
          }
 
      }
 
  }


24) Write a program for Bubble Sort in java. 

  public class MyBubbleSort 
 
  {
 
      // logic to sort the elements
 
      public static void bubble_srt(int array[]) 
 
      {
 
          int n = array.length;
 
          int k;
 
          for (int m = n; m >= 0; m--) 
 
          {
 
              for (int i = 0; i < n - 1; i++) 
 
              {
 
                  k = i + 1;
 
                  if (array[i] > array[k]) 
 
                  {
 
                      swapNumbers(i, k, array);
 
                  }
 
              }
 
              printNumbers(array);
 
          }
 
      }
 
      private static void swapNumbers(int i, int j, int[] array) 
 
      {
 
          int temp;
 
          temp = array[i];
 
          array[i] = array[j];
 
          array[j] = temp;
 
      }
 
      private static void printNumbers(int[] input) 
 
      {         
 
          for (int i = 0; i < input.length; i++) 
 
          {
 
              System.out.print(input[i] + ", ");
 
          }
 
          System.out.println("\n");
 
      }
 
      public static void main(String[] args) 
 
      {
 
          int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
 
          bubble_srt(input);
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java MyBubbleSort 
2, 4, 6, 9, 12, 23, 0, 1, 34, 
2, 4, 6, 9, 12, 0, 1, 23, 34, 
2, 4, 6, 9, 0, 1, 12, 23, 34, 
2, 4, 6, 0, 1, 9, 12, 23, 34, 
2, 4, 0, 1, 6, 9, 12, 23, 34, 
2, 0, 1, 4, 6, 9, 12, 23, 34, 
0, 1, 2, 4, 6, 9, 12, 23, 34, 
0, 1, 2, 4, 6, 9, 12, 23, 34, 
0, 1, 2, 4, 6, 9, 12, 23, 34, 
0, 1, 2, 4, 6, 9, 12, 23, 34,

25) Write a program for Insertion Sort in java. 

  public class MyInsertionSort 
 
  { 
 
      public static void main(String[] args) 
 
      {
 
           
 
          int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
 
          insertionSort(input);
 
      }  
 
      private static void printNumbers(int[] input) 
 
      {
 
           
 
          for (int i = 0; i < input.length; i++) 
 
          {
 
              System.out.print(input[i] + ", ");
 
          }
 
          System.out.println("\n");
 
      }
 
      public static void insertionSort(int array[]) 
 
      {
 
          int n = array.length;
 
          for (int j = 1; j < n; j++) 
 
          {
 
              int key = array[j];
 
              int i = j-1;
 
              while ( (i > -1) && ( array [i] > key ) ) 
 
              {
 
                  array [i+1] = array [i];
 
                  i--;
 
              }
 
              array[i+1] = key;
 
              printNumbers(array);
 
          }
 
      }
 
  }


Output:
mukesh@ubuntu:~/Desktop/javaPrograms$ java MyInsertionSort 
2, 4, 9, 6, 23, 12, 34, 0, 1, 
2, 4, 9, 6, 23, 12, 34, 0, 1, 
2, 4, 6, 9, 23, 12, 34, 0, 1, 
2, 4, 6, 9, 23, 12, 34, 0, 1, 
2, 4, 6, 9, 12, 23, 34, 0, 1, 
2, 4, 6, 9, 12, 23, 34, 0, 1, 
0, 2, 4, 6, 9, 12, 23, 34, 1, 
0, 1, 2, 4, 6, 9, 12, 23, 34, 
Related Posts Plugin for WordPress, Blogger...