R
R
Roman2016-07-06 10:51:20
Java
Roman, 2016-07-06 10:51:20

What methods to use for type conversion in Java?

I found 3 ways to convert String to int, but where is not explained how best to do it and why?
Using a constructor

try { 
        Integer i1 = new Integer("20349");
        System.out.println(i1);
    }catch (NumberFormatException e) {  
        System.err.println("Неверный формат строки!");  
    }

Using the valueOf method of the Integer class
String str1 = "1451";
    try {
        Integer i2 = Integer.valueOf(str1);
        System.out.println(i2);    
    }catch (NumberFormatException e) {  
        System.err.println("Неверный формат строки!");  
    }

Using the parseInt method of the Integer class
int i3 = 0;
    String str2 = "102944";
    try {
        i3 = Integer.parseInt(str2);
        System.out.println(i3);  
    } catch (NumberFormatException e) {  
        System.err.println("Неверный формат строки!");  
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-09-30
@GTech

No longer needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question