8 methods convert an integer string java
이 튜토리얼에서는 흥미로운 프로그래밍 예제와 함께 Integer를 Java에서 String으로 변환하는 다양한 방법을 탐색합니다.
Java에서 Int를 String으로 변환하기 위해 다른 Java 클래스에서 제공하는 다음 메소드의 사용을 다룰 것입니다.
- 문자열 연결
- String.valueOf ()
- String.format ()
- Integer.toString ()
- Integer.String (int)
- StringBuilder 추가 ()
- StringBuffer 추가 ()
- DecimalFormat 형식 ()
이러한 방법을 하나씩 자세히 살펴 보겠습니다.
=> 처음부터 Java를 배우려면 여기를 방문하십시오.
학습 내용 :
Java에서 문자열로 은밀한 정수
다양한 시나리오에서 응용 프로그램이나 웹 사이트를 개발하는 동안 정수를 문자열로 변환하는 Java 프로그램을 작성해야합니다.
int 변수에 대해 특정 산술 연산을 수행 한 후 수신 된 결과 값이 정수 값인 Java 프로그램의 시나리오를 고려해 보겠습니다. 그러나이 값은 웹 페이지의 일부 텍스트 필드 또는 텍스트 영역 필드에 전달되어야합니다. 이러한 경우 먼저이 int 값을 String으로 변환해야합니다.
# 1) 문자열 연결 사용
Java와 '+'연산자를 여러 번 사용했습니다. 이것은 System.out.println () 메서드를 사용하여 콘솔에서 출력을 인쇄 할 때 매우 일반적으로 사용됩니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String concatenation * * @author * */ public class IntStringDemo1 { public static void main(String() args) { // Assign int 25 to int variable length int length = 25; // Assign int 10 to int variable width int width = 10; // Multiply variable value length and width and assign to calculatedArea int calculatedArea = length * width; // concatenate calculatedArea to String 'Variable calculatedArea Value --->' using plus ‘+’ // operator // print variable int type calculatedArea System.out.println('Variable calculatedArea Value --->' + calculatedArea); } }
다음은 프로그램 출력입니다.
계산 된 변수 영역 값 —> 250
위의 프로그램에서 우리는 int를 연결하고 있습니다. 계산 된 영역 다음과 같이 문자열“변수 계산 영역 값 —>”를 사용합니다.
'변수 계산 영역 값 —>'+ 계산 영역
이것은 int 계산 된 영역을 String으로 변환합니다. 그런 다음이 문자열이 System에 인수로 전달됩니다. 밖 .println () 메서드를 사용하여 다음과 같이 콘솔에 인쇄합니다.
체계. 밖 .println ( '계산 된 변수 변수 값 —>'+ 계산 된 영역);
그러면 콘솔에 문자열이 인쇄됩니다.
계산 된 변수 영역 값 —> 250
# 2) String.ValueOf () 메서드 사용
String 클래스에는 valueOf ()의 정적 오버로딩 메서드가 있습니다. 이러한 오버로딩 메서드의 목적은 int, long, float와 같은 기본 데이터 유형의 인수를 String 데이터 유형으로 변환하는 것입니다.
아래에서 int 데이터 유형에 대한 메서드 시그니처를 살펴 보겠습니다.
public static String valueOf (int i)
이 정적 메서드는 데이터 유형 int의 인수를 수신하고 int 인수의 문자열 표현을 반환합니다.
매개 변수 :
i : 이것은 정수입니다.
보고:
int 인수의 문자열 표현입니다.
다음 샘플 프로그램을 사용하여이 String.valueOf () 메서드를 사용하는 방법을 이해하겠습니다. 이 프로그램에서는 두 개의 숫자를 추가하고 String.valueOf () 메서드를 사용하여 정수 sumValue를 String으로 변환합니다.
다음은 참조 용 샘플 프로그램입니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String.valueOf() method * * @author * */ public class IntStringDemo2 { public static void main(String() args) { // Assign int 300 to int variable x int x = 300; // Assign int 200 to int variable y int y = 200; // Add variable value x and y and assign to sumValue int sumValue = x + y; // Pass sumValue as an argument to String.valueOf() to convert // sumValue to String String sum = String.valueOf(sumValue); // print variable String sum System.out.println('Variable sum Value --->' +sum); } }
다음은 프로그램 출력입니다.
가변 합계 값 —> 500
# 3) String.format () 메서드 사용
String 클래스에는 인수를 지정된 형식으로 변환하는 정적 메서드가 있습니다.
아래에서 메서드 시그니처를 살펴 보겠습니다.
public static String format (String format, Object… args)
지정된 String 형식 및 Object 인수 인수를 사용하고 형식화 된 String을 반환하는 String 클래스 정적 메서드입니다. 형식 지정자보다 인수가 많은 경우 추가 인수는 무시됩니다. 인수의 수는 가변적이며 0 일 수도 있습니다.
매개 변수 :
형식 : 형식 문자열
args : 형식 문자열에 따라 형식화해야하는 인수
보고:
지정된 형식 문자열에 따라 형식이 지정된 문자열
던졌습니다 :
이 메서드는 IllegalFormatException, NullPointerException을 throw합니다.
이 String.format () 메서드의 사용을 이해해 봅시다.
두 개의 정수를 비교하는 동일한 프로그램 코드를 살펴 보겠습니다. 프로그램은 2 개의 숫자 중 더 큰 숫자를 인쇄합니다. 이 프로그램은 String.format () 메서드를 사용하여 정수를 변환합니다. 큰 숫자 문자열로.
샘플 프로그램은 다음과 같습니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using String.format() method * * @author * */ public class IntStringDemo3 { public static void main(String() args) { // Assign int 25 to int variable a int a = 25; // Assign int -50 to int variable b int b = -50; // Compare two numbers a and b int largeNumber = 0; if(a>b) { //if a is greater than b assign it to largeNumber variable largeNumber = a; }else { //if a is less than b then assign b to largeNumber variable largeNumber = b; } // Pass largeNumber as an argument to String.format() to convert // largeNumber to String String largeNumberString = String.format('|%5d|',largeNumber); // print variable String largeNumberString System.out.println('Variable largeNumber Value --->' + largeNumberString); } }
다음은 프로그램 출력입니다.
변수 largeNumber 값 —> | 25 |
위의 샘플 코드에서는 String.format () 메서드를 사용했습니다. '| % 5d |'를 사용하고 있습니다. 형식으로 다음과 같이 int 값 largeNumber를 전달합니다.
String largeNumberString = 문자열. 체재 ( '| % 5d |', largeNumber);
String.format ()은 지정된 형식 '| % 5d |'에 따라 형식화 된 문자열을 반환합니다. 즉, 너비가 5이고 오른쪽 맞춤, 즉 '||'에 지정된 숫자입니다. | 25 | 콘솔에서도 동일하게 인쇄합니다.
체계. 밖 .println (“변수 largeNumber 값 —>”+ largeNumberString);
따라서 콘솔의 출력은 변수 largeNumber 값 —> | 25 |
이제 Integer 클래스에서 제공하는 Integer to String Java 변환 메소드를 살펴 보겠습니다.
품질 관리 인터뷰 질문 및 답변 pdf
다음 Integer 클래스 메서드를 볼 수 있습니다.
-
-
- 정수 (int) .toString ().
- Integer.toString (int)
-
# 4) Integer (int) .toString () 메서드 사용
정수 클래스는 메서드를 제공합니다 toString () int를 String으로 변환합니다.
아래에서 메서드 시그니처를 살펴 보겠습니다.
공용 문자열 toString ()
이 메서드는 값을 부호있는 10 진수 표현으로 변환하고 String 개체를 반환합니다.
이것의 사용법을 이해합시다 정수 (int) .toString () 방법.
두 숫자의 나머지를 계산하고 Integer (int) .toString () 메서드를 사용하여 콘솔에 인쇄하여 정수 나머지 값을 문자열 표현으로 변환하는 샘플 코드를 살펴 보겠습니다.
다음은 아래의 샘플 프로그램입니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using Integer.toString() method * * @author * */ public class IntStringDemo4 { public static void main(String() args) { // Assign int 33 to int variable dividentValue int dividentValue = 33; // Assign int 5 to int variable dividerValue int dividerValue = 5; // Calculate remainder of dividentValue and dividerValue using modulus int remainderValue = dividentValue % dividerValue; // Pass remainderValue as an argument to new Integer() to convert it to Integer object Integer remainderIntValue = new Integer(remainderValue); // Invoke toString() method on Integer object remainderIntValue convert it to String String remainder = remainderIntValue.toString(); // print variable String remainder System.out.println('Variable remainder Value --->' + remainder); } } }
다음은 프로그램 출력입니다.
가변 나머지 값 —> 3
위 프로그램에서는 Integer 클래스의 인스턴스를 생성했습니다.
새로운 정수 (remainderValue);
아래와 같이 toString () 메서드를 호출했습니다.
문자열 나머지 = restderIntValue.toString ();
이 명령문은 Integer 클래스 객체 restderIntValue의 문자열 표현을 반환합니다.
# 5) Integer.toString (int) 메서드 사용
정수 또한 정적 메서드를 제공합니다 toString () int를 String으로 변환합니다.
아래에서 메서드 시그니처를 살펴 보겠습니다.
공개 정적 문자열 toString (int i)
이 정적 메서드는 지정된 정수에 대한 String 개체 표현을 반환합니다. 여기에서 인수는 부호있는 10 진수 표현으로 변환되고 문자열로 반환됩니다. 이것은 기수 값이 10 인 오버로드 된 메소드 toString (int i, int radix)와 정확히 동일합니다.
매개 변수 :
i : 이것은 변환해야하는 정수 값입니다.
보고:
기수가 10 인 인수 i의 문자열 표현입니다.
이것의 사용법을 이해합시다 정수 . toString (int i) 방법.
정수 squareValue를 String으로 변환하기 위해 Integer.toString (int i) 메서드를 사용하여 사용자에게 숫자를 입력하고, 숫자의 제곱을 계산하고, 콘솔에 제곱을 인쇄하는 샘플 프로그램 코드를 작성해 보겠습니다.
다음은 아래의 샘플 프로그램입니다.
package com.softwaretestinghelp; import java.util.Scanner; /** * This class demonstrates sample code to convert int to String Java program * using Integer.toString(int i ) method * * @author * */ public class IntStringDemo5 { private static Scanner scanner; public static void main(String() args) { //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.print('Please Enter the number'); //Scan the next token of the user input as an int and assign it to variable x int x= scanner.nextInt(); //Calculate square of the number assigned to x int squareValue = x*x; // Pass squareValue as an argument to Integer.toString() to convert // squareValue to String String square = Integer.toString(squareValue); // print variable String square System.out.println('Variable square Value --->' + square); } }
다음은 프로그램 출력입니다.
숫자 5를 입력하세요
가변 제곱 값 —> 25
위의 프로그램에서 우리는 squareValue를 인수로 전달하여 Integer 클래스에서 정적 메소드 toString을 호출했습니다.
문자열 사각형 = 정수. toString (squareValue);
이것은 int 값 squareValue의 문자열 표현을 반환합니다.
더 많은 방법, 즉 StringBuffer, StringBuilder 클래스 메서드를 활용하는 방법을 살펴 보겠습니다.
StringBuffer 클래스는 문자열에 여러 값을 추가하는 데 사용됩니다. StringBuilder는 정확한 작업을 수행하며 유일한 차이점은 StringBuffer가 스레드로부터 안전하지만 StringBuilder는 그렇지 않다는 것입니다.
추천 자료 => 자바 문자열 튜토리얼
# 6) StringBuilder 클래스 메서드 사용
Java에서 int를 String으로 변환하기 위해 StringBuilder 메소드를 사용하는 방법을 살펴 보겠습니다.
다음은 메서드 서명입니다.
공용 StringBuilder 추가 (int i)
이 메서드는 int 인수의 문자열 표현을 시퀀스에 추가합니다.
매개 변수 :
i : 이것은 정수입니다.
보고:
이것은 객체에 대한 참조입니다.
공용 문자열 toString ()
이 메서드는이 시퀀스의 데이터를 나타내는 문자열을 반환합니다.
다음은 정수 값의 평균을 계산하고 정수 avgNumber를 String으로 변환하기 위해 StringBuilder를 사용하는 방법을 보여주는 샘플 프로그램입니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using StringBuilder append() toString() method * * @author * */ public class IntStringDemo6 { public static void main(String() args) { // Assign values to array of type int int() numArray = {15,25,60,55}; //Find the array size int arrLength = numArray.length; int arrSum = 0; //Calculate addition of all numbers for(int i=0;i' + average); } }
다음은 프로그램 출력입니다.
가변 평균 값 —> 38
위 프로그램에서는 StringBuilder append () 메서드를 사용하고 toString () 메서드를 사용하여 StringBuilder 객체를 String으로 변환했습니다.
strbAvg.append (avgNumber);
문자열 평균 = strbAvg.toString ();
# 7) StringBuffer 클래스 메서드 사용
Java가 StringBuffer 메서드를 사용하여 int를 String 방식으로 변환하는 것을 살펴 보겠습니다.
다음은 메서드 서명입니다.
공용 StringBuffer 추가 (int i)
이 메서드는 int 인수의 문자열 표현을 시퀀스에 추가합니다.
매개 변수 :
i : 이것은 정수입니다.
보고:
이것은 객체에 대한 참조입니다.
공용 문자열 toString ()
이 메서드는이 시퀀스의 데이터를 나타내는 문자열을 반환합니다.
아래의 샘플 프로그램을 살펴 보겠습니다. 더 낮은 Math.min () 메서드를 사용하여 2 개의 int 값 중 더 낮은 값을 찾고 StringBuffer 메서드를 사용하여 정수 minValue를 String으로 변환합니다.
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert int to String Java program * using StringBuffer append() toString() method * * @author * */ public class IntStringDemo7 { public static void main(String() args) { // Assign int 60 to int variable a int a = 60; // Assign int -90000 to int variable b int b = -90000; // Get lower value between int a and b using Math class method min() int minValue = Math.min(a, b); // Pass minValue as an argument to StringBuffer.append() method StringBuffer strbMinValue = new StringBuffer(); strbMinValue.append(minValue); //Convert strbMinValue to String using toString() method String minimumValue = strbMinValue.toString(); // print variable String miniumValue System.out.println('Variable miniumValue Value --->' + minimumValue); } }
다음은 프로그램 출력입니다.
가변 최소값 값 —>-90000
위 프로그램에서는 StringBuffer append () 메소드를 사용하고 toString () 메소드를 사용하여 StringBuffer 객체를 String으로 변환했습니다.
소프트웨어 테스트에서 사용자 수용 테스트는 무엇입니까
strbMinValue.append (minValue);
문자열 minimumValue = strbMinValue.toString ();
# 8) DecimalFormat 클래스 메서드 사용
Java int는 java.text.DecimalFormat Class 메소드를 사용하여 String으로 변환 할 수도 있습니다.
다음은 클래스 형식 () 메서드의 메서드 서명입니다.
NumberFormat. DecimalFormat은 NumberFormat 클래스를 확장합니다.
공개 최종 문자열 형식 (긴 숫자)
이 메소드는 long 데이터 유형의 인수에 대해 형식화 된 문자열을 리턴합니다.
매개 변수 :
숫자 : 이것은 long 데이터 유형의 값입니다.
보고:
포맷 된 문자열
다음은 DecimalFormat 클래스 메서드를 사용하여 정수 elementValue를 String으로 변환하는 방법을 보여주는 샘플 프로그램입니다.
package com.softwaretestinghelp; import java.text.DecimalFormat; import java.util.Scanner; /** * This class demonstrates sample code to convert int to String Java program * using DecimalFormat format() method * * @author * */ public class IntStringDemo8 { private static Scanner scanner; public static void main(String() args) { // Assign values to array of arrays of type int int()() numArray = { {15,20,30,60}, {300,600,900} }; //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.println('Please Enter the array number'); //Scan the next token of the user input as an int and assign it to variable x int x= scanner.nextInt(); System.out.println('Please Enter the element number'); //Scan the next token of the user input as an int and assign it to variable y int y= scanner.nextInt(); int elementValue = numArray(x)(y); System.out.println(elementValue); // Pass '#' as format for DecimalFormat DecimalFormat formatElement = new DecimalFormat('#'); //Pass elementValue as an argument to format() method to convert it to String String element = formatElement.format(elementValue); // print variable String element System.out.println('Variable element Value --->' + element); } }
다음은 프로그램 출력입니다.
어레이 번호를 입력하십시오
1
요소 번호를 입력하십시오
1
600
가변 요소 값 —> 600
위의 프로그램에서는 DecimalFormat 클래스 형식 () 메서드를 사용하여 아래와 같이 int elementValue를 String으로 변환했습니다.
문자열 요소 = formatElement.format (elementValue);
따라서 우리는 Java 정수를 문자열 값으로 변환하는 여러 방법을 다루었습니다. 모든 샘플 프로그램에서 정수 값을 문자열 값으로 변환해야하고 콘솔 출력이 표시되는 다양한 시나리오를 보았습니다.
따라서 Java에서 정수를 문자열로 변환 할 목적으로 위의 샘플 코드에서 설명 된 모든 메소드를 Java 프로그램에서 사용할 수 있습니다.
다음은 int에서 String으로의 변환에 대해 자주 묻는 질문입니다.
Java에서 Int를 문자열로 변환하는 방법에 대한 FAQ
Q # 1) Java에서 int를 String으로 변환 할 수 있습니까?
대답: 예 , Java에서는 int를 String으로 변환 할 수 있습니다.
다음 메소드를 사용하여 int를 String으로 변환 할 수 있습니다.
- 문자열 연결
- String.valueOf ()
- String.format ()
- Integer.toString ()
- Integer.String (int)
- StringBuilder 추가 ()
- StringBuffer 추가 ()
- DecimalFormat 형식 ()
Q # 2) cast int를 string에 입력 할 수 있습니까?
대답: 예, String.valueOf (), Integer.toString () 등과 같은 String 및 Integer 클래스 메서드를 사용하여 int를 String으로 변환 할 수 있습니다.
Q # 3) 문자열을 숫자로 어떻게 변환합니까?
대답: Integer.valueOf () 및 Integer.parseInt ()와 같은 Integer 클래스의 메서드를 사용하여 문자열을 여러 int 유형으로 변환 할 수 있습니다.
결론
이 튜토리얼에서는 다음 방법을 사용하여 Java에서 정수를 문자열로 변환하는 방법을 탐색했습니다.
- 문자열 연결
- String.valueOf ()
- String.format ()
- Integer.toString ()
- Integer.String (int)
- StringBuilder 추가 ()
- StringBuffer 추가 ()
- DecimalFormat 형식 ()
각 방법을 자세히 다루고 샘플 예제를 사용하여 각 방법의 사용을 설명했습니다.