Difference between primitive type and object in Java

Asked

Viewed 3,493 times

3

In Java, we have so-called primitive types and so-called objects. What’s the difference between the two?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

8

Let’s understand In programming, what is an object?. So all data is objects.

There is a misconception that there are only objects in object-oriented programming. If this were true, what would you call what is not an object?

When you talk primitive, you’re using an adjective, so alone it doesn’t make sense. So when you use that term you’re referring to what, as being primitive? It’s a primitive object! We could call it a rudimentary object as opposed to the complex object, although some languages use the primitive term for objects that are also complex on some level.

In C# "everything" is object in the sense of OOP, i.e., "everything" derives from Object, there is no idea of primitive types. And Java has now begun to abandon this idea as well (there will still be primitive types, but it will only be a specialization of types by value that will also derive from Object). I want to see how they will call these new types that do not fit the definition of primitive and nor the object that initially the language defined, is what gives wrong define in the beginning.

Perhaps primitive types would be those that do not derive from Object. A wrong idea for a language that says totally OO.

So let’s differentiate what is derived from Object and what is a general object.

In Java, only classes could derive from Object, but this changes starting in version 14 (if nothing happens delay, it was to be in 10). Anyway all data are objects, some have taxinomy that indicates the name Object in its hierarchy, others do not possess it.

Taxonomy is hierarchical, everything has several levels of classification. Each individualized data is an object, no matter specific characteristics, some conform to Object. Object and object are different things, on different levels, define different characteristics, just have the same name.

It is often said that:

The two most difficult computing problems are cache invalidation and naming things

-- Phil Karlton.

When we have difficulties using the right names, in the right contexts we have difficulties understanding the problems correctly. That’s why OOP is so hard, it requires that you classify everything correctly to work well and if you do it wrong it’s hard to fix later. And the Internet, or even other sources, is full of wrong names (example). Only right view leads us the right way.

I’m not saying that my understanding is the right one, anyone can question it, but it’s what you use in your environment when you think about what you’re using.

The term object has always been used in all languages long before OOP became fashionable or even existed. We can’t ignore that term because fashion has decided to appropriate the term for you. Even worse if a language was poorly conceptualized and is now having difficulties explaining what is right and implementing the mechanism necessary for what it has idealized from the start.

The class-based type generates an object derived from Object. If a primitive type does not generate an object, it generates what then?

To give more context, the doubt originated in my answer (see comment also) on another AP question. So every object exists only when it is instantiated, and what changes in instantiation only depends on whether the type is by value (the bad primitive term) or by reference. Allocation cannot define whether it is an object or not, it always is, no matter if it is in stack or heap, whether you have a reference to it or not.

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

  • 1

    as you say, "Java today", in theory, informs that there are primitive types and that there are objects. If there is such a difference in Java’s handling of these matters, then why would it be incorrect to say that there are differences?

  • 1

    I guess you didn’t read the answer carefully.

  • I don’t think I understand what you mean. First of all, you write that all data is objects. This makes me think that you do not differentiate primitive type of object. In the end, you write that every object exists only when it is instantiated. This makes me think that now you differentiate primitive type of object, because in Java, currently, instantiation would be the creation of an object, and that primitive types are not instantiable. You understand how I don’t understand your answer?

  • I imagine you have problems interpreting text or understanding grammar and are drawing conclusions that are not in the text. And I think you’re so caught up in the misconception that you’ve learned that you can’t read this text without a bias. Forget all wrong understanding and read calmly, paying attention, reflecting on what is written. I edited the other answer in the original question to see if it is easier to understand. And I strongly suggest following the links that stand to have a more universal understanding on the subject.

  • Okay, take it easy. I’m a beginner in Java. And, your text is not that understandable. Let me see if I understand your thinking. You recognize that in Java you have the primitive types and the ones by reference, but in your way of thinking all the data are objects, and regardless of what is being instantiated (type by value or by reference). As for allocation, are you referring to what we know as stack and heap? That is, the data, independent of the memory area where it is allocated, is an object?

  • That’s right, this whole part is right.

  • @Maniero, in this case then you refer to the instance in a platonic sense? Type 1 is a "material" representation of an integer ideal, so it is an instance of the integers?

  • 1

    @Jeffersonquesado this (I think, if I understood what I said). Why? Has a different view?

  • @Maniero no, my vision was the same. Just to put drops in i’s, confirm my understanding

  • 1

    But it is concrete (from the computer point of view, I will not enter into the discussion that in the computer everything is abstract except the electrons). Because the 1 of a int should be different from 1 of a Integer, except for the fact that the second has a reference to it, and allocated in the heap, save some optimization? Both are instances of my value. Although they have the same value, they have no identity, they are different objects, they are distinct instances of the same model, one direct and one indirect.

  • @Maniero understands your thinking, but I would like to draw attention to the question you have in your context the Java programming language. Currently, Java differentiates types by value and types by reference. And, I would like to have an answer in the context that the question fits.

  • @Alexandres.V.Oliveira and the answer considers it. Alias, she’s all about it. I answered what you asked. If it was specifically about the difference between types by value and types by reference, you should have a question about that. , And the question would have been closed as duplicate already who answer on this site. But it wouldn’t make much sense to be about that because what gave rise to that question was https://answall.com/questions/274048/array-e-o-tipo-que-est%C3%a1-being-created#comment560840_274053. You still have a bias and you’re not reading what I wrote.

  • @I am not biased. I am open-minded to learn. I take into account all the answers and/or comments.

Show 8 more comments

1

Java has two types of data that are divided by value (tipos primitivos) and by reference (tipos por referência).

The primitive types are boolean, byte, char, short, int, long, float e double. Reference types are classes that specify object types Strings, Primitive Arrays and Objects.

A primitive type variable can store exactly one value of its declared type at a time, when another value is assigned to that variable, its initial value will be replaced.

Primitive type instance variables are initialized by default, type variables byte, char, short, int, long, float e double are initialized as 0, and variables of type boolean are initialized as false. These types can specify their own starting value for a primitive type variable by assigning a value to the variable in its declaration.

Java provides two primitive types for storing floating point numbers in memory, the float and double type.

The difference between them is that the double variables can store numbers with greater magnitude and more details, i.e., it stores more digits to the right of the decimal fraction point, than the float variables. Float type variables represent simple precision floating point numbers and can represent up to 7 digits.

Double type variables represent double precision floating point numbers, where they need twice the amount of memory of the float variables providing 15 digits, being twice the accuracy of float variables. Double values are known as floating point literals. For precise floating point numbers, Java provides the Bigdecimal class (java.Math package).

Listing 2: Example of primitive type sizes

public class Datatypes {

public static void main(String[] args) {
    System.out.println("Tipos de dados em Java: \n" +
            "\nMenor Byte: " + Byte.MIN_VALUE +
            "\nMaior Byte: " + Byte.MAX_VALUE +
            "\nMenor Short Int: " + Short.MIN_VALUE +
            "\nMaior Short Int: " + Short.MAX_VALUE +
            "\nMenor Int: " + Integer.MIN_VALUE +
            "\nMaior Int: " + Integer.MAX_VALUE +
            "\nMenor Long: " + Long.MIN_VALUE +
            "\nMaior Long:" + Long.MAX_VALUE +
            "\nMenor Float: " + Float.MIN_VALUE +
            "\nMaior Float: " + Float.MAX_VALUE +
            "\nMenor Double: " + Double.MIN_VALUE +
            "\nMaior Double: " + Double.MAX_VALUE);

}

} Listing 3: Declaration of primitive types

public class Tipos_Primitivos {
    public static void main(String[] args) {
          byte tipoByte = 127;
          short tipoShort = 32767;
          char tipoChar = 'C';
          float tipoFloat = 2.6f;
          double tipoDouble = 3.59;
          int tipoInt = 2147483647;
          long tipoLong = 9223372036854775807L;
          boolean tipoBooleano = true;
          System.out.println("Valor do tipoByte = " + tipoByte);
          System.out.println("Valor do tipoShort = " + tipoShort);
          System.out.println("Valor do tipoChar = " + tipoChar); 
          System.out.println("Valor do tipoFloat = " + tipoFloat);
          System.out.println("Valor do tipoDouble = " + tipoDouble);
          System.out.println("Valor do tipoInt = " + tipoInt);
          System.out.println("Valor do tipoLong = " + tipoLong);
          System.out.println("Valor do tipoBooleano = " + tipoBooleano);
    }
}

In List 3 the type declared as char is always declared with simple quotes because the size is only 1 character. The float types will always have the character "f" at the end of the value for their identification, being the same thing with the long type only that is inserted the character "L".

Types by reference Programs use type variables by reference to store object locations in computer memory. These objects that are referenced can contain various instance variables and methods within the pointed object.

To bring in an object its instance methods, it is necessary to have reference to some object. Reference variables are initialized with the value "null" (null).

For example, ClasseConta acao = new ClasseConta(), creates a class object ClasseConta and the action variable contains a reference to that object ClasseConta, where you can invoke all your class methods and attributes. The new keyword prompts system memory to store an object and initializes the object.

Listing 4: Example accessing an object method

public class AcessaMetodo {

    public void imprime(){
        System.out.println("Bem Vindo ao Java!");
    }

    public static void main(String[] args) {
        AcessaMetodo acessa = new AcessaMetodo ();
        acessa.imprime();

    }

}

The output of this code above will be reproduced through the access action.imprime(), because is being accessed the method of the object that was initialized with the variable defined as "access".

Final considerations The variables of tipos por valor não referenciam objetos, these types of variables cannot be used to invoke methods. Remember that local variables are not initialized by default (variables within methods). Variables of the primitive type cannot be initialized as a reference to an object.

Source:https://www.devmedia.com.br/tipos-de-dados-por-valor-e-por-referencia-em-java/25293

Classes Wrappers in Java

  • within the context in which the question is inserted, your answer answers my question. " A primitive type variable can store exactly one value of its declared type at a time, when another value is assigned to that variable, its initial value will be replaced". " Types by reference Programs use type variables by reference to store object locations in computer memory. These objects that are referenced can contain various instance variables and methods within the pointed object."

  • yes, @Alexandres.V.Oliveira

  • @Alexandres.V.Oliveira the question itself has no context, it is very simple to have a context. Is the context in the comments that culminated in https://answall.com/questions/274048/array-e-o-tipo-que-est%C3%a1-being-created/274053? noredirect=1#comment560864_274053. I should have put that context. LR10 did not know this context. I gave the answer I promised there. And there’s a link about types by value and types by reference. Note that you don’t use these terms anywhere in this question, use two terms: primitive type and object (lowercase). You still find object

  • is synonymous with type by reference, and primitive type is synonymous with type by value, and is not. All this is explained in my answer. In addition to this answer speak of something outside the real context (because the question did not clarify), it has errors in it, despite being right in large part, but does not say what is the real difference between the two terms asked.

Browser other questions tagged

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