Is it ideal to use primitive types in Java?

Asked

Viewed 1,336 times

31

Java has several wrapper’s who help us (Integer, Double, BigDecimal), and also gives us the possibility to use primitive types (int, float, char).

A teacher told my college class that Java should not have support for primitive types of data, so much so that from Java 9 they will be obsolete (The teacher said, I don’t know if it’s true). Is that a fact? Why shouldn’t I use primitive types not even in a loop of repetition?

  • 2

    Strange, what I always hear is that primitives, when they attend the occasion, are better to be used than Wrappers. I will await a clarification on this as well. Good question +1

  • @diegofm yes I have seen many discussions on the subject, but I have never heard an explanation about whether or not to use, it leaves me very much in doubt.

  • You edited the question and complicated my answer, but I’ll give you an update.

  • I edited only the explanation the context and the question is identical.

  • tanto que a partir do *Java 9* ficaram depreciados *(O professor disse, não sei se é verdade '~') that part did not have in the original. I added now in the reply.

  • Sorry, I remembered after he had said that, I found it interesting to supplement the question.

  • @Felipepaetzold Now that it’s been a few days, what your teacher said after that?

  • @Victorstafusa I had the final exams at that time and I could not approach him to get the subject back, I will try to talk to him in my grade meeting in February, or through facebook, but this is a conversation that I prefer to have personally ^^

  • 2

    A year has passed, Java 9 has been launched, and the primitive types are there firm and strong. :)

Show 4 more comments

3 answers

28


He can have whatever opinion he wants. He said why? Always try to understand why, more than understand what. If he disagrees with what everyone does he should justify. Some people might think it’s premature optimization, but I find it very academicism to find this.

  • The so-called primitive types perform better. Not primitive types are references, with indirect access (this concept changes somewhat with newer versions of Java). The difference in performance is huge. Do a loop test with both.

  • They have a semantics expected by most people that their value has its own identity and do not always do what people are used to. A copy does not create a new identity.

    Integer x = 1000;
    Integer y = 1000;
    x == y //dá falso já que as identidades são diferentes apesar dos valores serem iguais
    

I put in the Github for future reference.

  • The "not primitive" types allocate space in the heap and puts pressure on the garbage collector. Primitives allocate in the stack and management is simple and fast. They even waste a lot of memory because of overhead natural that objects possess. Again this has changed a little in some cases.

  • The primitive types will not have problems of NullPointerException.

  • In the specific case of Java the syntax of primitive types is more convenient than the primitive types. Primitive types do not need to use equals(), for example, but this may be changing, at least in part.

There are other problems with not using primitive types that I’m not remembering. Probably the use of nonprimitives make it difficult to resolve the choice of Overload of methods.

So it’s ideal, yes, whenever possible. Even C# has a way of creating types by their own value - which are the primitives - and Java has proposed to have the same in the next two versions (if not already implemented when reading this), so useful that it is. And it will be confusing when this happens, because the term will be ambiguous within what Java has always used and some of the things I’ve said here won’t even be 100% true anymore, it won’t change the fact, but the definition (so I had to edit to say that some things have changed).

Use the shape boxed only when there is a reason for it.

Some people like to think linear, others are more pragmatic and choose the best tool for the job.

If he gave or give a justification put here for us.

Discontinuation

That is totally inappropriate. I don’t know if you’re expressing anything other than what he actually said, but if this happened almost 100% of the code written in Java would stop working. And frankly, a statement like that puts the credibility of the person at risk.

Not only is there no proposal to discontinue this feature of language, but to contemplate it would be completely absurd. On the contrary, as I said, they should be extended in future version (it was foreseen in Java 10, but changed everything in the version scheme, who knows in 15) and you can create your own types by value which are the primitive types. See the official proposal.

See more in What is considered primitive in a programming language?.

  • Thank you for the answer, I will look for it and ask a justification.

  • I believe he’s confused with the term disparage, he’s an excellent teacher and he understands very well, maybe he wasn’t on a good day :/

  • Or you might have understood a little different than what he said? :)

  • Not the term used was depreciated.

  • But he may have used in another context, he may have spoken of something specific and not the whole concept of primitive type.

  • It is possible, anyway, I will come back to the subject with him.

  • @bigown the issue of a java version not having previous compatible features would not be a big surprise.

  • 1

    @pmargreff until I understand, but this would make all applications impossible, except one Hello World :)

Show 3 more comments

19

The new features that have been added to Java 9 are:

  • Jshell - A Java command interpreter.
  • Javadoc with HTML 5 and search using jQuery.
  • Simplification of cross-compilation (cross-compiling) for older versions in the compiler.
  • Annotation @Deprecated improved.
  • Improvements in operating system process control (for example: support for Kill).
  • StackWalker to inspect the execution stack.
  • Factories of immutable collections.
  • HTTP2 client with websocket.
  • New modularization with the introduction of the concept of modules above that of packages.
  • Improvements in the Locking.
  • UTF-8 Properties Files.
  • Implementation of the DTLS transport protocol.
  • Unicode 7 and 8, including support for various new emojis.
  • Discontinuation of Applets.
  • Unified logging of the JVM.
  • Support TIFF images already included by default.
  • Compilation Ahead-of-time.
  • Compact strings. In Java 9, Strings internally use an array of byte (primitive), instead of an array of char.
  • Private method in interfaces.
  • Several other more internal and obscure changes.

Behold here the complete list of Features.

At no time did anyone talk about the possibility of removing the primitive types.

Inclusive, see here in the class source code Integer, Java 9, on line 1101 that the class Integer is implemented by means of an object containing a field final of the kind int. This has been so since the beginnings of Java when it was still called Oak and has not changed until now.

Moreover, if int was discontinued, so why the method int parseInt(String) was not discontinued as well? The answer is because int is not discontinued at all.

What was discontinued was the builder of Integer who receives a int as a parameter. The reason is that using such a constructor is bad programming practice. It is recommended to use the method Integer.valueOf(int). Analogous cases in other packaging classes also occur.

There is one thing internal in the JVM where it can optimize and simplify some cases where packaging classes are used and transform them for primitive types. With this, the difference between the use of packaging classes and primitive classes decreases. But to go from that to say that primitive types will become obsolete is nonsense.

  • I’ve been looking at the link you refer to as full list of Ports and found no reference to "Private method on interfaces". Where can I find it?

  • @It’s one of the things about Milling Project Coin, of JEP 213: http://openjdk.java.net/jeps/213 - See here the Feature request: https://bugs.openjdk.java.net/browse/JDK-8071453

12

Another important reason that should be taken into account when using or not using Boxed types (Integer, Float, etc.), also known for Wrappers, is that its classes are immutable (just like the class String). This means that you will be instantiating a new object for any content changes that the variable undergoes (except for integers in range -128 to 127, see end of response). So if you do this:

Integer i = 0;    
i++;

Then a new object of the type Integer will be instantiated (when you do i++), in the same way as with any String when you change the contents of the variable. Therefore, the above code is much slower than doing the same with a primitive type.

Another way to see this problem of immutability applied in that context:

Run the code below:

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Then run that:

    long start = System.currentTimeMillis();
    for (Integer i = 0; i < 1000000000; i++) ;
    long end = System.currentTimeMillis();
    System.out.println(end - start);

Note that the time difference is abysmal.

The Boxed types have not been introduced to replace the primitive types, they have been introduced as a mechanism to facilitate that primitive types are passed as a parameter where their corresponding class is expected. A classic example is when you need to add a int in a Collection of Integer.

@Victorstafusa made an important observation. If the integer is in the range -128 to 127, then a new instance will not be created, as Java caches for instances Integer in the meantime. See: /a/3381/3084

  • "This means that you will be instantiating a new object for any content changes that the variable undergoes." - This is a half-truth. Java maintains a cache for instances of Integer by default from -128 to 127. See more in this answer: http://answall.com/a/3381/132

  • Thanks @Victorstafusa! I’ve updated my reply.

  • Excellent response!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.