
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 = 666Notice 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!
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
