skyridertk
skyridertk

Reputation: 101

Why is naming a String variable, String, a valid Java construct?

Given this case:

    String String = ""; //valid

Why is this valid?

Also, why is it that:

    int int = 0;  // is invalid

I'm baffled.

Upvotes: 0

Views: 47

Answers (2)

hovanessyan
hovanessyan

Reputation: 31433

Reserved words can't be used in variable names.

List of reserved words:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Same goes for class names.

Upvotes: 2

Makoto
Makoto

Reputation: 106390

int is a reserved keyword. Reserved keywords may not be used as part of any formal variable name - the same is true of true, false, and null as literals. There's a list of those such keywords available.

String is a class name and cannot be a reserved keyword. This is because you cannot predict what the name of a class will be in general.

By convention, reserved keywords are lower case, variable names are camelCased, and classes are TitleCased. Following these conventions will ensure that your code doesn't run into these simple errors.

Upvotes: 3

Related Questions