• Post Reply Bookmark Topic Watch Topic
  • New Topic

Asking about Integer  RSS feed

 
Jackson Steward
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class like this:
   

What does this part mean



And can I replace Integer with int in this java code?

I am still a novice so any details will help. Thanks in advance.

thank
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

The thing with the question mark and colon is called the ternary operator. In this case, it means: if freq is null, then take 1, otherwise take freq + 1.

In this code, you cannot replace Integer by int. That would cause a NullPointerException in line 8 if the Map does not contain an entry for the word that is being looked up in the map.

But in general, it's better to use the primitive types such as int instead of the wrapper types such as Integer, because primitive types are more efficient for the JVM to process. Only use the wrapper classes (Integer etc.) if you have a good reason to do so. In this case, there is a good reason.
 
Paweł Baczyński
Bartender
Posts: 2077
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, in Java 8 you can use merge method for this logic:
 
Jackson Steward
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:Welcome to the Ranch.

The thing with the question mark and colon is called the ternary operator. In this case, it means: if freq is null, then take 1, otherwise take freq + 1.

In this code, you cannot replace Integer by int. That would cause a NullPointerException in line 8 if the Map does not contain an entry for the word that is being looked up in the map.

But in general, it's better to use the primitive types such as int instead of the wrapper types such as Integer, because primitive types are more efficient for the JVM to process. Only use the wrapper classes (Integer etc.) if you have a good reason to do so. In this case, there is a good reason.


Thank you for such a detailed answer.

And by the way, is this only normal logical operator or any kind of special syntax? Thanks.
 
Paweł Baczyński
Bartender
Posts: 2077
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is called ternary operator.

You can read about it here.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!