R
PRO
last week
Rockycountry asked

In the given code, why do I have to declare the type for distance2? Is it because it's a new variable name? class Main { public static void main(String[] args) { // Create and print the distance variable int distance = 134; System.out.println(distance); // Create another variable distance2 int distance2 = 564; // Assign value of distance2 to distance distance = distance2; // Print distance System.out.println(distance); } }

Udayan Shakya
Expert
3 days ago
Udayan Shakya answered

Hello Rocky! I see you're taking your Java lessons earnestly, and it's really encouraging to see learners like you!

And your hunch about type declaration is right on the mark:

Every time you declare a new variable, you need to specify its type. You don't need to specify type for the variable after you've declared it.

Let's clarify this with a modified version of the program you've given:

class Main {
    public static void main(String[] args) {
     
        // Create and print the distance variable
        int distance = 134;
        System.out.println("Original distance = " + distance);
     
        // Create another variable distance2
        int distance2 = 564;
        System.out.println("Original distance2 = " + distance2);
     
        // Assign another value to distance
        // No need to declare type again
        distance = 760;
        System.out.println("\nModified distance = " + distance);
     
        // Assign another value to distance2
        // No need to declare type again
        distance2 = 666;
        System.out.println("Modified distance2 = " + distance2);
     }
}

Output

Original distance = 134
Original distance2 = 564

Modified distance = 760
Modified distance2 = 666

Notice the following blocks of code above:

distance = 760;
System.out.println("\nModified distance = " + distance);
     
distance2 = 666;
System.out.println("Modified distance2 = " + distance2);

You can clearly see that you don't need to redeclare the types of distance and distance2 because they've already been declared when you created the variables:

// Declaration of 'distance' variable
int distance = 134;


// Declaration of 'distance2' variable
int distance2 = 564;

This is true not just for Java, but for other programming languages like C, C++, TypeScript, etc. as well.

Hope that clears things up! Contact us again if you have further questions!

Java
This question was asked as part of the Learn Java Basics course.