Home Java javaTutorial Type transfer precautions in Java

Type transfer precautions in Java

Sep 12, 2024 am 10:16 AM

Java is a strongly typed language, but it is still possible to transfer values ​​between primitive variables of different types. For example, I can assign the value of an int to a double without any problems, as long as the storage capacity of the type receiving the value can handle it.

See below the size of each primitive type:

Cuidados com transferência de tipos em Java

Transferring value to a type with greater storage capacity has a technical name: "widening conversion". The term in Portuguese is usually translated as "enlargement conversion" or "widening conversion". It refers to the process in which a value from a smaller or more restricted data type is converted to a larger or more comprehensive type without loss of information.

But what if I want to transfer the value to a type with smaller storage capacity? The Java compiler doesn't like this, but it will allow it if you cast it, as in the example below.

double decimal = 65.9;
int i = (int) decimal; //aqui ele perde a casa decimal e vira 65
char c = (char) i; //aqui ele vira a letra A (que corresponde a 65)
Copy after login

If the size of the value that will go to the new type exceeds the limits of that type, something more dramatic can happen. An int i = 10 fits in a byte variable, as it contains 8 bits in a range from -128 to 127. However, what if I want to put an int i = 128 in a variable of type byte... there will be a loss of information .

public class Main
{
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte) i;

        System.out.println(b); // o valor de b agora é -128 :S
    }
}
Copy after login

Autoboxing

In the last post [read it here], I talked a little about the Wrapper classes. As an example, I had written Integer.parse(i) = imagine that i is a type
primitive int.

Currently, using the Wrapper parse method is no longer encouraged as it is deprecated. To transform a primitive into a Wrapper class and, in this way, use built-in methods, it is recommended to do "autoboxing", as in the example:

Character ch = 'a';
Integer i = 10;
Copy after login

Note that it is a more direct approach. Simply assign the value all at once.

To do the opposite and return the data as a primitive type, you can do the "unboxing" using the valueOf:
method

Integer i = 10;
int j = Integer.valueOf(i);
Copy after login

Making a Wrapper from a primitive, as I said in the previous post, has the advantage of allowing you to use the class's methods and making life easier when working with the data.

The wrapper version of a primitive may look a lot like it at first glance, but the JVM does not treat an object and a primitive in the same way, don't forget. Remember that primitives go to the Stack and objects to the Heap [remember here].

In terms of performance, it is clear that retrieving data from a primitive is less costly for the computer, since the value is stored directly, and not by reference. It's much faster to get a ready-made piece of data than to keep putting the pieces together in memory.

But there are cases where using a Wrapper will be essential. For example, when you want to work with the ArrayList class. It only accepts objects as parameters, not primitive values.

The flexibility that this transformation from primitive to object and vice versa brings is really cool about the language. But we need to be aware of these pitfalls discussed here and many others.

Just to shock society (lol) I'm going to give an example of a problematic case involving the unexpected behavior of a code when working with overloading (I haven't made a post about overloading yet, but I will. Basically, overloading occurs when a method has different signatures).

This case was mentioned in the book "Effective Java", by Joshua Bloch.

public class SetListTest {
    public static void main(String[] args) {
        Set<Integer> set = new TreeSet<>();
        List<Integer> list = new ArrayList<>();

        for (int i = -3; i < 3; i++) {
            set.add(i);
            list.add(i);
        }

        for (int i = 0; i < 3; i++) {
            set.remove(i);
            list.remove(i); // como corrigir: list.remove((Integer) i);
        }

        System.out.println(set + " " + list);

    }
Copy after login

In this program, the objective was to add integer values ​​from -3 to 2 [-3, -2, -1, 0, 1, 2] to a set and a list. Then delete the positive values ​​[0, 1 and 2]. But, if you run this code, you will notice that the set and the list did not present the same result. The set returns [-3, -2, -1], as expected. List returns [-2, 0, 2].

This happens because the call to the built-in remove(i) method of the List class treats i as a primitive type int, and nothing else. The method, in turn, removes elements at position i.

The call to the remove(i) method of the Set class calls an overload that receives an Integer object as a parameter, automatically converting i, which was originally an int, to Integer. The behavior of this method, in turn, excludes from the set elements that have a value equal to i (and not an index equal to i) - note that the expected type for both the set and the list was Integer. (Set set / List list). That's why the overloading chosen for the remove method, from the Set class, converted it to Integer.

While the behavior of remove in List is to delete by index, remove in Set is to delete by value. All due to overloading of remove that receives Integer.

The above is the detailed content of Type transfer precautions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles