Maison> Java> javaDidacticiel> le corps du texte

Déballage en Java

王林
Libérer: 2024-08-30 15:09:02
original
746 Les gens l'ont consulté

Unboxing est un processus de conversion d'un objet de la classe wrapper en JAVA en un type de données primitif. Il est présent dans le package « java.lang » et peut être utilisé dans les programmes jAVA après l'importation de ce package. Par exemple, convertir l’objet de la classe wrapper Integer en Int. C'est l'inverse de l'autoboxing en JAVA. Il a été introduit dans le cadre du développement dans JAVA 5, facilitant grandement la vie du développeur.

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Syntaxe

La syntaxe utilisée pour le déballage en JAVA est fournie ci-dessous :

import java.lang.* class mainClass { public static void main (String args[] ) { Integer variableName=new Integer( VariableValue); variableName2 = variableName; //Unboxing in JAVA } }
Copier après la connexion

Ici, l'objet de la classe wrapper « Integer » est affecté au type de données primitif Int et la valeur est passée en paramètre dans le constructeur de la classe wrapper. Cela se produit implicitement dans l'autoboxing.

Comment fonctionne le déballage en Java ?

Unboxing est le processus de conversion d'un objet en un type de données primitif. Ce processus est effectué automatiquement par le compilateur JAVA car les bibliothèques de JAVA le prennent en charge dans JAVA 5e édition et au-delà. Deux conditions préalables doivent être remplies pour que le déballage puisse être exécuté par le compilateur JAVA. Ces deux prérequis sont répertoriés ci-dessous :

  1. Le compilateur utilise le déballage lorsque l'objet de la classe wrapper utilisée attend une « valeur » du type de données primitif associé.
  2. L'objet de la classe wrapper utilisée est, à son tour, affecté à la variable du type de données primitif.

Vous trouverez ci-dessous le tableau contenant la classe wrapper et son type de données primitif associé :

Wrapper class Related primitive data-type
Boolean boolean
Integer Int
Float float
Character char
Byte byte
Long long
Short short
Double double

The data flow and explanation of unboxing in JAVA is explained properly with examples in the below section.

Examples of Unboxing in Java

Some examples are provided below will provide a conceptual clarity of the unboxing technique.

Example #1

Code:

public class test1 { public static void main(String args[]) { Integer var1=new Integer(50); if( var1 > 10) // Unboxing using comparator. { int var2=var1 + 10; int var3=var2; System.out.println(" The value of variable using unboxing functionality is JAVA is :"+ var3); } else { int var2=var1 - 10; //Unboxing using assignment operator. int var3=var2; System.out.println(" The value of variable using unboxing functionality is JAVA is :"+ var3); } } }
Copier après la connexion

Output:

Déballage en Java

Explanation: In this program, The main class is declared as “test1” as it contains the main() method. The program execution starts with the main() function. An object of the wrapper class “Integer” is created with the name “var1” and assigned with the value “50”. You should focus on the syntax of assigning value to variable “var1”, which is different in comparison to autoboxing. Here, the object is used instead of the data type for declaration and assignment purposes. Once the assignment is done, unboxing is done for that object.

Here, a comparison operator is used to unboxing the object. “If” logic checks if the value of “var1” is more than 10 or not. If not, then the control flows to another part of the program, starting with the “else” keyword and the whole code snippet under if loop will be skipped. In the else section, there is no comparator operator, so it enters the control logic. Assignment operator “=” does the unboxing part in case else is invoked. You can change the value of “var1” by changing the parameter provided to the wrapper class’s constructor (“Integer()” in this example). Finally, value is added or subtracted and printed as per logic.

Example #2

Code:

public class test2 { public static void main(String args[]) { Character charName = 'M'; // Autoboxing. char charName2 = charName; // Unboxing System.out.println("The process used here is auto-unboxing to display the character : "+ charName2 ); } }
Copier après la connexion

Output:

Déballage en Java

Explanation: Here, unboxing is done using the assignment operator. The data flow and control execution will work, as explained in the previous example. Here one thing to notice is that we have not used the object of a wrapper class to declare and assign the value to the variable “charName”. Although unboxing is done on “charName” using the assignment operator.

Example #3

Code:

public class test3 { public static void main (String args[]){ Integer varName = new Integer("1000"); int varName2 = varName.intValue(); System.out.println("Variable name is printed after unboxing using a built-in function is : " + varName2); } }
Copier après la connexion

Output:

Déballage en Java

Explanation:This works similar to the previous example with an added function called “intValue(). This function should extract the value from the variable “varName” and assign it to another variable named “varName2”. The function “intValue()” explicitly returns the value of object ”varName”. This is exactly what the compiler does in the backend. You should try removing this function and see the results to compare it with example number 2.

Advantages

Some of the primitive advantages of unboxing in JAVA is presented in the form of the list below:

  1. It represents the true use of JAVA’s object-oriented features.
  2. Standard code and syntax style used throughout the project but increased the number of lines in code.
  3. Cleaner and understandable code.
  4. Easy to maintain by the AMS (Application maintenance support) team for big projects.

Conclusion

Unboxing is the reverse of autoboxing in JAVA. It is converting the wrapper class’s object into a primitive data type. Although we have the functionality of declaring and assigning variables using primitive data type directly (That is called the autoboxing feature of JAVA), objectification of wrapper class and then assigning this object to a primitive data type is used several times when standardization of code is important. This reveals the true object-oriented property of JAVA. It is used mostly in big projects for easy maintenance.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!