Table of Contents
Knowledge point 1: The difference between integer and int" >Knowledge point 1: The difference between integer and int
Knowledge point 2: Detailed explanation of integer.values() method" >Knowledge point 2: Detailed explanation of integer.values() method
Home Java javaTutorial The difference between integer and int and the detailed explanation of integer.values() method

The difference between integer and int and the detailed explanation of integer.values() method

Jun 26, 2017 am 10:20 AM
integer the difference method

Statement: This article is a reprinted article by the blogger. The original address can be found at the end of the article.

Knowledge point 1: The difference between integer and int

/*
* int is the 8 primitive types provided by java One of the data types. Java provides wrapper classes for each primitive type. Integer is the wrapper class provided by java for int. The default value of int is 0,
* and the default value of Integer is null
*, that is, Integer can distinguish the difference between unassigned value and value 0, int It is impossible to express the unassigned situation. For example, if you want to express the difference between not taking the exam and the exam score being 0
*, you can only use Integer
*. In JSP development, the default value of Integer is null, so when the el expression is used to display it in the text box, the value is a blank string, and the default value of int is 0, so when the el expression is used to display it in the text box
* , the result is 0, so int is not suitable as the form data type of the web layer.
* In Hibernate, if the OID is defined as an Integer type, then Hibernate can determine whether an object is temporary based on whether its value is null
* , if the OID is defined as int type, you also need to set its unsaved-value attribute to 0 in the hbm mapping file.
* In addition, Integer provides multiple integer-related operation methods, such as converting a string into an integer. Integer also defines constants that represent the maximum and minimum values ​​of integers.

*/

Knowledge point 2: Detailed explanation of integer.values() method

Why does the first judgment return true and the second judgment returns false? Is there any difference between 127 and 128 that I don’t know? (Of course, except 127 is less than 128...)

Also, why does the third judgment return Got true?
I read the answers to another related question, but I still don’t know when they return true and why the second judgment returns false.

Answer #1:

Integer.valueOf(String) does have an unusual behavior.

valueOf will return an Integer (integer) object when the string being processed is between -128 and 127 (inclusive boundaries), the returned object is pre-cached. This is why the call in the first line returns true-127

This integer object is cached (so twice valueOf The same object is returned) - the call in the second line returns false because 128 is not cached, so each call will generate a new integer object,

So the two 128integer objects are different objects.

The important thing is that you need to know that in the above comparison, what you are actually comparing is the object reference returned by integer.valueOf, so when you compare outside the cache When an integer object is used, the equality judgment will not return true, even if you

pass a valueOf value that is equal, it will be useless. (Like Integer.valueOf(128)==Integer.valueOf(128)) in the second line. If you want this judgment to return true, you need to use the equals() method.

parseInt() returns not an integer object, but a int type basic element. This is why the last judgment will return true. In the third line of judgment, when judging equality, the actual comparison is 128 == 128,

so It must be equal.

Let’s talk about a little difference in the third comparison, which makes its result different from the second comparison:

an unboxing conversion (a conversion during comparison, which converts the The conversion of the object reference to its corresponding atomic type) occurs in the comparison on line 3. Because the comparison operator uses == and there is a

int

type and a Integer object reference on both sides of the equal sign . In this case, the Integer object returned on the right side of the equal sign is further converted into an int value before being equal to the left side.

So after the conversion is completed, what you are actually comparing are two atomic integer values. This conversion is exactly what you'd expect to see when comparing two atomic types, so you end up comparing 128 equals 128.

Answer #2: The

Integer class has a static cache that stores 256 special Integer objects - each object corresponds to a value between `-128 and 127.
With this concept, you can know the difference between the above three lines of code.

##1
2
3
System.out.println(Integer.valueOf("127")==Integer.valueOf("127" ));
System.out.println(Integer.valueOf("128")==Integer.valueOf( "128"));
System.out.println(Integer.parseInt("128")==Integer.valueOf("128"));

Shows that a new Integer object is created.

##1
##new Integer(123);
##1
##Integer.parseInt(
"123");
##Return after parsing the string A
int
value.

##1##This situation is better than others It's a little more complicated. String parsing is done first, and then if the parsed value is between -128 and
#Integer.valueOf(
"123"
);
127
, the object is returned from the static cache. If it exceeds this range, the

Integer() method will be called and the parsed value will be passed in as a parameter to get a new object. Now, let’s look at the 3 expressions in the question.

##1
#Integer.valueOf()==Integer.valueOf(, because the value of Integer is fetched 2 times from the static cache, the expression Returns the result of comparing the object with itself. Because there is only one Integer object, the return result is
"127"
"127"
);
The above expression returns
true
true
.

##1

#Integer.valueOf("128""128"
)==Integer.valueOf(
);

The above expression returns false because 128 no static buffer exists. So every time when equality is determined, new Integer objects will be created on both sides of the equation. Since the two Integer objects are different, == will return

true

only when both sides of the equation represent the same object. Therefore, the above equation returns false.

##1
##Integer.parseInt(
"128")==Integer.valueOf("128");
The above expression compares the original
int

value 128 on the left with the newly created Integer on the right Object. But because the comparison between int and Integer is meaningless, Java will automatically unbox Integer before comparison, so the final thing is # Comparison between ##int

and

int values. Since 128 is equal to itself, true is returned.

The above is the detailed content of The difference between integer and int and the detailed explanation of integer.values() method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek What is the difference between r1 and v3 version deepseek What is the difference between r1 and v3 version Feb 19, 2025 pm 03:24 PM

DeepSeek: In-depth comparison between R1 and V3 versions helps you choose the best AI assistant! DeepSeek already has tens of millions of users, and its AI dialogue function has been well received. But are you confused when facing the R1 and V3 versions? This article will explain the differences between the two in detail to help you choose the most suitable version. The core difference between DeepSeekR1 and V3 version: Features The design goal of the V3 version focuses on complex problem reasoning, deep logic analysis, multi-functional large language model, focusing on scalability and efficiency architecture and parameter reinforcement learning optimization architecture, parameter scale 1.5 billion to 70 billion MoE hybrid Expert architecture, total parameters are as high as 671 billion, each token is activated by 37 billion

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

Does Bitcoin have stocks? Does Bitcoin have equity? Does Bitcoin have stocks? Does Bitcoin have equity? Mar 03, 2025 pm 06:42 PM

The cryptocurrency market is booming, and Bitcoin, as a leader, has attracted the attention of many investors. Many people are curious: Do Bitcoin have stocks? The answer is no. Bitcoin itself is not a stock, but investors can indirectly invest in Bitcoin-related assets through various channels, which will be explained in detail in this article. Alternatives to Bitcoin Investment: Instead of investing directly in Bitcoin, investors can participate in the Bitcoin market by: Bitcoin ETF: This is a fund traded on the stock trading market, whose asset portfolio contains Bitcoin or Bitcoin futures contracts. This is a relatively convenient option for investors who are accustomed to stock investments, without having to hold Bitcoin directly. Bitcoin Mining Company Stocks: These companies' business is Bitcoin mining and holding Bitcoin

What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading Mar 03, 2025 pm 11:54 PM

In traditional financial markets, pre-market and after-market trading refers to trading activities outside the regular trading period. Although the cryptocurrency market is trading around the clock, trading platforms like Bitget also offer similar features, especially some comprehensive platforms that trade stocks and cryptocurrencies at the same time. This article will clarify the differences in pre-market and after-market trading and explore its impact on currency price. Four major differences between pre-market and after-market trading: The main differences between pre-market and after-market trading and regular trading periods are in four aspects: trading time, liquidity, price fluctuations and trading volume: Trading time: Pre-market trading occurs before the official trading starts, and after-market trading is carried out after the regular trading ends. Liquidity: The liquidity of pre- and after-hours trading is low, there are few traders, and the bid and offer price difference is large; while the liquidity is high during the regular trading period, the price is

Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Mar 04, 2025 pm 04:06 PM

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI ​​market is mature, Bittensor faces competitive risks and may be subject to other open source

Is there any difference between South Korean Bitcoin and domestic Bitcoin? Is there any difference between South Korean Bitcoin and domestic Bitcoin? Mar 05, 2025 pm 06:51 PM

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

Pepe bought and sold out in a big way, is MUTM a smarter investment in 2025? Pepe bought and sold out in a big way, is MUTM a smarter investment in 2025? Mar 03, 2025 pm 07:09 PM

After the surge in PEPE, can MUTM become a more stable investment choice in 2025? PEPE (PEPE) has made early investors profitable, but its violent price fluctuations have also made many people question its long-term prospects. As the meme currency market continues to turbulently, traders are beginning to focus on projects with more fundamental advantages, and MutuumFinance (MUTM) is one of them. This is a decentralized lending platform focusing on practical financial applications. Unlike PEPE, which relies on speculative speculation, MUTM builds a structured DeFi ecosystem where users can borrow and earn passive income. Its pre-sale has exceeded one million US dollars, the first phase of token sales rate exceeds 97%, early investment

Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Mar 04, 2025 am 10:21 AM

Artificial intelligence agents (AIAgents) are rapidly integrating into daily operations of enterprises, from large companies to small businesses, almost all areas have begun to be used, including sales, marketing, finance, law, IT, project management, logistics, customer service and workflow automation. We are moving from an era of manual processing of data, performing repetitive tasks, and using Excel tables to an era of autonomous operation by AI agents around the clock, which not only improves efficiency but also significantly reduces costs. Application case of AI agents in Web2: YCombinator's Perspective Apten: A sales and marketing optimization tool combining AI and SMS technology. BildAI: A model that can read architectural blueprints,

See all articles