Alan2
Alan2

Reputation: 24562

What is the difference between declaration and definition in Java?

I'm very confused between the two terms. I checked on stackoverflow and there's a similar question for C++ but not for java.

Can someone explain the difference between the two terms for java?

Upvotes: 92

Views: 90923

Answers (8)

aioobe
aioobe

Reputation: 420921

The conceptual difference is simple:

  • Declaration: You are declaring that something exists, such as a class, function or variable. You don't say anything about what that class or function looks like, you just say that it exists.

  • Definition: You define how something is implemented, such as a class, function or variable, i.e. you say what it actually is.

In Java, there is little difference between the two, and formally speaking, a declaration includes not only the identifier, but also it's definition. Here is how I personally interpret the terms in detail:

  • Classes: Java doesn't really separate declarations and definitions as C++ does (in header and cpp files). You define them at the point where you declare them.

  • Functions: When you're writing an interface (or an abstract class), you could say that you're declaring a function, without defining it. Ordinary functions however, are always defined right where they are declared. See the body of the function as its definition if you like.

  • Variables: A variable declaration could look like this:

    int x;
    

    (you're declaring that a variable x exists and has type int) either if it's a local variable or member field. In Java, there's no information left about x to define, except possible what values it shall hold, which is determined by the assignments to it.

Here's a rough summary of how I use the terms:

abstract class SomeClass {                // class decl.
                                          //                           \
    int x;                                // variable decl.            |
                                          //                           |
    public abstract void someMethod();    // function decl.            |
                                          //                           |
    public int someOtherMethod() {        // function decl.            |
                                          //                           | class
        if (Math.random() > .5)           // \                         | def.
            return x;                     //  |  function definition   |
        else                              //  |                        |
            return -x;                    // /                         |
                                          //                           |
    }                                     //                           |
}                                         //                          /

Upvotes: 113

Stephen C
Stephen C

Reputation: 718688

The Java Language Specification specifies and uses the term "declaration" extensively, but it does not use "definition" except as a normal English word.

My evidence is that the term "declaration" appears a number of times in the JLS table of contents and in the index. By contrast, the word "definition" does not appear in either the table of contents or the index.

So, when you see someone use the word "definition" in the context of Java, they are either using it in the non-technical sense, or they are being sloppy with their terminology.

In the latter case, they might mean the same thing as the technical term "declaration", or they might mean something else. And if they mean something else, you need to ask them what they mean. If they have defined it ... fair enough, but it is not standard terminology.


The answers that state that "definition" refers to the point at which the variable is initialized are specifically not supported by the Java Language Specification. In Java, initialization of a variable either happens at the point of declaration, or in a later assignment. In the latter case, no special term is used ... or needed ... apart from assignment and / or initialization. There is no specified point at which storage is allocated for the variable. Indeed, the chances are that the space for the variable itself is allocated before the declaration is reached.


The reason that the "definition" term is not used in Java in the JLS spec is that it is not needed.

  • Since Java allows members to be declared in any order, there is no need for "forward declarations". That is the context where there it is necessary to distinguish between the two concepts.
  • In Java the stack space required for a variable is a compile time constant, so the stack offset calculations happen at compile time. (Remember that in Java, an array is a reference to a heap object ... and only the reference is held in the stack frame.)
  • The way that Java handles "definition without initialization" of a field or variable does not require a single "declaration" point. If an initialization of a variable is required, it may happen at multiple points in the source code.

(The only place in Java where they might have used declaration versus definition is in abstract methods. Except that if they had done, the would have had to refer to a regular method declaration as a definition ... for consistency ... and that would be confusing. So they just call the "abstract" subcase an declaration of an abstract method.)

C and C++ handle these things differently, and hence do need distinct "declaration" and "definition" terms in their technical descriptions. My take on the "Sun Glossary" definitions are that they are C / C++ -centric.

Upvotes: 32

Will Hawkins
Will Hawkins

Reputation: 111

I just wanted to reiterate that @stephen-c's answer was excellent. However, I believe that it needs a slight tweak. The JLS does use the term "definition" outside of its natural-language meaning in a few places. I believe that this only confuses the otherwise clean language in the specification that focuses the reader's attention on declarations instead of definitions. Consider the bottom of example 15.12.2-1.:

If a third definition of test were added:

static void test(ColoredPoint p, ColoredPoint q) {
    System.out.println("(ColoredPoint, ColoredPoint)");
}

then it would be more specific than the other two, and the method invocation would no longer be ambiguous.

Again, I wish that they had not included these few errant uses of definition which would have helped their focus on declaration instead of definition that much more obvious.

Oh well.

Upvotes: 0

shraddha patel
shraddha patel

Reputation: 41

Declaration: The declaration concept includes notifying the compiler about properties of the variable such as its name, type of value it holds and the initial value if any it takes.

Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable.

 public class JavaDemo{
       public static void main(String args[]){
          int a; // declaration of variable
          a=10; // definition of variable
          functionA(a); // declaration of function
       }
       public static void functionA(int a){
          System.out.println("value of a is " + a); // definition of function
       }
    }

Upvotes: 2

Jainendra
Jainendra

Reputation: 25143

From the Sun glossary's definitions:

declaration: A statement that establishes an identifier and associates attributes with it, without necessarily reserving its storage (for data) or providing the implementation (for methods).

definition: A declaration that reserves storage (for data) or provides implementation (for methods).

The way I read the Sun glossary would be like this:

List i;              // declaration - variable on the stack  
i = new ArrayList(); // definition - gives variable a reference

Upvotes: 8

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

Java language defines only the term declaration not use definition.

Declaration:

class A{}// class declaration

String str;// variable declaration

Upvotes: 2

me_digvijay
me_digvijay

Reputation: 5492

I think I can can better explain this question some thing like this:

Think of the following scenario:

There is a new vacant post of Software engineer in your firm. This means that the person you will chose to fill this position will be a software engineer, (you cannot chose a marketing guy for this post). So creating this post is similar to declaration.

Now when you define what the person with this post can/cannot do, what authorities he has, what are his limitations, then this is called definition.

So saying

SoftwareEngineer se;

means Declaration;

and

class SoftwareEngineer {

// define role and responsibilities
}

means definition. Hope it helps you.

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

1. Declaration means creating a primitive or Object reference variable, but with no assignment of value or object respectively..

eg:

          int x;   // declaration of x of type int

          Cat myCat;  //  declaration of myCat an Object of type Cat

2. Defination is when we assign values or Object to them.

         int x = 5;

         Cat myCat = new Cat();

3. In case of Method, its like this...

public abstract void go();       // Method Declaration (Abstract method)

   public void go(){               // Method Defination

            // Your code      

    }

Upvotes: 4

Related Questions