How can I convert a String variable to a primitive int in Java

0 votes

I want to convert a String(having just numbers) to int. For Example: "100" to be converted to a numeric 100. So that I can perform Arithmetic operations on it.

Apr 12, 2018 in Java by parth295
• 4,640 points
188 views

2 answers to this question.

0 votes

You can convert a String to int by using a function:

int num= Integer.parseInt(string);

For Example:

String s="100";
int i=Integer.parseInt(s);

You can convert a String to Integer by using a function:

int num=Integer.valueOf(string);

String s="100";
int i=Integer.valueOf(s);
answered Apr 12, 2018 by sharth
• 3,350 points
0 votes

 Here are two ways illustrating this:

Integer x = Integer.valueOf(str);// orint y = Integer.parseInt(str);

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

answered Aug 20 by Sirajul
• 38,420 points

Related Questions In Java

0 votes
2 answers
+15 votes
18 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7 in Java by Suresh
• 700 points
89,115 views
0 votes
2 answers

How to convert an int array to string using tostring method in java?

Use java.util.Arrays: String res = Arrays.toString(array); System.o ...READ MORE

answered Aug 16 in Java by Sirajul
• 38,420 points
258 views
0 votes
2 answers

How to convert a JSON String into Object in Java?

You could probably check out Google's Gson: ...READ MORE

answered Aug 21 in Java by Sirajul
• 38,420 points
408 views
0 votes
2 answers

Integer to String conversion in java

We can do this in 2 ways: String ...READ MORE

answered Jul 27, 2018 in Java by samarth295
• 2,190 points
83 views
0 votes
3 answers

String to Double conversion in java

Double temp = Double.valueOf(str); number = temp.doubleValue(); READ MORE

answered Sep 10, 2018 in Java by Sushmita
• 6,880 points
60 views
0 votes
4 answers

Remove extra spaces from string in java

import java.util.regex.Matcher; import java.util.regex.Pattern; String pattern="[\\s]"; String replace=""; part="name=john age=13 year=2001"; Pattern ...READ MORE

answered Sep 10, 2018 in Java by parth295
• 4,640 points
120 views
0 votes
1 answer

Formatting Double Value in Java

An alternative is to use String.format: double[] arr = ...READ MORE

answered May 15, 2018 in Java by Rishabh
• 3,540 points
76 views
0 votes
2 answers

How can I convert byte array into hex string in Java?

public static String byteArrayToHex(byte[] a) { ...READ MORE

answered Aug 29 in Java by Sirajul
• 38,420 points
570 views
0 votes
3 answers

How to reverse a string in java?

public static String reverse(String s) { ...READ MORE

answered Aug 16, 2018 in Java by samarth295
• 2,190 points
92 views