SwadhyAI Notes

All Java notes

Java variables

›Short versionOpen if you only have a minute.
  • A variable is a name, a type, and the value currently stored. The type is fixed at the declaration.
  • int age = 25; introduces the name and stores 25. age = 30; replaces the value and does not declare the name again.
  • A local variable has no default. Reading it before an assignment is a compile error, not a quiet zero.
  • An assignment of the wrong type is rejected. An int cannot hold a String.
  • final allows one assignment. A second assignment to that name does not compile.

A lets a method keep a value and use it again by name. The line that creates it is a . The on that line is the decision you do not get to revise.

java
String name = "Alice";
int age = 25;
double price = 19.99;
boolean isStudent = true;
char grade = 'A';

Text uses double quotes. A char uses single quotes and holds one character. A float literal needs an f, as in float temperature = 98.6f;, because a plain decimal is a double. The sizes and the overflow of these types are on Java data types.

Declare once, assign as often as the type allows

You can split the first store from the declaration. After that, every change is an . The type is not written again.

java
int score;
score = 100;
System.out.println(score);

score = 200;
System.out.println(score);

score = score + 50;
System.out.println(score);

The prints are 100, then 200, then 250. score = score + 50 reads 200, adds 50, and stores 250. Several names of the same type can be declared in one statement, int x = 5, y = 10;, and each name is still its own variable.

score = "high"; does not compile. The name was declared as an int, and a string is not an int. Changing your mind means declaring a different name with the type you actually need.

One assignment, then the name stays

is how you say the binding should not move. Constants are conventionally written in capitals with underscores, so a reader can see that the name is not supposed to be reassigned.

java
final double PI = 3.14159;
final int MAX_USERS = 100;

PI = 3.14;

The last line is a compile error. PI already holds a value. A blank final, written final int limit; and assigned once on a later line, is allowed. A second assignment is not.

Names start with a letter, _, or $. They may contain digits after that. They cannot contain a space or a hyphen, and they cannot be a keyword such as class. age and Age are different names. The ordinary shape is camel case, firstName, with the first letter lower so it does not look like a class.

This method declares int age; and then prints age. What happens when you compile it?

It does not compile. age is a local variable, so it has no default value. The compiler reports that the variable might not have been initialized. Store a value first, or declare it with an initializer: int age = 25;.