Thursday, 28 July 2016

Covariant return type

In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass.

C# does not support return type covariance. Covariant return types have been (partially) allowed in the Java language since the release of JDK5.0.

However if the return type is void or primitive then the data type of parent class method and overriding method should be same.

class Parent { 
     Parent getCovariant() {
           return this;
     }

     void getMessage() {
           System.out.println("Covariant return type!!");
     }
}

class TestCovariant extends Parent {

     TestCovariant getCovariant() {
           return this;
     }

     public static void main(String args[]) { 
           new TestCovariant().getCovariant().getMessage(); 
     } 
}
Output:
Covariant return type!!

How to proof that main method will called without creating the instance of Class?

1. Using Instance Initializer block
Instance Initializer block is used to initialize the instance data member. It runs each time when object of the class is created.

public class MainMethodTest {
     /** Instance block called while creating the Object. */
     {
           System.out.println("Inside Instance Initializer block!!");
     }
    
     public static void main(String[] args) {
           System.out.println("Main method executed!!");
     }
}
Output:
Main method executed!!

In above program, there is main() method along with Instance Initializer block. The Instance Initializer block is not called while executing the main method which proves that the class is not initialised while executing the main method.

2. By using abstract keyword
We cannot create the instance of an abstract class. Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

public abstract class MainMethodTest {
    
     public static void main(String[] args) {
           System.out.println("Main method executed!!");
     }
}
Output:
Main method executed!!

However we are able to execute the main method inside the abstract class which proves that there is no need to create the object while executing the main method.

3. Using Constructor
A default (no-argument) constructor is called while creating the object of any class.

public abstract class MainMethodTest {
    
     public MainMethodTest() {
           System.out.println("Constructor MainMethodTest!!");
     }
    
     public static void main(String[] args) {
           System.out.println("Main method executed!!");
     }
}
Output: Main method executed!!

The constructor is not called while executing main method. Hence the instance of class is not created while execution of main method.

Wednesday, 27 July 2016

Create an annotation in Java

CustomAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
     int studentAge() default 21;
     String studentName();
     String stuAddress();
     String stuStream() default "CS";
}

How to use the field of Annotation in Java?

TestCustomAnnotation.java
package annotations;
import java.lang.reflect.Method;
public class TestCustomAnnotation {
     public static void main(String[] args) {
           new TestCustomAnnotation().testAnnotation();
     }
     @CustomAnnotation(
                studentName="Rajesh",
                stuAddress="Mathura, India"
     )
     public void testAnnotation() {
           try {
                Class<? extends TestCustomAnnotation> cls = this.getClass();
                Method method = cls.getMethod("testAnnotation");
               
                CustomAnnotation myAnno = method.getAnnotation(CustomAnnotation.class);
               
                System.out.println("Name: "+myAnno.studentName());
                System.out.println("Address: "+myAnno.stuAddress());
                System.out.println("Age: "+myAnno.studentAge());
                System.out.println("Stream: "+myAnno.stuStream());
               
           } catch (NoSuchMethodException e) {
           }
     }
}
Output:
Name: Rajesh
Address: Mathura, India
Age: 21
Stream: CS

Java Annotations

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Uses of Annotations:
Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
Runtime processing — some annotations are available to be examined at runtime.

Example of Java annotations:
To describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull.
To describe the "nature" of an element: e.g. @Entity, @TestCase, @WebService.
To describe the behavior of an element: @Statefull, @Transaction.
To describe how to process the element:  @Column, @XmlElement.

In all the above cases, annotations are used to describe the element and clarify its meaning.

Note:
Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. However it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.

Advantages of the annotation:
1) All the information is in a single file (no need to open two files to configure a given behavior).
2) When the class changes, no need to modify the xml file.

Tuesday, 19 July 2016

Longest Palindromic Substring

    Brute force

Time complexity: O ( n^3 )
Auxiliary complexity: O ( 1 ).

    Dynamic programming

Time complexity: O ( n^2 )
Auxiliary complexity: O ( n^2)

package geeks.dp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LongestPalindromeSubstring {
       private static int max = 0;

       public static void main(String[] argsthrows IOException {
           BufferedReader buffReader = new BufferedReader(
                                         new InputStreamReader(System.in));
           System.out.println("Input String !!");
           char[] inputChars = buffReader.readLine().toCharArray();
             
           int length = inputChars.length;
             
           int[][] dp = new int[length+1][length+1];
             
           for (int i = 1; i <= lengthi++) {
               for (int j = 1; j <=lengthj++) {
                   if(inputChars[i-1]==inputChars[length-j]) {
                        dp[i][j] = dp[i-1][j-1]+1;
                   } else {
                        dp[i][j] = 0;
                   }
                   max = Math.max(dp[i][j], max );
               }
          }
          System.out.println(max);
       }
}

Output:
Input String !!
geeksskeeggeeksskeeg
20
Related Posts Plugin for WordPress, Blogger...