Table of Contents
小故事" >小故事
Basic data types" >Basic data types
Reference type" >Reference type
Data type conversion" >Data type conversion
Cache pool" >Cache pool
Home Java javaTutorial Haven't learned Java data types? Because the posture is useless!

Haven't learned Java data types? Because the posture is useless!

Jul 26, 2023 pm 05:24 PM
java

小故事

Hello everyone, I am brother node, known as Brother Qing in the world. I recently read the very popular book "Java from Getting Started to Being Buried" I'm very fascinated. I heard that it ranks first in the sales rankings of major bookstores? It seems that there are still many friends who love to learn! They say knowledge changes destiny and Java makes life, so it seems that my decision to learn Java was the right one!

Haven't learned Java data types? Because the posture is useless!

But having said that, this book is really well written, but after all, I have just started, and I am still a little confused about some small knowledge points, such as the data types I just learned. , which is still a bit difficult for me with zero foundation.

On this day, I was bored and wandering around on CSDN and saw a blog: [Data Structure and Algorithm 05, Red-Black Tree After reading Understand~ 】. To be honest, I am very disdainful when I see articles like this. Red-black trees? What tree is it? Why is it half red and half black? Do you understand after reading this? What if I understand half of it? Isn't that a dystocia? snort! Let me show you what kind of monster you are.

With a little tap of my hand, I came in. I was very disapproving at first, but the further down the line, the more surprised I became... Two minutes later, I almost knelt down! This is so well written. I feel like it’s more detailed than what’s in the book (although I didn’t understand it)! Look at this full of useful information, this fresh and refined text, this full screen of [knowledge], how could I bear to miss it? Why don't you let him quickly go to my favorites to eat ashes? Watch me follow, like, and add to favorites, one after another, to make everything clear for the boss.

With excitement, I quietly clicked on the boss’s dialog box.

I: Boss, are you there?

After a while, the boss actually replied!

武哥: What’s the matter~?

Me: (I don’t know how to organize the words) Um... Boss... you are so handsome! So cool!

武哥: Harmful! Isn't this accepted?

: (With a black line on his forehead, I bet this guy is a bit narcissistic. I’m just trying to flatter him for business, but he’s quite proud of himself?) Haha~ Boss, that’s it, I am a newbie learning Java, can you help me?

武哥: Well...this...is also ok, I charge a fee

Me: (I thought I was indeed a big boss, and I still charge a fee) Big brother, I like Java very much. I recently bought a book to study. The title is "Java from Getting Started to Being Buried". I think this book is very good, but I have a little doubt and would like to ask some questions about learning. Do you think there can be a back door?

Brother Wu: Then... okay. Since you are so eager to learn, I will give you some pointers. Where have you learned now?

: I just learned the basics of Java, and I’m a little confused when I see the data structure~

武哥: That’s easy to say , it took me more than half a year to learn the basics of Java! The foundation is very solid. I can take you through this knowledge point together.

I: Really? Boss! Thank you so much! I'll treat you to dinner later!

武哥: Small problem, small problem. I see you are in Hefei too?

: Yes~ (A little panicked, quietly clicked on the boss’s profile, could it be...)

武哥: Haha, What a coincidence! I'm here too!

I: Aha? Such a coincidence? How about... (It seems like a meal can't escape, I cry...)

武哥: You add me on WeChat, I will send you a location, let's talk in detail .

I: (Is this...a face-to-face encounter? Only a few minutes of communication? Are all the big guys so coquettish? Although I am not willing in my heart, my body is very honest) emm... Okay, I'll be there right away...

Brother Wu: Okay, I'll wait for you~

I was trembling...there was a trace of panic in my heart!

Half an hour later, I took a taxi according to the address given by Brother Wu.

When I saw Brother Wu, as expected, he was extremely angry!

I saw Brother Wu slicking his hair back, applying some oil, leaning on the car at an angle of 45 degrees, looking up at the sky, lighting a cigarette, and feeling endless vicissitudes of life and loneliness.

I: (I bite the bullet and go up to say hello) Brother Wu?

武哥: (stopped smoking and glanced at me, his eyes a little confused): Hello? Are you a node brother?

: Well...yes (quietly takes a few steps back)

武哥: (Strides over and puts his arm around my shoulders) Let's go to a coffee shop, have a cup of coffee, and talk about Java. How about that?

Me: (I thought you were like this, but I still refused!) Okay...

So, Brother Wu hugged me and twisted. I went to Starbucks...and found a quiet private room...

I guess you can guess the next scene...

Ahem! Be serious! We are here to discuss learning!

What? You do not believe?

Then take a look below, Dry information warning!

Here comes the useful stuff

Java data There are many types. This article mainly summarizes them from four aspects: basic types, packaging types, reference types and cache pools.

Basic data types

The basic data types include byte, short, int, long, float, double, boolean, and char. Regarding their classification, I drew a picture.

Haven't learned Java data types? Because the posture is useless!
Basic types

Next, I will summarize it into a table from the aspects of byte count, data range, default value, and purpose, so that it is clear at a glance .

Haven't learned Java data types? Because the posture is useless!

Packaging data type

The basic types mentioned above have corresponding packaging types, for the convenience of readers , I also compiled a table.


Haven't learned Java data types? Because the posture is useless!


Reference type

In Java, reference type variables are very similar to C/C pointers. A reference type points to an object, and a variable pointing to an object is a reference variable. These variables are assigned a specific type when declared, such as Student, Dog, etc. Once a variable is declared, its type cannot be changed.

Objects and arrays are reference data types. The default value for all reference types is null. A reference variable can be used to refer to any compatible type. For example:

Dog dog = new Dog("旺财")。

Data type conversion

How to convert between packaging types and basic types?

Integer x = 2;     // 装箱 调用了 Integer.valueOf(2)
int y = x;         // 拆箱 调用了 X.intValue()

How to convert between basic types? There are two points:

  1. Forced type conversion must be used when converting a large-capacity type to a small-capacity type.

  2. # Converting small-capacity types to large-capacity types can be automatically converted.

For example:

int i =128;   
byte b = (byte)i;
long c = i;

Cache pool

Let’s think about a question: new What is the difference between Integer(123) and Integer.valueOf(123)?

Some people may know, some may not. In fact, they are very different.

  1. new Integer(123) 每次都会新建一个对象;

  2. Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。

我写个demo大家就知道了

Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y);    // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k);   // true

编译器会在自动装箱过程调用valueOf()方法,因此多个值相同且值在缓存池范围内的 Integer 实例使用自动装箱来创建,那么就会引用相同的对象。如:

Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true

valueOf()方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。我们看下源码就知道。

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

根据数据类型的不一样,这个缓存池的上下限也不同,比如这个 Integer,就是 -128~127。不过这个上界是可调的,在启动 jvm 的时候,通过 -XX:AutoBoxCacheMax=来指定这个缓冲池的大小,该选项在 JVM 初始化的时候会设定一个名为 java.lang.IntegerCache.high 系统属性,然后 IntegerCache 初始化的时候就会读取该系统属性来决定上界。

参考自StackOverflow:

https://stackoverflow.com/questions/9030817/differences-between-new-integer123-integer-valueof123-and-just-123

 

OK,关于Java数据类型的小知识就分享到这了,虽然我还有点意犹未尽…

Java 的数据类型虽然简单,但是里面还是有很多小细节值得我们玩味的,希望这篇文章能给大家带来一些帮助。

The above is the detailed content of Haven't learned Java data types? Because the posture is useless!. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1596
276
What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

PS oil paint filter greyed out fix PS oil paint filter greyed out fix Aug 18, 2025 am 01:25 AM

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

Building Cloud-Native Java Applications with Micronaut Building Cloud-Native Java Applications with Micronaut Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Fixed: Windows Is Showing 'A required privilege is not held by the client' Fixed: Windows Is Showing 'A required privilege is not held by the client' Aug 20, 2025 pm 12:02 PM

RuntheapplicationorcommandasAdministratorbyright-clickingandselecting"Runasadministrator"toensureelevatedprivilegesaregranted.2.CheckUserAccountControl(UAC)settingsbysearchingforUACintheStartmenuandsettingtheslidertothedefaultlevel(secondfr

See all articles