Elettracompany.com

Компьютерный справочник
8 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Integer valueof java

Целочисленный метод valueOf () в Java

Параметры: Метод принимает единственный параметр a целочисленного типа, представляющий параметр, экземпляр которого Integer должен быть возвращен.

Возвращаемое значение: Метод возвращает экземпляр целого числа , представляющий.

Примеры :

Ниже программы иллюстрируют метод java.lang.Integer.valueOf (int a).
Программа 1: для положительного числа.

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

public class Geeks <

public static void main(String[] args)

Integer obj = new Integer( 10 );

// Возвращает экземпляр Integer

// представляет указанное значение int

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

Программа 2: для отрицательного числа.

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

public class Geeks <

public static void main(String[] args)

Integer obj = new Integer( 10 );

// Он вернет экземпляр Integer

// представляет указанное значение int

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

Java.lang.Integer.valueOf ( String str ) — это встроенный метод, который используется для возврата объекта Integer, содержащего значение указанной String str .

Параметры: Этот метод принимает один параметр str типа String, который должен быть проанализирован.

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

Примеры:

Ниже программы иллюстрируют метод java.lang.Integer.valueOf (String str):
Программа 1: для положительного числа.

// Java праограмма для иллюстрации
// java.lang.Integer.valueOf (String str)

public class Geeks <

public static void main(String[] args)

Integer obj = new Integer( 8 );

String str = «424» ;

// Он вернет экземпляр Integer

// представляет указанную строку

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

Программа 2: для отрицательного числа.

// Java праограмма для иллюстрации
// java.lang.Integer.valueOf (String str)

public class Geeks <

public static void main(String[] args)

Integer obj = new Integer( 8 );

String str = «-6156» ;

// Он вернет экземпляр Integer

// представляет указанную строку

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

Java.lang.Integer.valueOf ( String s, int radix ) — это встроенный метод, который возвращает объект Integer, содержащий значение, извлеченное из указанной строки при анализе с основанием, заданным вторым аргументом.

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

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

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

Integer valueof java

Класс Integer — это оболочка простого типа int. Объект содержит единственное поле типа int. Кроме того, этот класс обеспечивает несколько методов для преобразования int в String и обратно, а также другие константы и методы полезные при работе с int.

Поля класса:

  • static int MAX_VALUE — Самая большая величина типа int
  • static int MIN_VALUE — Минимальная величина типа int
  • static Class TYPE — Объект Класса представляющий простой тип int

Конструктор класса:

  • Integer(int value) — Создает вновь размещенный объект Integer, который создается на основе аргумента
  • Integer(String s) — Создает вновь размещенный объект Integer, который создается на основе строкового аргумента

Методы класса:

  • byte byteValue() — Возвращает величину Integer как byte
  • int compareTo(Integer anotherInteger) — Сравнивает два целых числа
  • int compareTo(Object o) — Сравнивает число с другим объектом
  • static Integer decode(String nm) — Переводит строку в целое
  • double doubleValue() — Возвращает величину Integer как double
  • boolean equals(Object obj) — Сравнивает это объект с другим объектом
  • float floatValue() — Возвращает величину Integer как double
  • static Integer getInteger(String nm) — Определяет значение целого системного свойства с определенным именем
  • static Integer getInteger(String nm, int val) — Определяет значение целого системного свойства с определенным именем
  • static Integer getInteger(String nm, Integer val) — Возвращает значение целого системного свойства с определенным именем
  • int hashCode() — Возвращает hashcode для этого обьекта
  • int intValue() — Возвращает величину Integer как int
  • long longValue() — Возвращает величину Integer как long
  • static int parseInt(String s) — Выполняет грамматический разбор аргумента строки как десятичного целого
  • static int parseInt(String s, int radix) — Выполняет грамматический разбор аргумента строки, как целого со знаком в системе счисления определенной во втором аргументе
  • short shortValue() — Возвращает величину Integer как short
  • static String toBinaryString(int i) — Создает представление строки аргумента целого как целое с базой 2
  • static String toHexString(int i) — Создает представление строки аргумента целого как целое с базой 16
  • static String toOctalString(int i) — Создает представление строки аргумента целого как целое с базой 8
  • String toString() — Возвращает строковое представление числа
  • static String toString(int i) — Возвращает новый объект строки с десятичным представлением числа
  • static String toString(int i, int radix) — Возвращает новый объект строки с текстовым значением числа i в заданной системе счисления radix
  • static Integer valueOf(String s, int radix) — Возвращает новый объект Integer инициализированный величиной определенной в строковой переменной s записанной в системе счисления radix

Java Integer Cache – Why Integer.valueOf(127) == Integer.valueOf(127) Is True

Posted by: Naresh Joshi in Core Java November 27th, 2018 0 Views

In an interview, one of my friends was asked that if we have two Integer objects, Integer a = 127; Integer b = 127; Why a == b evaluate to true when both are holding two separate objects? In this article, I will try to answer this question and also try to explain the answer.

Short Answer

The short answer to this question is, direct assignment of an int literal to an Integer reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts Integer a = 127; to Integer a = Integer.valueOf(127); .

The Integer class maintains an internal IntegerCache for integers which by default ranges from -128 to 127 and Integer.valueOf() method returns objects of mentioned range from that cache. So a == b returns true because a and b both are pointing to the same object.

Читать еще:  Код ошибки msvcr100 dll

Long Answer

In order to understand the short answer let’s first understand the Java types, all types in Java lies under two categories

  1. Primitive Types: There are 8 primitive types (byte, short, int, long, float, double, char and boolean) in Java which holds their values directly in the form of binary bits.
    For example int a = 5; int b = 5; , here a and b directly holds the binary value of 5 and if we try to compare a and b using a == b we are actually comparing 5 == 5 which returns true.
  2. Reference Types: All types other than primitive types lies under the category of reference types e.g. Classes, Interfaces, Enums, Arrays etc. and reference types holds the address of the object instead of the object iteslf.
    For example, Integer a = new Integer(5); Integer b = new Integer(5) , here a and b do not hold the binary value of 5 instead a and b holds memory addresses of two separate objects where both objects contain a value 5 . So if we try to compare a and b using a == b, we are actually comparing those two separate memory addresses hence we get false , to perform actual equality on a and b we need to perform a.euqals(b) . Reference types are further divided into 4 categories Strong, Soft, Weak and Phantom References.

And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.

Now if we create two integer objects a and b, and try to compare them using the equality operator == , we will get false because both references are holding different-different objects

But if we assign the value 127 to both a and b and try to compare them using the equality operator == , we will get true why?

As we can see in the code that we are assigning different objects to a and b but a == b can return true only if both a and b are pointing to the same object.

So how the comparison returning true? whats actually happening here? are a and b pointing to the same object?

Well till now we know that the code Integer a = 127; is an example of auto-boxing and compiler automatically converts this line to Integer a = Integer.valueOf(127); .

So it is the Integer.valueOf() method which is returning these integer objects which means this method must be doing something under the hood.

And if we take a look at the source code of Integer.valueOf() method, we can clearly see that if the passed int literal i is greater than IntegerCache.low and less than IntegerCache.high then the method returns Integer objects from IntegerCache . Default values for IntegerCache.low and IntegerCache.high are -128 and 127 respectively.

In other words, instead of creating and retruning new integer objects, Integer.valueOf() method returns Integer objects from an internal IntegerCache if the passed int literal is greater than
-128 and less than 127 .

Java caches integer objects which fall into -128 to 127 range because this range of integers gets used a lot in day to day programming which indirectly saves some memory.

As you can see in the following image Integer class maintains an inner static IntegerCache class which acts as the cache and holds integer objects from -128 to 127 and that’s why when we try to get integer object for 127 we always get the same object.

The cache is initialized on first usage when the class get loaded into memory because of the static block . The max range of the cache can be controlled by the -XX:AutoBoxCacheMax JVM option.

This caching behavior is not applicable for Integer objects only, similar to Integer.IntegerCache we also have ByteCache , ShortCache , LongCache , CharacterCache for Byte , Short ,
Long , Character respectively.

Byte, Short and Long have a fixed range for caching between –127 to 127 (inclusive) but for Character, the range is from 0 to 127 (inclusive). The range can be modified via argument only for Integer but not for others.

You can find the complete source code for this article on this Github Repository and please feel free to provide your valuable feedback.

Opinions expressed by Java Code Geeks contributors are their own.

Java Integer Cache: Why Integer.valueOf(127) == Integer.valueOf(127) Is True

So here’s the cache.

Join the DZone community and get the full member experience.

According to our calculations, Integer.valueOf(127) == Integer.valueOf(127) is true.

In an interview, one of my friends was asked: If we have two Integer objects, Integer a = 127; Integer b = 127; Why does a == b evaluate to true when both are holding two separate objects? In this article, I will try to answer this question and explain the answer.

Short Answer

The short answer to this question is, direct assignment of an int literal to an Integer reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts Integer a = 127; to Integer a = Integer.valueOf(127); .

The Integer class maintains an internal IntegerCache for integers which, by default, ranges from -128 to 127 and Integer.valueOf() method returns objects of mentioned range from that cache. So a == b returns true because a and b both are pointing to the same object.

Читать еще:  Sortedset java пример

Long Answer

In order to understand the short answer, let’s first understand the Java types, all types in Java lies under two categories

  1. Primitive Types: There are 8 primitive types ( byte , short , int , long , float , double , char , and boolean ) in Java, which holds their values directly in the form of binary bits.
    For example, int a = 5; int b = 5; here a and b directly holds the binary value of 5, and if we try to compare a and b using a == b , we are actually comparing 5 == 5 , which returns true.
  2. Reference Types: All types other than primitive types lies under the category of reference types, e.g. Classes, Interfaces, Enums, Arrays, etc. and reference types holds the address of the object instead of the object itself.
    For example, Integer a = new Integer(5); Integer b = new Integer(5) , here, a and b do not hold the binary value of 5 instead a and b holds memory addresses of two separate objects where both objects contain a value 5 . So if we try to compare a and b using a == b, , we are actually comparing those two separate memory addresses. Hence, we get false , to perform actual equality on a and b we need to perform a.euqals(b) .
    Reference types are further divided into 4 categories: Strong, Soft, Weak and Phantom References.

And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.

Now, if we create two integer objects a and b, and try to compare them using the equality operator == , we will get false because both references are holding different-different objects

But if we assign the value 127 to both a and b and try to compare them using the equality operator == , we will get true why?

As we can see in the code, we are assigning different objects to a and b but a == b can return true only if both a and b are pointing to the same object.

So, how does the comparison return true? what’s actually happening here? are a and b pointing to the same object?

Well, until now, we know that the code Integer a = 127; is an example of auto-boxing and compiler automatically converts this line to Integer a = Integer.valueOf(127); .

So, it is the Integer.valueOf() method that is returning these integer objects, which means this method must be doing something under the hood.

And if we take a look at the source code of Integer.valueOf() method, we can clearly see that if the passed int literal i is greater than IntegerCache.low and less than IntegerCache.high , then the method returns Integer objects from IntegerCache . Default values for IntegerCache.low and IntegerCache.high are -128 and 127 respectively.

In other words, instead of creating and returning new integer objects, Integer.valueOf() method returns Integer objects from an internal IntegerCache if the passed int literal is greater than -128 and less than 127 .

Java caches integer objects that fall into -128 to 127 range because this range of integers gets used a lot in day-to-day programming, which indirectly saves some memory.

As you can see in the following image, the Integer class maintains an inner static IntegerCache class, which acts as the cache and holds integer objects from -128 to 127, and that’s why when we try to get integer object for 127, we always get the same object.

The cache is initialized on the first usage when the class gets loaded into memory because of the static block . The max range of the cache can be controlled by the -XX:AutoBoxCacheMax JVM option.

This caching behavior is not applicable to Integer objects only. Similar to Integer.IntegerCache , we also have ByteCache , ShortCache , LongCache , CharacterCache for Byte , Short , Long , Character respectively.

Byte , Short , and Long have a fixed range for caching between -127 to 127 (inclusive), but for Character , the range is from 0 to 127 (inclusive). The range can be modified via argument only for Integer but not for others.

You can find the complete source code for this article on this GitHub repository, and please feel free to provide your valuable feedback in the comments section.

Разница между parseInt и valueOf в java?

В чем разница между этими двумя методами? Они, по-видимому, делают точно то же самое со мной (также относится к parseFloat() , parseDouble() , parseLong() и т. д., Чем они отличаются от Long.valueOf(string) ?

Edit: кроме того, какой из них предпочтительнее и чаще используется по соглашению?

12 Ответов

Итак, API для Integer.valueOf(String) действительно говорит, что String интерпретируется точно так же, как если бы оно было дано Integer.parseInt(String) . Однако valueOf(String) возвращает объект new Integer() , тогда как parseInt(String) возвращает примитив int .

Если вы хотите воспользоваться потенциальными преимуществами кэширования Integer.valueOf(int) , вы также можете использовать это бельмо на глазу:

Теперь, если вы хотите получить объект, а не примитив, то использование valueOf(String) может быть более привлекательным, чем создание нового объекта из parseInt(String) , потому что первый постоянно присутствует в Integer , Long , Double и т. д.

parseInt() возвращает примитивное целое число тип (int ), при котором valueOf возвращает java.lang.Integer, который является объектом представитель целого числа. Там есть ли обстоятельства, при которых вы могли бы захотеть целочисленный объект, а не примитивный тип.

Читать еще:  Java nio file nosuchfileexception

Конечно, еще одно очевидное отличие разве что intValue это метод экземпляра при этом parseInt — это статический метод.

Разница в том, что valueOf() возвращает Integer , а parseInt() — int (примитивный тип). Также обратите внимание, что valueOf() может возвращать кэшированный экземпляр Integer , что может привести к путанице результатов, когда результаты тестов == кажутся периодически правильными. До автобоксинга может быть разница в удобстве, после java 1.5 это действительно не имеет значения.

Кроме того, Integer.parseInt(s) также может принимать примитивный тип данных.

Посмотрите на источники Java: valueOf использует parseInt :

parseInt возвращает int

Integer.parseInt может просто вернуть int в качестве собственного типа.

Integer.valueOf может действительно потребоваться выделить целочисленный объект, если только это целое число не является одним из предварительно выделенных. Это стоит дороже.

Если вам нужен только собственный тип, используйте parseInt. Если вам нужен объект, используйте valueOf.

Кроме того, из-за этого потенциального распределения, автобоксинг на самом деле не является хорошей вещью во всех отношениях. Это может замедлить ход событий.

Потому что вы можете использовать jdk1.5+ , и там он автоматически преобразуется в int. Поэтому в вашем коде сначала возвращается целое число, а затем автоматически преобразуется в int.

ваш код такой же, как

Вариации parse* возвращают примитивные типы,а версии valueOf-объекты. Я полагаю, что версии valueOf также будут использовать внутренний пул ссылок, чтобы вернуть объект SAME для данного значения, а не просто другой экземпляр с тем же внутренним значением.

Поскольку valueOf возвращает новый целочисленный объект, почему приведенный ниже код является правильным?

Если вы проверите класс Integer, то обнаружите, что valueof вызывает метод parseInt. Большая разница заключается в кэшировании при вызове valueof API . Это кэш, если значение находится в диапазоне от -128 до 127, пожалуйста, найдите ниже ссылку для получения дополнительной информации

публичное статическое целое число valueOf(строка s)

    Аргумент интерпретируется как представляющий знаковое десятичное целое число, точно так же, как если бы аргумент был дан методу parseInt(java.lang.String).

Результатом является целочисленный объект, представляющий целочисленное значение, указанное строкой.

Другими словами, этот метод возвращает целочисленный объект, равный значению: новое целое число(Integer.parseInt(s))

Integer.parseInt принимает только строку и возвращает примитивный целочисленный тип (int).

Iteger.valueOf примите int и String. Если значение String, то valueOf преобразует его в простой int с помощью parseInt и возвращает новое целое число, если входное значение меньше -128 или больше 127. Если input находится в диапазоне (-128-127), он всегда возвращает целочисленные объекты из внутреннего IntegerCache. Integer class поддерживает внутренний статический класс IntegerCache, который действует как кэш и содержит целочисленные объекты от -128 до 127, и именно поэтому, когда мы пытаемся получить целочисленный объект для 127 (например), мы всегда получаем один и тот же объект.

Используйте Iteger.valueOf(200), если вы хотите получить новое целое число из int 200. Iteger.valueOf(127) не имеет никакого смысла, потому что это то же самое, что целое число = 127;

Если вы хотите преобразовать строку, например, в новое целое число или целое число, используйте Iteger.valueOf.

Если вы не хотите конвертировать строку в простой int, используйте Integer.parseInt. Это работает быстрее.

И сравнение Integer.valueOf(127) == Integer.valueOf(127) вернет true

Потому что он берет целочисленные объекты с одинаковыми ссылками из кэша.

Но Integer.valueOf(128) == Integer.valueOf(128) является ложным, потому что 128 находится вне диапазона IntegerCache и возвращает новое целое число, поэтому объекты будут иметь разные ссылки.

  1. В случае ValueOf — > это создание целого объекта. не примитивный тип и не статический метод.
  2. В случае ParseInt.ParseFloat — > он возвращает соответствующий примитивный тип. и это статический метод.

Мы должны использовать любой из них в зависимости от нашей потребности. В случае ValueOf, так как он создает экземпляр объекта. он будет потреблять больше ресурсов, если нам нужно только значение некоторого текста, то мы должны использовать parseInt,parseFloat и т. д.

Похожие вопросы:

Возможный Дубликат : Разница в поведении между parseInt() и parseFloat() var box = $(‘.box’), fontSize = parseInt(box.css(‘font-size’), 10) + 5; $(‘button’).on(‘click’, function() <.

В чем разница между parseInt(string) и Number(string) в JavaScript году?

При просмотре исходного кода для Integer.parseInt(String s, int radix) (java 8, 1.8.0_131), я нашел следующий блок комментариев: /* * WARNING: This method may be invoked early during VM.

Я новичок в java, и я пытаюсь сделать метод, который возвращает сумму цифр числа, скажем: input = 123 — > возвращает 6. Я использую строковый ввод (так как я также собираюсь связать строку с собой.

В чем же разница между ними new Date().valueOf() и new Date() * 1 Оба дают одинаковое значение, есть ли разница в производительности? (Просто из любопытства)

Я хочу знать, какой метод быстрее? Integer.valueOf(String string) или Integer.parseInt(String string) ? Есть ли разница в производительности или памяти между этими двумя подходами? Я видел разницу.

FirstOfAll plz помогите мне предоставить информацию о работе метода valueOf в разных объектах. Есть ли разница между String.prototype.valueOf и Object.prototype.valueOf метод, если существует.

В чем разница между следующими import java.util.Scanner; //Creating the scanner Scanner input=new Scanner(System.in); System.out.println(Enter the number 1); int number1=input.nextInt(); против int.

Почему два выражения ниже возвращают разные результаты? Date().valueOf() Fri Feb 07 2014 16:03:34 GMT-0500 (Eastern Standard Time) new Date().valueOf() 1391807020802 Date().toString() Fri Feb 07.

В чем разница между valueOf и copyValueOf . Я посмотрел на GrepCode, только чтобы обнаружить, что оба возвращают одно и то же. copyValueOf : Параметры : данные массива символов. Возвращается .

0 0 голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты 220 Вольт