Tuesday, 26 December 2017

How to Convert String to int in Java

In Java we can convert string to integer with Integer.parseInt() function.

Syntax:
int in = Integer.parseInt(str); 

Example:


package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "4";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output:  4

Note:

In order to use Integer.parseInt() method, we should pass string numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException.


Example:
package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "Tutorial4u";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output: 


Exception in thread "main" java.lang.NumberFormatException: For input string: "Tutorial4u"

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.tutorial4u.StringToInt.main(StringToInt.java:6)

How to Convert String Array to List in Java

In java we have inbuilt function to convert String array to List.


Syntax :-

   Arrays.asList("Input string array");


Java String Array to List Example:

package com.tutorial4u;

import java.util.Arrays;
import java.util.List;

public class ArrayToList {
       public static void main(String[] args) {
             String[] str = {"Tutorial4u","Ashish"};
             List<String> list = Arrays.asList(str);
             System.out.println(list);
       }

}


Output:  [Tutorial4u, Ashish]

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...