Monday, 25 July 2011

Java: Variables (Initializing and Named Constants)

Still technically Monday!

This one will be short, so let's get to it. Last post, I talked about initializing the variables already, but just to clarify, the first time you declare a variable to exist in a program, you need to first name its type, then the variables name. At this point you can either end the statement for now and give it a value later, or immediately give that variable a value.

int x;
String s = "This is a string!";
double g;
g = 9.8;


Note that String is capitalized, while int and double are not. This is because String is not a primitive variable type, it's closer to a char list, with each character in the String being a new char in a new position.


Constant Variables, such as pi, can be declared once as final variables. This stops the variable from being able to change at a later point in the program, and it removes the need to type out "3.1415..." constantly.

final double pi = 3.141592; In the case of pi, cut it off when you get to a desirable accuracy

Now, at any point in the program you can call pi, it will count as the double you finalized it as. If you now try to change the value, the compiler will throw an error at you.

No comments:

Post a Comment