Wednesday, March 22, 2017

String pattern example

Java Program to format the string (having only 1 and 0) in such a way that all 1s should be printed first then all 0s

for example the string 0011010101010001 should be printed as 0000000001111111

/* Method 1*/
package dev21century;

public class StringPattern3 {

public static void main(String[] args) {

String str = "0011010101010001";
char[] strAsCharArray = str.toCharArray();
int index1 = str.length() - 1;
int index2 = 0;
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1') {
strAsCharArray[index1] = tempChar;
index1--;
}

if (tempChar == '0') {
strAsCharArray[index2] = tempChar;
index2++;
}

}

System.out.println(strAsCharArray);
}
}



/* Method 2*/
package dev21century;

public class StringPattern3 {

public static void main(String[] args) {

String str = "0011010101010001";
StringBuffer tempStr1 = new StringBuffer();
StringBuffer tempStr2 = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1')
tempStr1.append(tempChar);

if (tempChar == '0')
tempStr2.append(tempChar);

}
str = tempStr1.toString() + tempStr2.toString();
System.out.println(str);

}
}


Output for both programs:
1111111000000000


Wednesday, March 8, 2017

Classes within an Interface

There is an option in java to create classes within an interface. In this case the inner class should always be the static class. We cannot create a non static class inside an interface.

Another condition is, we cannot create local class because we have to define the local classes in a method, and as we know we cannot define any method inside an interface.

Let’s take this example:

Create a file ClassInInterfaceImpl.java inside com.dev21century package:

package com.dev21century;
interface MyInterface1{
      public void show();
}

interface MyInterface2{
  MyInterface1 myinterface1 = new MyInterface1()
  {
   public void show()
    {
      System.out.println("Inside anonymous class of interface.");
    }
   };
    
 class Inner{
    void display()
      {
        System.out.println("static nested class inside interface.");
      }
     }
}

public class ClassInInterfaceImpl implements MyInterface2
//extends MyInterface2.Inner{

      public static void main(String[] args) {
            myinterface1.show();
            Inner inner = new Inner();
            inner.display();
            //new ClassInInterfaceImpl().display();
      }
}

Output:


In above program we have created an anonymous class as well as an inner class inside the interface.

Anonymous Class

An anonymous class is a temporary Class & Object, it is mandatory that an anonymous class must have its parent, we always keep its reference to its parent.

Lets define an anonymous class in 3 different ways:

1st Way: (create a file AnonymousDemoImpl.java inside com.dev21century):

package com.dev21century;
interface AnonymousDemo
{
      public void show();
}

public class AnonymousDemoImpl {
     
      int x = 100;
      static int y = 200;
      AnonymousDemo display(){
            return (new AnonymousDemo(){
           
            public void show()
            {
                  System.out.println("x = " + x);
                  System.out.println("y = " + y);
            }});
      }
     
      public static void main(String[] args) {
            AnonymousDemoImpl anonymous = new AnonymousDemoImpl();
            AnonymousDemo anonymousInterface = anonymous.display();
            anonymousInterface.show();
      }
}
Output:


In above program we have created an anonymous class inside display method, and there is no way to get object of that class in main() method. That’s why we have created an interface (AnonymousDemo), and made our anonymous class as a child of that interface. In main() method we have called the display method which returns object of anonymous class in a reference variable of interface.

Here compiler creates separate .class files for all anonymous classes and name them like Outer$1.class, Outer$2.class etc. In our program the .class file name is AnonymousDemoImpl$1.class.

2nd Way to create anonymous class:

Alter above program as follows:

package com.dev21century;
interface AnonymousDemo
{
      public void show();
}

public class AnonymousDemoImpl {

      int x = 10;
      static int y = 20;
      void display(AnonymousDemo annoInterface)
      {
            annoInterface.show();
      }
     
   public static void main(String[] args) 
    {
     AnonymousDemoImpl anonymous = new AnonymousDemoImpl();
     anonymous.display(new AnonymousDemo()
      {
       public void show()
       {
        System.out.println("Inside show method of anonymous class.");
        System.out.println("y = " + y);
       }
       });
    }
}

Output:


In above program we have created the anonymous class in our main method itself, and inside display method we are only calling show() method of interface which is implemented inside our anonymous class.

3rd Way to create anonymous class:

package com.dev21century;
interface AnonymousDemo
{
      public void show();
}

public class AnonymousDemoImpl {

      public static void main(String[] args) 
         {
          AnonymousDemo anonymous = new AnonymousDemo(){
          public void show()
           {
            System.out.println("Inside anonymous class.");
           }
           };
            anonymous.show();
      }
}

Output:
Inside anonymous class.

Above program is very easy way of implementing anonymous class. In all of the above programs, it is looking like we are creating an object of interface, but it is clearly not. We can never create instance of any interface. We are just creating a reference variable of interface and assigning anonymous class object in it.


Local Inner or Nested Class

Local in the sense something which is defined inside an init block, a static block, a method or a constructor. All rules and regulations do apply here as well and it cannot go beyond its block.

Rule – when we are using local variables of a function within local class then it must be final.

For example: (TempLocalClass.java)
package com.dev21century;

public class TempLocalClass {
int x=10;
      static int y=20;
      void display()
      {
            final int p=30;
            class Inner
            {
                  public void show()
                  {
                        System.out.println("p = "+p);
                        System.out.println("x = "+x);
                        System.out.println("y = "+y);
                  }
            }
            Inner inner=new Inner();
            inner.show();
      }    
      public static void main(String[] args) {
            TempLocalClass temp=new TempLocalClass();
            temp.display();
      }
}

Output:


In above program try to remove final keyword and recompile, it will not be compiled successfully.

In above program we have invoked the show() method inside display method, now how we will invoke it outside its method, because we cannot create an object of local class outside of the method. The solution for this problem is, create an interface with show() method and implement it in local class and return its reference variable. Like this:

Alter above program as follows:
package com.dev21century;
interface My
{
      public void show();
}

public class TempLocalClass {
      int x=10;
      static int y=20;

      My display()
      {
            final int p=30;
            class Inner implements My
            {
                  public void show()
                  {
                        System.out.println("p = "+p);
                        System.out.println("x = "+x);
                        System.out.println("y = "+y);
                  }
            }
            My my = new Inner();
            return my;
      }    
      public static void main(String[] args) {
            TempLocalClass temp = new TempLocalClass();
            My my = temp.display();
            my.show();
      }
}

Output:
Same as above.

Here compiler will create separate .class files for all local classes and name them something like Outer$1InnerClassName.class, Outer$2InnerClassName.class etc. In our program the compiler will create .class file name as TempLocalClass$1Inner.class.