Convert Java strings to other types of values. Type Conversion in Java

This article:

  • written by the team. We hope that it will be useful to you. Happy reading!
  • this is one of the articles from our

Type conversion is a topic that may seem daunting to those new to Java programming. However, we assure you that everything is actually simple. The main thing is to understand what laws govern the interaction between variables and remember this when writing programs. So, let's figure it out.

There are 2 types of transformations in Java - the picture will help you:

Recall that the entire “Java Universe” consists of:

  • primitive types (byte, short, int, long, char, float, double, boolean)
  • objects

In this article we:

  • consider type conversion for primitive variable types
  • conversion of objects (String, Scanner, etc.) is not considered in this article, since a separate “magic” happens to objects - this is a topic for a separate article.
Automatic conversion

Well, let's try to figure out what "automatic conversion" is.

Remember, when we looked at variable types (in the article), we said that a variable is some kind of “container” , which can store the value for further use in a programme. We also talked about the fact that each type of variable has its own range acceptable values and the amount of memory occupied. Here is the sign where it was all written out:

So this is what we are actually getting at. Besides, it’s not just that you were given ranges of acceptable values ​​and the amount of memory occupied :)

Let's compare, for example:

1. byte and short. byte has a smaller range of valid values ​​than short. That is, byte is like a smaller box, and short is a larger box. And that means we can put a byte into a short.

2. byte and int. byte has a smaller range of valid values ​​than int. That is, byte is like a smaller box, and int is like a larger box. And that means we can put byte into int.

3. int and long. int has a smaller range of valid values ​​than long. That is, int is like a smaller box, and long is like a larger box. And that means we can put int into long.

This is an example of automatic conversion. This can be schematically depicted in the form of a picture like this:

Let's look at how this works in practice.

Example No. 1

Code No. 1 - if you run this code on your computer,

class Test ( public static void main(String args) ( byte a = 15; byte b = a; System.out.println(b); ) )

class Test(

byte a = 15 ;

byte b = a ;

Code No. 2 - if you run this code on your computer, the number 15 will be displayed in the console

class Test ( public static void main(String args) ( byte a = 15; int b = a; System.out.println(b); ) )

class Test(

public static void main (String args) (

byte a = 15 ;

int b = a ;

System. out . println(b);

Eeyore? Do you think that times the same number was output to the console, and code No. 1 differs from code No. 2 only in the type of variable b , then there is no difference between them? E that's not true.

Code No. 2 contains automatictype conversion , but in code No. 1 - no:

Although the number is, in principle, the same, it is now in b O a larger container that takes up more disk space. In this case, the JVM performs automatic conversions for you. She knows that int more than byte .

Cast

It's a different matter if you're trying to transfer something from a larger container to a smaller one.

You may know that the larger container contains something that can fit in the small one - but the JVM does not know about this and tries to protect you from errors.

Therefore, you must “plainly say” that the situation is under control:

class Test ( public static void main(String args) ( int a=0; long b=15; a = (int) b; ) )

class Test(

public static void main (String args) (

int a = 0 ;

long b = 15 ;

a = (int) b;

Here we have added (int) before b. If the variable a was, for example, like byte, in brackets there would be (byte). The general formula looks like this:

She says "make of (more) meaning b a variable of the type I need (target) int ".

If something went wrong.

Before this, we approached situations assuming that we knew exactly what we were doing. But what if you try to put something into a container that doesn’t fit there?

It turns out that only what “fits” in there will remain in the container. For example, floating point numbers will be “cut off” fraction:

//example 1 class Test ( public static void main(String args) ( double a=11.2345; int b=(int)a; System.out.println(b); // the console will display the number 11 ) )

//example 1

class Test(

public static void main (String args) (

double a = 11.2345 ;

int b = (int ) a ;

System. out . println(b); // the console will display the number 11

We must remember that the fractional part not rounded, A discarded.

What happens if we try to place a number that is outside the allowed range? For example, if you put the number 128 in byte (byte range from -128 to 127)? Do you think we'll get 1? No. We get -128:

class Test ( public static void main(String args) ( double a=128; byte b=(byte)a; System.out.println(b); //we will see -128 in the console) )

The value of a variable with such a transformation can be calculated, but the programmer's goal is to prevent a situation where the value goes beyond the permissible limits, since this can lead to incorrect operation of the program.

Tasks:
  1. Consistently write in the compiler the conversions of all primitive types to each other, including the char and types. Make a table like this:
byte short char int long float double boolean
byte
short
char
int
Long
Float
double
boolean

At the intersection write: a - if the conversion occurs automatically, on - if you need to use an explicit conversion, x - if the conversion is impossible.

* casting a type to itself is called identical– it is not necessary to register it

  1. Look again at what size each primitive type is. Try to make a flowchart showing which types go where. Draw arrows labeled “expanding transformation” and “constricting transformation.”
Questions

During an interview for the position of Junior Java Developer, you may be asked:

What do you know about converting primitive data types, is there data loss, is it possible to convert a boolean type?

Try to answer the question.

Let's summarize:
  • If you "put" the contents of a smaller container into a larger container, the conversion occurs automatically and no errors should occur.
  • If there is a need to put “a value from a larger container into a smaller one,” you need to be careful and use explicit type casting.
  • When casting float or double to integral types, the fractional part is not rounded, but simply discarded.
  • The type boolean is not castable to any type.
  • The type char is cast to numeric types, as a character code in the UNICODE system.
  • If the number is larger than its container, the result will be unpredictable.

This article describes only part of the material on the topic of type casting. There are also casts of object types, casts to a string (after all, anything can be written in a string, right?), and automatic promotion types in expressions.

We hope that our article was useful to you. There is also the opportunity to enroll in our Java courses in Kyiv. We teach from scratch. Detailed information You can find it on our website.


Approximate level necessary knowledge: Java Syntax quest and a little Java Core.

At the end of the first JavaRush quest we learn about type conversion. In the level 10 lectures, you could see that converting an int to a String is very simple, and in general, almost any primitive type can be converted to String without problems.

int x = 5 ;

String text = "X=" + x; Also, those who have already completed level 10 of the Java Syntax quest know that it is impossible to convert a reference to a number to a reference to a string. So what's the best way to convert a string to a primitive integer? It is better to do this using the parseInt method of the Integer class. The parseInt method must convert a String to an int and throws a NumberFormatException if the string cannot be converted to an int type. Example The basic line that converts a string to an integer: int i = Integer. parseInt(myString); If the string represented by the myString variable is a valid integer, such as "1", "200", Java will quietly convert it to the primitive data type int . If for some reason this fails, doing so may throw a NumberFormatException, so we need a little more code to make the program work correctly for any string. A program that demonstrates the Java String to int conversion method, managing for a possible NumberFormatException: public class JavaStringToIntExample ( public static void main (String args) ( // String s = "fred"; //use this if you need to test //the exception below String s = "100" ;

try (

// this is where String is converted to int int i = Integer. parseInt(s. trim()); code: int i = Integer. parseInt (s. trim () ) But sometimes converting a string to a number just won’t work. In our example, such a string is the name fred. We can talk about codes in which letters are written on a computer, but, formally speaking, fred is not a number, and it is better to leave it as a string. Our program is designed so that when it tries to convert "fred" to a number, the Integer parseInt process will throw a NumberFormatException, which you must handle in a try/catch block. In this case, you don't have to use the trim() method of the String class, but in real programming you should use it. So we showed it to you. Since this topic has come up, here are some “hints” on the topic of String classes and Integer:
  • Integer.toString(int i) is used to convert int to Java strings.
  • If you want to convert a String object to an Integer object (rather than the primitive int class), use the valueOf() method on the Integer class instead of the parseInt() method.
  • If you need to convert strings into additional primitive Java fields, use methods like Long.parseLong() and similar ones.
Author of the answer: Alice Watson

Frequently asked question on String/int types in Java: How to convert String type to Int type?

Solution: Using the parseInt class method Java Integer. The parseInt method converts the String type to an Int, and throws a NumberFormatException if the string cannot be cast to an integer value.

Let's look at two short examples.

1. Simple example of “string to integer” conversion in Java

Ignoring the exception that might occur, everything that needs to be done to convert a String to an int fits into one line of code:

int i = Integer.parseInt(myString);

If the string represented by myString is a valid integer, such as “1”, “200”, etc., it will be cast to type int . If the conversion fails, a NumberFormatException will be thrown. So your code needs to be a little longer to take this into account, as shown in the following example.

2. Complete example of converting String to int

Below is full code example program. It demonstrates the process of converting a string to an integer in Java and handling a possible NumberFormatException:

public class JavaStringToIntExample( public static void main (String args) ( // String s = "fred"; // Use this line for an exception test String s = "100"; try ( // converting String to int is done here int i = Integer.parseInt(s.trim());// print the value after conversion System.out.println("int i = " + i); ) catch (NumberFormatException nfe) ( System.out.println("NumberFormatException: " + nfe.getMessage()); ) ))

Explanation

In the above example, the Integer.parseInt(s.trim()) method is used to translate the string s to an integer i in the following line of code:

int i = Integer.parseInt(s.trim());

If the conversion attempt fails ( for example if you are trying to cast the string fred to an integer type), then the parseInt method of the Integer class will throw a NumberFormatException, which must be handled in a try/catch block.

In this example, you don't actually need to use the trim() method of the String class. But in real programs it will be needed, so I applied it here.

Additional Notes

While we're on the subject, here are a few notes about the String and Integer classes:

  • The Integer.toString(int i) method is used to convert from int type to Java String class.
  • To convert a String object to an Integer object, use the valueOf() method of the Integer class instead of parseInt() .
  • If you need to cast strings to other primitive Java types, such as long, use the Long.parseLong() methods, etc.

Summary

Hope this example of converting String to int in Java was helpful. If you have questions or comments, leave them in the comments.

Translation of the article “ How to convert a Java String to an Int” was prepared by the friendly project team.

Good bad

    The Integer class is a container for the int data type. This class includes methods for converting values ​​from a string to an Integer object. This manual contains...