>  기사  >  Java  >  Java의 오토박싱

Java의 오토박싱

WBOY
WBOY원래의
2024-08-30 15:58:00923검색

오토박싱은 JAVA에서 따르는 프로세스로, 기본 데이터의 변환이 컴파일러에 의해 객체 유형으로 변환됩니다. 따라서 예를 들어 변수가 "int"로 선언되면 변수는 해당 형식에서 사용되는 컴파일러에 의해 기본 정수에서 개체 데이터 형식으로 변환됩니다. "언박싱"이라고 불리는 오토박싱의 반전 프로세스가 하나 더 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

정의: 기본 데이터 유형의 값을 해당 래퍼 클래스의 객체로 변환하는 것을 오토박싱이라고 합니다.

구문

오토박싱에 사용되는 구문은 다음과 같습니다.

primitive_DataType variableName = 'VariableValue';

Java에서 Autoboxing은 어떻게 작동하나요?

JAVA 컴파일러는 기본 데이터 유형을 가져와 이를 래퍼 클래스의 객체로 변환합니다. 그러면 컴파일러는 아래 두 가지 사항이 충족되는 경우에만 작동합니다.

  1. 변수는 래퍼 클래스의 객체 생성을 예상하는 함수에 매개변수로 전달됩니다.
  2. 컴파일러가 오토박싱을 수행할 수 있도록 변수에 기본 값이 할당됩니다.
  3. 모든 기본 데이터 유형은 해당 래퍼 클래스에 연결되어 있습니다(이는 라이브러리에 저장된 JAVA에 의해 이미 수행되었습니다). 기본 데이터 유형과 연결된 래퍼 클래스는 다음과 같이 연결됩니다.
Primitive data type Wrapper class
boolean Boolean
byte Byte
long Long
double Double
short Short
char Character
Int Integer
float Float

Examples of Autoboxing in Java

Below are the examples of autoboxing in JAVA which are helpful to understand this concept further.

Example #1

Code:

import java.io.*;
class example1
{
public static void main (String[] args)
{
//here we are creating an integer "test1" having value of "100".
Integer test1 = new Integer(100);
System.out.println("Here is the value of integer test1 which is created into object of the wrapper class integer: " + test1);
//here we are autoboxing a character "test2" with a value of "a".
Character test2 = 'a';
System.out.println("Here is the value of test2 variable after autoboxing using character wrapper class: " + test2);
}
}

Output:

Java의 오토박싱

Explanation:

The JAVA library named “java.io” was imported so that JAVA prime functionalities can be used. First, the main class name “example1” was created containing the main function. The main function is the point where the execution of the program will start. Next, an integer named “test1” was created and assigned with the value. It is slightly different from the normal way of declaring and assigning the values; as you can see, the wrapper class “Integer” was instantiated, and the value to be assigned is passed as a parameter to the wrapper class. This process is called objectifying the primitive data type using the wrapper class. No doubt that “JAVA” is called a fully object-oriented language.

In the next section of code, the Character primitive data type is assigned to a variable named “test2” with a value “a.” This is a usual way of declaring and assigning the variable with the value. This is working because the JAVA compiler is smart enough to convert the primitive data type into an object of its wrapper class automatically in the back. This functionality is called autoboxing in JAVA.

Example #2

Code:

public class BoxingWidening
{
// The function below is demonstrating the boxing functionality in JAVA.
static void testFunction(char i)
{
System.out.println("Program output for boxing:: ");
System.out.println("char in short");
}
// This function is demonstrating the widening functionality in JAVA.
static void testFunction(Character i)
{
System.out.println("Program output for widening: ");
System.out.println("Character in full");
}
public static void main(String args[])
{
char ch='a';
testFunction(ch);
}
}

Output:

Java의 오토박싱

Explanation:

In this example, the difference between “widening” and “boxing” is demonstrated. Widening is a functionality where the full class name is used, for example, Integer or character instead of int or char. Two functions are defined with the same name, “testFunction,” one with widening and the other with boxing syntax declarations and assignments. In the main function, a character named “ch” is declared and assigned with a value “a,” and a function is called with its function name. This function has two definitions on its name. Since JAVA prefers boxing, the function’s boxing definition is called, and the parameter “ch” is passed to the boxing definition. The final result is displayed using the print() function. This function shows boxing definition in the output screen rather than taking a widening definition. Certainly, autoboxing is much powerful in comparison to the widening functionality offered by the JAVA language.

Advantages

Some of the advantages derived from this useful functionality by JAVA are enlisted below:

  1. The developer has to write less code, and this reduces the burden on the coder so that the coder can concentrate on complex logic.
  2. Cleaner code as the complexity of creating an object and instantiating it is abstracted due to compiler intelligence.
  3. The best strategy for information is picked up by the compiler using this. For example, if we want the value of the integer to be picked up, then we should use code: valueOf (int) rather than new Integer (int). This improves turnaround time.
  4. Promotes abstraction.
  5. Reduces the possibility of bugs in the lengthy code/ project because of abstraction.

Conclusion

Autoboxing is one of the best strategies to abstract complex code from the developer by adding compiler intelligence. This reduces the overhead on the developer of writing small code snippets which are not logically related. This is used so extensively by developers that the instantiating of a wrapper class is not known to many developers. Autoboxing is certainly a powerful and cleaner way of declaring and assigning the values to the variables.

위 내용은 Java의 오토박싱의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:JAVA에서의 반사다음 기사:JAVA에서의 반사