What is the difference between declaring and defining in Java
.
I am trying to find an proper answer, but I'm not able to get one.
Please explain.
What is the difference between declaring and defining in Java
.
I am trying to find an proper answer, but I'm not able to get one.
Please explain.
When you declare a variable, a function, or even a class all you are doing is saying: there is something with this name, and it has this type. The compiler can then handle most (but not all) uses of that name without needing the full definition of that name. Declaring a value--without defining it--allows you to write code that the compiler can understand without having to put all of the details. This is particularly useful if you are working with multiple source files, and you need to use a function in multiple files. You don't want to put the body of the function in multiple files, but you do need to provide a declaration for it
What does it mean to define a variable, exactly? It means you are telling the compiler where to create the storage for that variable
Declaration vs Definition: In Summary
A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols.
Declaring a variable simply creates memory for the variable and assigns it a default value. i.e int x;
Since you did not define a value for x, the default will be 0.
Defining a variable is declaring with an initial value i.e int x = 5;