Kwert-soft.ru

IT Софт для ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Int tostring java

Целое число toString () в Java

Параметры: Метод не принимает никаких параметров.

Возвращаемое значение: метод возвращает строковый объект определенного целочисленного значения.

Ниже программа иллюстрирует метод Java.lang.Integer.toString ():

// Java-программа для иллюстрации
// метод toString ()

public class Geeks<

public static void main(String[] args) <

Integer obj = new Integer( 8 );

// вернет строковое представление

String stringvalue1 = obj.toString();

System.out.println( «String Value= » +

Integer obj3 = new Integer( 10 );

// вернет строковое представление

String stringvalue3 = obj3.toString();

System.out.println( «String Value = » +

Java.lang.Integer.toString ( int a ) — это встроенный метод в Java, который используется для возврата объекта String, представляющего указанное целое число в параметре.
Синтаксис:

Параметры: метод принимает один параметр a целочисленного типа и ссылается на целое число, которое необходимо преобразовать в строку.

Возвращаемое значение: метод возвращает строковое представление аргумента в конкретной базе.

Примеры:

Ниже программы иллюстрируют метод Java.lang.Integer.toString (int a):
Программа 1:

// Java-программа для иллюстрации
// метод toString (int a)

public class Geeks<

public static void main(String[] args) <

Integer obj = new Integer( 8 );

// вернет строковое представление

String stringvalue1 = obj.toString( 75 );

System.out.println( «String Value = » +

Integer obj2 = new Integer( 8 );

// вернет строковое представление

String stringvalue2 = obj2.toString( 6787 );

System.out.println( «String Value = » +

Integer obj3 = new Integer( 10 );

// вернет строковое представление

String stringvalue3 = obj3.toString(- 787 );

System.out.println( «String Value = » +

Программа 2: для десятичных и строковых параметров.
Примечание. Это приводит к ошибке, а также к отсутствию подходящего конструктора Integer.

// Java-программа для иллюстрации
// Java.lang.Integer.toString (int a) метод

public class Geeks<

public static void main(String[] args) <

Integer obj = new Integer( 8 );

String stringvalue1 = obj.toString( 58.5 );

System.out.println( «String Value = » +

Integer obj2 = new Integer( 8 );

String stringvalue2 = obj2.toString( «317» );

System.out.println( «String Value = » +

// Пустой конструктор приведет к ошибке

Integer obj3 = new Integer();

String stringvalue3 = obj3.toString(- 787 );

System.out.println( «String Value = » +

Выход:

Java.lang.Integer.toString ( int a, int base ) — это встроенный метод в Java, который используется для возврата строкового представления аргумента a в базе, указанной вторым аргументом base . Если основание / основание меньше, чем Character.MIN_RADIX или больше, чем Character.MAX_RADIX, тогда используется основание 10. Символы ASCII, которые используются в качестве цифр: от 0 до 9 и от a до z.
Синтаксис:

Параметр: метод принимает два параметра:

  • a : это целочисленный тип и относится к целочисленному значению, которое должно быть преобразовано.
  • base : это также целочисленный тип и относится к основанию, которое будет использоваться при представлении строк.

Возвращаемое значение: метод возвращает строковое представление указанного аргумента в указанной базе.

Примеры:

Ниже программы иллюстрируют метод Java.lang.Integer.toString (int a, int base):
Программа 1:

// Java-программа для иллюстрации
// метод toString (int, int)

public class Geeks<

public static void main(String[] args) <

Integer a = new Integer( 10 );

// Возвращает строковое представление

String returnvalue = a.toString( 5254 , 2 );

System.out.println( «String Value = » +

// Возвращает строковое представление

returnvalue = a.toString( 35 , 8 );

System.out.println( «String Value = » +

// Возвращает строковое представление

returnvalue = a.toString( 47 , 16 );

System.out.println( «String Value = » +

// Возвращает строковое представление

returnvalue = a.toString( 451 , 10 );

System.out.println( «String Value = » +

Программа 2:

// Java-программа для иллюстрации
// метод toString (int, int)

Int tostring java

This tutorial will show example codes on how to convert Java Int to String. Performing conversion from int to String is a common scenario when programming with Core Java.

Here are some quick reference example codes:

Convert using Integer.toString(int)

The Integer class has a static method that returns a String object representing the specified int parameter. Using this is an efficient solution.

Syntax

The argument i is converted and returned as a string instance. If the number is negative, the sign will be preserved.

Example
The code is equivalent to:
If you will try and search for solutions, this is one of the most popular ways of converting an int to String.

Читать еще:  Java net sockettimeoutexception timeout

Convert using String.valueOf(int)

The String class has several static methods that can convert most primitive types to their String representation. This includes integers.

Example
or

This is also an efficient solution like the first option above. And because this is simple and efficient, it is also a very popular method for converting an int to String.

Convert using new Integer(int).toString()

Another alternative method is to create an instance of Integer class and then invoke it’s toString() method. This is a little less efficient than the first two options shown above. This is because a new instance of Integer is created before conversion is performed.

Example

We can shortened to:

If your variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int). But if your variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke it’s toString() method as shown above.

Convert using String.format()

String.format() is a new alternative that can be used for converting an Integer to String object. It is first introduced in Java 5 (JDK1.5) and has many cool features.

Syntax

There are many options on how to use this method. But for conversion purposes, here is a simple example:

Example
And the variable numberAsString will have the value «-782»

If you are using Java 5 or higher, this is also a very simple alternative for converting an int to String object.

Convert using DecimalFormat

The class java.text.DecimalFormat is a class that formats a number to a String representation following a certain pattern.
Example
Will output

This is an example that will convert to String but with commas
Will output

This is my favorite from all the options shown in this post because of the level of control that you can do with the formatting. You can specify the number of decimal places and comma separator for readability.

Convert using StringBuffer or StringBuilder

StringBuffer is a class that is used to concatenate multiple values into a String. StringBuilder works similarly but not thread safe like StringBuffer. These two classes can be used to convert a Java Integer to String.

StringBuffer Example

StringBuilder Example

Shortened Examples

Quick Solution

When you concatenate a String and an integer, the result is a String. Internally, the code is inefficient because there are intermediate objects that are created behind the scene.

Convert with special radix

All of the examples above uses the base (radix) 10. There are cases when we wish to convert a Java Integer to String but using another base. There are convenient methods to convert to binary, octal, and hexadecimal system. Arbitrary custom number system is also supported.

Examples

    Binary
    The output is
    11111111 is the binary representation of the number 255.

Octal
The output is
377 is the octal representation of the number 255.

Hexadecimal
The output is
ff is the hexadecimal representation of the number 255.

Custom Base/Radix
We can use any other custom base/radix when converting an int to String. The sample shown below uses the base 7 number system.
The output is
513 is the representation of the number 255 when written in the base 7 system.

Int tostring java

Converting a primitive int , or its respective wrapper class Integer , to a String is a common and simple operation. The same goes for the other way around, converting a String to Integer.

Converting Integer to String

When converting an int or Integer to a String, there are four approaches. The String class provides a couple of methods — valueOf() and format() for this purpose, though the already mentioned Integer class also offers a toString() method that takes care of this problem. Additionally, you could also rely on StringBuilder ‘s append() method, though this isn’t a commonly used scenario:

  • String.valueOf(int i) — This approach is considered best practice due to simplicity. This method accepts other types as well — boolean , char , char[] , double , float , long , Object
  • Integer.toString(int i) — This approach is older than valueOf() and simply utilizes the method every Java object has to return a String representing the given int. This approach, unlike the previous, can return a NullPointerException though.
  • String.format(String format, Object. args) — Returns a String formatted according to the format specifier and the following arguments
  • StringBuilder.append(int i).toString() — Same as the valueOf() method, this method accepts all primitive types with the addition of some other types like String , StringBuffer and CharSequence .
Читать еще:  Создание игр на javascript книга

String.valueOf()

The valueOf() method is the static method of String class that returns the String representation of the specified type.

There are many types allowed here:

But we’ll be focusing on int for this tutorial. The representation returned exactly matches the representation returned by Integer.toString() when passing the same argument:

Running this piece of code will yield:

This makes sense since both of these methods return a new String. The equals() method returns true, because their value is the same, whereas == returns false since their reference variables don’t point to the same object in memory.

Using valueOf() keeps your code consistent across conversion of one data type to another. In the case of an Integer, the valueOf() method is also able to cache frequently used numbers e.g. from -127 to 128, in order to speed up the conversion and reduce memory.

Because of this, it’s encouraged to use the valueOf() method for both String and Integer conversion.

Integer.toString()

This approach utilizes one of the most common Java methods — toString() shared amongst all objects.

The method has many usages and warrants a detailed explanation. If you’d like to read more about it, we’ve got a great article already covering it!

In this case, the method returns a String object representing the specified int. The argument is converted to signed decimal representation and returned as a String:

Running this piece of code will yield:

If your variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int) . But if your variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above.

String.format()

Returns a String formatted according to the format specifier and the following arguments. While the purpose of this method isn’t exactly to convert, but rather format a String, it can also be used for conversion.

There are quite a few specifiers to choose from:

  • %a — Hex output of a floating point number
  • %b — true if not null, false if null
  • %c — Unicode character
  • %d — Decimal Integer
  • %e — Scientific notation of a decimal Integer
  • %f — Decimal floating point number
  • %g — Same as above, but possibly scientific, depending on the value
  • %h — Hex String of hashCode() return value
  • %n — Line separator
  • %o — Octal Integer
  • %s — String
  • %t — Date/Time conversion
  • %x — Hex String

We’ll be focusing on %d for this tutorial:

Running this piece of code will yield:

Читать еще:  Java string split пример

The format() method throws an IllegalFormatConversionException if you pass an incompatible type e.g. passing Integer for specifier %s , which expects a String object.

Some of the most common specifiers are %s for String, %d for decimal integer and %n .

StringBuilder and StringBuffer

Both StringBuffer and StringBuilder are classes used to concatenate multiple values into a single String.

StringBuffer is thread safe but slower, whereas StringBuilder isn’t thread safe but is faster.

Running this piece of code will yield:

Conclusion

We’ve covered one of the fundamental topics of Java and common problem developers face — Converting an int or Integer to a String using tools shipped with the JDK.

Java String to int, Java int to String

Today we will look at Java String to int conversion and then java int to String conversion. Java provides several ways to convert String to int and int to String.

Table of Contents

Java String to int

  • Using Integer.parseInt method
  • Using Integer.valueOf method
  • Using above methods with different radix.

Java String to int example

Let’s write a simple java program to convert String to an int, note that String is an Object whereas int is a primitive data type. An integer can be written in Decimal, Hexadecimal, Octal Binary or any other nonstandard formats.

Java 7 one of the feature is Binary Literals. In this example, we will explore how to convert String to int using different radix values.

Output of the above program is:

  • Interegr.parseInt(String str) is the most commonly used method to convert String to int, if String represents int in decimal format. Internally, it invokes method Interegr.parseInt(String str, int radix) with radix value as 10.
  • By passing redix value as 2, we can convert Binary int representation String to int, same is true for other known formats Octal, Hexadecimal also.
  • Minimum radix value is 2 and maximum radix value is 36. For radix 36, it includes 0 to 9 and then A(10) to Z(36). The conversion from String to int is case insensitive.
  • Integer.valueOf(String str) is also a way to convert String to int. There is also an overloaded method where we can pass radix, as you can see from above example code.
  • If the String representation does not contain a parsable integer, both above methods throw NumberFormatException .
  • The String representation should only contain the value and not the radix prefix associated with int, like 0x, 0b etc.

Java int to String

  • Using + operator to concatenate int to string.
  • Using String.valueOf method.
  • Using String.format method

Java int to String example

Let’s write a simple program to convert java int to String object using different methods.

The output of the above program is:

  • +” operator is overloaded for String and it can be used to convert int to String. It also takes care of different formats like Hexadecimal, Octal, Binary and convert them to decimal format before returning the final String object.
  • String.valueOf(int i) can be used to convert int to String. valueOf() method is overloaded to accept float, long, double etc. Internally it uses Integer.toString(int i) method to return the String object.
  • String.format(String format, Object. args) is also another way to convert int to String object.
  • Before converting int to string, value is always converted to decimal format and then assigned to string. As you can see from the output above, all the string representations are in the decimal format.

That’s all for Java String to int and int to String conversion, we will cover more java interview questions in future posts.

Ссылка на основную публикацию
Adblock
detector