Tuesday, 1 July 2014

StringBuffer

StringBuffer is like a string, but it is mutable. I.e, it can be modified. StringBuffer is final, so it can't be extended.

String Buffer is thread safe. The necessary methods in StringBuffer are synchronized.

Every string buffer has a capacity. Whenever the characters in string reaches the capacity, the capacity automatically made larger.





Prevoius                                                 Next                                                 Home

Monday, 30 June 2014

Simple Testing tool using Annotations

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }

public class TestClass {
    @Test public static void m1() { }
  
    public static void m2() { }
  
    @Test public static void m3() {
        throw new RuntimeException("Boom");
    }
  
    public static void m4() { }
  
    @Test public static void m5() { }
  
    public static void m6() { }
  
    @Test public static void m7() {
        throw new RuntimeException("Crash");
    }
  
    public static void m8() { }
}

import java.lang.reflect.*;

public class RunTests {
   public static void main(String[] args) throws Exception {
      int passed = 0, failed = 0;
      for (Method m : Class.forName(args[0]).getMethods()) {
         if (m.isAnnotationPresent(Test.class)) {
            try {
               m.invoke(null);
               passed++;
            } catch (Throwable ex) {
               System.out.printf("Test %s failed: %s %n", m, ex.getCause());
               failed++;
            }
         }
      }
      System.out.printf("Passed: %d, Failed %d%n", passed, failed);
   }
}

Compile all the java files.

Run the below command

java RunTests TestClass

Output
Test public static void TestClass.m3() failed: java.lang.RuntimeException: Boom

Test public static void TestClass.m7() failed: java.lang.RuntimeException: Crash

Passed: 2, Failed 2


Prevoius                                                 Next                                                 Home

@Documented

@Documented is a meta-annotation. You apply @Documented when defining an annotation, to ensure that classes using your annotation show this in their generated JavaDoc.

Example : Lets generate java doc for a java file using Annotations and using javadoc.

Using Documentation Comments
/**
 *  Author : Krishna
 *  Date : June 17th 2014
 *  Current Version : 1
 *  Last Modified : June 17th 2014
 *  Reviewers : Raghav
 */
public class SampleFile{

}
Run the below command
javadoc SampleFile.java.

You can get the documentation like below.

Using @Documented
import java.lang.annotation.*;

@Documented
public @interface AuthorDetails{
 String author();
 String date();
 int currentVersion() default 1;
 String lastModified() default "N/A";
 String[] Reviewers();
}

@AuthorDetails(
 author = "Krishna",
 date = "June 17th 2014",
 currentVersion = 1,
 lastModified = "June 17th 2014",
 Reviewers = {"Raghav", "Krishna"}
)
public class SampleFile{

}

Run the below command
javadoc SampleFile.java.

You can get the documentation like below.

Annotation @Documented is used to make the information in @AuthorDetails appear in Javadoc-generated documentation.



Prevoius                                                 Next                                                 Home

Sunday, 29 June 2014

@FunctionalInterface

A Functional interface is the one which has only one abstract method. The method declared in functional interface must not a public member of Object class.

The annotation type FunctionalInterface is used to indicate that an interface is meant to be a functional interface.

@FunctionalInterface
interface Interface1{
 Object getObject();
 int getABC();
}

When you tries to compile the above interface , compiler throws below error. Since Interface1 contains two abstract methods.

Interface1.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  Interface1 is not a functional interface
    multiple non-overriding abstract methods found in interface Interface1
1 error

1. The following interface is not functional because it declares nothing which is not already a member of Object

@FunctionalInterface
 interface NonFunc {
 boolean equals(Object obj);
}

2. Below Program compiles fine. Since return types are covariantly equivalent, Interface2 Overrides the method in Interface1.
@FunctionalInterface
interface Interface1{
 Object getObject();
}

@FunctionalInterface
interface Interface2 extends Interface1{
 String getObject();
}

Related Links




Prevoius                                                 Next                                                 Home

@Repeatable

@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

It is much helpful when you have multiple fields declared in an annotation. For example:

@Repeatable
public @interface Role {
   String type;
   String[] allowed;
}

In this case, it is much easier to use this kind of annotation for multiple roles:

@Role(type="readonly", allowed={"view"})
@Role(type="admin", allowed={"view,add,update,delete"})
public boolean checkAllowed() {
}




Prevoius                                                 Next                                                 Home

@SafeVarargs

A variable arity parameter(Varargs) with a non-reifiable element type can cause heap pollution and give rise to compile-time unchecked warnings. Such warnings are uninformative if the body of the variable arity method is well behaved with respect to the variable arity parameter.

import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}
When you tries to compile the above program, compiler throws below warning messages.

Note: SafeVarargsEx.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

To suppress the above warnings use @SafeVarargs Annotation.

import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 @SafeVarargs
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}

Output
Hi

1. It is a compile-time error if a fixed arity method or constructor declaration is annotated with the annotation @SafeVarargs.

import java.util.*;
import java.lang.*;

class SafeVarargsEx1{
 @SafeVarargs
 static void call(List<String> stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
 
  myList1.add("Hi");
  
  call(myList1);
 }
}

When you tries to compile the above program, compiler throws below error.

SafeVarargsEx1.java:6: error: Invalid SafeVarargs annotation. Method call(List<S
tring>) is not a varargs method.
        static void call(List<String> stringLists) {
                    ^
SafeVarargsEx1.java:7: error: array required, but List<String> found
                String s = stringLists[0].get(0);
                                      ^
2 errors

2. @SafeVarargs is only applicable to static methods, final instance methods, and constructors, the annotation is not usable where method overriding occurs.

import java.util.*;
import java.lang.*;

class SafeVarargsEx2{
 @SafeVarargs
 void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }
}

When you tries to compile the above program, compiler throws below error.

SafeVarargsEx2.java:6: error: Invalid SafeVarargs annotation. Instance method call(List<String>...) is not final.
        void call(List<String>... stringLists) {
             ^
1 error





Prevoius                                                 Next                                                 Home

@Deprecated

A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.

A Java compiler produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with @Deprecated is used.

import java.util.*;

public class DeprecatedEx{    
 
 public static void main(String args[]){
  byte b[] = {1,2,3,4,5};
  String s  = new String(b, 3);
 }
}

When you tries to compile the above program, compiler throws below warning.  
Note: DeprecatedEx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

Since program used the deprecated String Constructor.

You can suppress the compiler warnings by @SuppressWarnings Annotation.

1. Use of the @Deprecated annotation on a local variable declaration or on a parameter declaration has no effect.



Prevoius                                                 Next                                                 Home