What’s the difference in instantiating, initializing, and declaring a variable?

Asked

Viewed 6,067 times

13

Many articles on the Internet refer to these verbs, regardless of the programming language. But sometimes they are all confused or exchanged, which creates a lot of confusion.

Which means "instantiate", "initialize" and "declare" a variable?

2 answers

13


The definition of "declare" can be found in What is the difference between declaration and definition?.

"Initialize" we can say that is synonymous with assigning a first value, not necessarily in the statement.

"Instantiating" is creating an object, is mounting in memory a value for this object.

Object has nothing to do with object-oriented programming, objects exist in all paradigms.

You can instantiate an object and:

  • put a value during variable declaration
  • initialize a variable at another point after the declaration
  • assign to a previously initialized variable, thus changing its value
  • pass as argument to a parameter
  • not store in variable.

An element of a array, collection or a member of another object is also a variable.

When you do

var x = 1;

You are declaring a variable, initiating it with an instantiated value. This value is an instance of the type number in JS, or int in C# or Java. A type string could be:

var a = "teste";

Some instances do not have literals in the language and need to use constructors:

var i = new Classe(10, "texto");

I put in the Github for future reference.

The variable i store an instance (an object) of type Classe (in fact a reference to this instance).

Some objects are by other value by reference, that changes the lifespan and possibly the memory location to be stored.

1

Being very simple and objective to your question...

Which means "instantiate", "initialize" and "declare" a variable?

Instantiate refers to a class. Then you will instantiate in a variable the class.

var pessoa = new Pessoa()

Initialize nothing more than you assign a value to a variable. For example, you cannot at certain times work with attributes of an object if you do not say before that this variable is an object. In this case, we initialize the variable before using it. We just make it exist before anything else.

var variavel = null;
var pessoa_object = {};

Declare is similar to initializing, but you don’t necessarily need to assign a value.

int idade;
  • 1

    I’m sorry, but I believe your definition of "declare" is wrong. I can declare an object and leave it in an uninitialized state, including this is a build error in Java, while in JS it will give an undefined object error

  • 1

    I edited. Really, I don’t necessarily need to assign a value when declaring a variable, other than initializing. Thank you

Browser other questions tagged

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