Comprehensive programming learning site SAMURAI ENGINEERING SCHOOL blog logo BLOG blog SERVICE Business content COMPANY Company Profile RECRUIT Employment information Free trial lesson home interview curriculum tutorial Learning column Learning plan diagnosis Free study consultation Python, freelance
Slide show
Blog Top> Programming> Java> Getting Started with Java [Java] Convert String type to int type Otake Otake 2017/1/24
2019/6/4
Hello! It is a freelance OTAKE.
Do you guys remember how to convert Java strings to int type?
Also, do you remember how to convert an int type number to a string? Do you know what happens if the conversion fails? You can easily learn how to convert Java strings to int type by reading this article!
In this article, how to convert a string to an int type
How to convert from String type to int type How to convert from String type to other numeric type How to convert from numeric type to String type Check if the value of String type is a number I will also explain the specific contents such as. This time, I will explain how to use it in an easy-to-understand manner on how to convert a character string to an int type!
Contents of this article
1 List of type conversion methods between String type and numeric type 2 How to convert from String type to int type (parseInt) 3 How to convert from String type to other numeric type 3.1 Conversion to byte type (parseByte) 3.2 Conversion to short type and long type (parseShort, parseLong) 3.3 Conversion to Float, Double (parseFloat, parseDouble) 3.4 How to use the valueOf method 4 How to convert from numeric type to String type 4.1 How to use valueOf 4.2 How to use toString 5 Check if the value of String type is a number 5.1 Exception handling with try-catch statement 5.2 Check with regular expression Click here for a summary article on how to use 6 String 7 Summary List of type conversion methods between String type and numeric type The method and writing method of Sting type ⇔ numerical type conversion are summarized in the table.
Type before conversion Type method after conversion Example of how to write String int Integer.parseInt Integer.valueOf Integer.parseInt("1") Integer.valueOf(“1”) byte Byte.parseByte Byte.valueOf Byte.parseByte(“1”) Byte.valueOf(“1”) short Short.parseShort Short.valueOf Short.parseShort(“1”) Short.valueOf(“1”) long Long.parseLong Long.valueOf Long.parseLong(“1”) Long.valueOf(“1”) float Float.parseFloat Float.valueOf Float.parseFloat(“1”) Float.valueOf(“1”) double Double.parseDouble Double.valueOf Double.parseDouble(“1”) Double.valueOf(“1”) Numeric type (int, byte, short, long, float, double) String String.valueOf String.valueOf (1) int String Integer.toString Integer.toString(1) byte String Byte.toString Byte.toString((byte)1) short String Short.toString Short.toString((short)1) long String Long.toString Long.toString(1l) float String Float.toString Float.toString(1.0f) double String Double.toString Double.toString(1.0) You can use methods such as parseInteger, paraseByte, and parseFloat and valueOf methods to convert from String type to numeric type. You can use the valueOf method and toString method to convert from numeric type to string type.
Let's check each usage example with sample code.
How to convert from String type to int type (parseInt) To convert a character string to an int type number, use the sample code below.
It can be converted to int type by using parsInt and valueOf of Integer class.
public class Main { public static void main(String[] args) {
String hoge = "1";
int num = Integer.parseInt(hoge);
System.out.println(num);
}
} Execution result:
1 How to convert from String type to other numeric type You can convert a string to a number by using a method that suits your purpose.
Conversion to byte type (parseByte) To convert a character string to a byte type number, write the following code. It can be converted to byte type by using parseByte of Byte class.
public class Main { public static void main(String[] args) {
String hoge = "1";
byte result = Byte.parseByte(hoge);
System.out.println(result);
}
} Execution result:
1 Conversion to short type and long type (parseShort, parseLong) In the case of short type and long type, it will be as follows. For conversion to short type, use the parseShort method of the Short class.
To convert to long type, use parseLong method of Long class.
public class Main { public static void main(String[] args) {
String hoge = "1";
short result1 = Short.parseShort(hoge);
System.out.println(result1);
long result2 = Long.parseLong(hoge);
System.out.println(result2);
}
} Execution result:
1 1 Conversion to Float, Double (parseFloat, parseDouble) As with the conversion to byte type and int type, use the following to convert to a decimal point. Use the Float.parseFloat method to convert to the float type.
And the conversion to double type uses the Double.parseDouble method.
public class Main { public static void main(String[] args) {
String hoge = "1";
float result1 = Float.parseFloat(hoge);
System.out.println(result1);
double result2 = Double.parseDouble(hoge);
System.out.println(result2);
}
} Execution result:
1.0 1.0 How to use the valueOf method There is a valueOf method in each of the Integer, Short, and Long classes just described. You can use this method to convert a string to a variable.
When the valueOf method of each type class is used, the return value is returned with the same type as that type class.
public class Main {
public static void main(String[] args) {
String hoge = "1";
System.out.println(Integer.valueOf(hoge));
System.out.println(Byte.valueOf(hoge));
System.out.println(Short.valueOf(hoge));
System.out.println(Long.valueOf(hoge));
System.out.println(Float.valueOf(hoge));
System.out.println(Double.valueOf(hoge));
}
} Execution result:
1 1 1 1 1.0 1.0 In this sample code, for example, the valueOf method of Integer is called first, so after calling it, it is converted to the Integer class.
How to convert from numeric type to String type Next, let's see how to convert a number to a string.
How to use valueOf Let's see how to convert it to a string using a method called valueOf.
I explained that valueOf is used in "Conversion from string to number" earlier. You can use valueOf in the conversion from a number to a string as well.
public class Main { public static void main(String[] args) {
int num = 1;
String str = String.valueOf(num);
System.out.println(str);
}
} Execution result:
1 In this sample code, an int type variable is converted to a string using the String.valueOf method.
How to use toString Classes such as the Integer class and Float class have a toString method, which can be used to convert to a string.
public class Main {
public static void main(String[] args) {
System.out.println(Integer.toString(1));
System.out.println(Byte.toString((byte)1));
System.out.println(Short.toString((short)1));
System.out.println(Long.toString(1l));
System.out.println(Float.toString(1.0f));
System.out.println(Double.toString(1.0));
}
} Execution result:
1 1 1 1 1.0 1.0 If you call the toString method in the form of this sample code, it will be converted to a string and returned.
Check if the value of String type is a number Let's take a look at the sample code to see what happens if the type conversion is not possible.
public class Main {
public static void main(String[] args) {
System.out.println(Integer.parseInt("aa"));
System.out.println(Integer.valueOf("aa"));
}
} If you try to run this sample code, you will get an exception or compilation error and you will not be able to run it. It must be the correct number when passed to the argument. Therefore, let's check whether the value of String type is a numerical value before performing type conversion.
There are two ways to check if a String value is a number. Exception handling with try-catch statement Check with regular expression
Let's take a closer look at each method. You can also use Apache Commons Lang's NumberUtils # isNumber method, but since it is not a standard library, I will omit the explanation.
Exception handling with try-catch statement In the try-catch statement, if the value of String is not a numerical value, describe to perform exception handling.
public class Main {
public static void main(String[] args) {
try {
System.out.println(Integer.parseInt("-10"));
System.out.println(Integer.valueOf("aa"));
} catch (NumberFormatException e) {
System.out.println(e);
}
}
} Execution result:
-10 java.lang.NumberFormatException: For input string: "aa" In this sample code, the Integer.parseInt method argument string is numeric, but the Integer.valueOf method argument string is not.
The try-catch statement describes exception handling when the argument string is not a numeric value.
Check with regular expression Here's how to specify a regular expression pattern and check if the string is a number.
import java.util.regex.Matcher; import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str1 = "-10";
String str2 = "aa";
// Regular expression settings String regex = "^-?[0-9]*$"; Pattern p = Pattern.compile(regex); Matcher m1 = p.matcher(str1); Matcher m2 = p.matcher(str2);
if(m1.find()) {
System.out.println(Integer.parseInt(str1));
}
if(m2.find()) {
System.out.println(Integer.valueOf(str2));
}
}
} Execution result:
-10 In this sample code, the string type variable regex specifies the regular expression pattern as an integer including negative values.
If it matches the integer regular expression pattern, it is converted to an integer value and displayed as output. If they do not match, the output is not displayed.
Please refer to the detailed explanation here for how to write a pattern that checks a character string with a regular expression.
[Regular expression in Java] How to write a pattern to check a character string and a sample Updated: April 23, 2019 Click here for a summary article on how to use String You can read more about how to use String here, so be sure to check it out!
[Java String] Let's understand string operations with 7 basic usages Updated: May 7, 2019 Summary This time, I explained how to convert a character string to an int type, but how about it?
Use methods such as parseInteger, paraseByte, parseFloat and valueOf methods to convert from String type to numeric type. Use valueOf or toString for strings from numbers.
If you forget it, please remember this article!
Send by LINE
Recommended for those who want to change jobs to IT engineers I want to change jobs to a company that evaluates me and raise my annual income! I want to know a unique project that suits my skills! Engineers are one of the hottest professions right now. There are many engineers who want to become engineers and increase their annual income, or who want to change jobs to a company that suits your skills.
However, even if the number of job offers handled by major career change media is large, the competition rate is quite high because everyone is registered. Therefore, even if you find a company that meets your requirements, it will take some effort and skill to change jobs.
With these media, it is not the best environment for changing jobs for those who are aiming to become engineers from inexperienced people or those who are thinking of changing jobs after 2 to 3 years of engineering experience.
Therefore, I would like to recommend "Samurai Works," which has many unique projects for inexperienced people and young engineers.
Samurai Works not only publishes many unique projects, but also
・ Consistent support from application to employment ・ After-sales follow-up after work
We have a safe follow-up system for those who are inexperienced or who are aiming to become engineers for the first time. Of course registration is completely free! Moreover, if you just want to see the matter, you do not need to register.
First of all, please feel free to see what kind of jobs are available. You will surely find the perfect company for you! View job listings for Samurai Works Otake Otake 30 years old, freelance programmer. Interested in programming since junior high school and experienced game development and website construction Weepingly pleased that we are interested in new frameworks and libraries and include innovative features.
See all articles Well read after this article!
Java [Introduction to Java] How to use switch-case statements 2017/3/27
2017/6/7
Java [Introduction to Java] Explaining how to use interfaces and implements from the basics! 2017/4/19
2019/4/16
Java [Introduction to Java in 5 minutes] How to use Map containsKey and speed summary 2017/3/7
2019/10/23
Java What is the difference between Java and JavaScript? Thorough analysis with four easy-to-understand differences 2017/9/2
2019/11/7
Java [Introduction to Java] How to compare String type strings with equals 2017/3/13
2017/12/15
Java [Introduction to Java] How to use Logger (explains log level and output destination settings) 2018/6/27
2019/5/2
Category Top interview Learning column curriculum tutorial Learning diagnosis Free study consultation curriculum Introduction to programming Getting Started with Ruby Getting Started with Swift Getting Started with Java Getting Started with Python Getting Started with JavaScript Operating company Company Profile Message from the President Employment information Contact Us privacy policy SAMURAI ENGINEERING SCHOOL blog logo facebook twitter youtube ©Samurai, Inc. All Rights Reserved.
Recommended Posts