Spring:Difference between @Controller and @RestController annotation

Posted on

  • Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations.
  • By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default.
  • When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

Let us understand this with an example:

@Controller
public class restClassName{

  @RequestMapping(value={"/uri"})
  @ResponseBody
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

@RestController
public class restClassName{

  @RequestMapping(value={"/uri"})
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

The above 2 codes both serve the same purpose.
Advertisements

Java: indexOf to find string occurrences

Posted on

String str = “tejuhelloreddytejuhello”;
String findStr = “teju”;
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {

       lastIndex = str.indexOf(findStr, lastIndex);

if (lastIndex != -1) {
count++;
        lastIndex += findStr.length();
}

}

System.out.println(count);

Java : How to find duplicate characters in String

Posted on Updated on

 

This program would find out the duplicate characters in a String and would display the count of them.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
 
    //Convert the String to char array
    char[] chars = str.toCharArray();
 
    /* logic: char are inserted as keys and their count
     * as values. If map contains the char already then
     * increase the value by 1
     */
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }
 
    //Obtaining set of keys
    Set<Character> keys = map.keySet();
 
    /* Display count of chars if it is
     * greater than 1. All duplicate chars would be 
     * having value greater than 1.
     */
    for(Character ch:keys){
      if(map.get(ch) > 1){
        System.out.println("Char "+ch+" "+map.get(ch));
      }
    }
  }
 
  public static void main(String a[]){
    Details obj = new Details();
    System.out.println("\nString: #@$@!#$%!!%@");
    System.out.println("-------------------------");
    obj.countDupChars("#@$@!#$%!!%@");
  }
}

Output:

String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2

Java : Checked Exceptions and Unchecked Exceptions

Posted on Updated on

Checked are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

//CheckedException
public class CheckedException {

public void method1()throws Exception{

}

public void method2() {

try {
method1();    // If no try catch block here , compiler will throw error
}catch(Exception e) {

}

}
}

//UnCheckedException
public class UnCheckedException {

public void method1()  throws NullPointerException{

}

public void method2() {
method1();   // No need to have try and catch block here , as it is runtime exception (or)  unchecked exception , JVM will take care .
}

}

Java : Serialization and De-serialization of a Java object

Posted on Updated on

Below is example for how to Serialize and DeSerialize java objects

// Java code for serialization and deserialization of a Java object

import java.io.*;

class Demo implements java.io.Serializable
{

public int a;
public String b;

// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}

}

class Test
{

public static void main(String[] args)
{
Demo object = new Demo(1, “geeksforgeeks”);
String filename = “file.ser”;

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object
out.writeObject(object);

out.close();
file.close();

System.out.println(“Object has been serialized”);

}

catch(IOException ex)
{
System.out.println(“IOException is caught”);
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object
object1 = (Demo)in.readObject();

in.close();
file.close();

System.out.println(“Object has been deserialized “);
System.out.println(“a = ” + object1.a);
System.out.println(“b = ” + object1.b);

}

catch(IOException ex)
{
System.out.println(“IOException is caught”);
}

catch(ClassNotFoundException ex)
{
System.out.println(“ClassNotFoundException is caught”);
}

}

}

Auto boxing and Unboxing in Java

Posted on Updated on

int a = 56;
Integer i = a; // Auto Boxing
Integer s = 45;
int a = s;// auto UnBoxing

Java :How to compare elements in two arrays

Posted on Updated on

Without java collections:

public class CompareArrays {
public static void main(String[] args) {

Integer[] arr1 = {4,7,3,9,2};
Integer[] 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]);
}
}
}

      }
}

With java collections : 

 import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CompareArrays {
public static void main(String[] args) {

Integer[] arr1 = {4,7,3,9,2};
Integer[] arr2 = {3,2,12,9,40,32,4};
Set set1 = new HashSet(Arrays.asList(arr1));
Set set2 = new HashSet(Arrays.asList(arr2));
set1.retainAll(set2);    // Intersection method 
Iterator it = set1.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

}
}