Scope and Constants
Constants
In Java, constants are special variables whose values cannot be changed once they are initialized. This is useful when you have a value that you know will never change, such as the value of pi or the maximum speed of your robot. Constants are typically declared using the final
keyword followed by the data type, name, and initial value. For example, you could declare a constant for the maximum speed of your robot like this:
final double MAX_SPEED = 5.0;
Once you have declared this constant, you cannot change its value. If you try to do so, the Java compiler will give you an error. This helps to prevent bugs where you accidentally change a value that should remain constant.
Scope of Variables
The scope of a variable in Java refers to the region of code where the variable can be accessed. The scope is determined by where a variable is declared. For example, if a variable is declared inside a method, it is a local variable and can only be used within that method:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
On the other hand, if a variable is declared as a class attribute, it is a class (or instance) variable and can be used by all methods in the class:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}
Tasks
For this week's tasks, we'll be practicing working with variables and data types.
-
At the top of your program, declare a constant named
PI
that has adouble
type and assign it the value of3.14
. -
Declare a variable of type
double
namedradius
and assign it a value of5.0
. -
Calculate the area of a circle using the formula
PI * radius * radius
and assign the result to adouble
variable namedarea
. Print the value ofarea
. -
Now, change the value of
radius
to10.0
and calculate thearea
again, storing the result in thearea
variable. Print the value ofarea
again. This should demonstrate how variables can be reassigned. -
Declare two
String
variables,teamMemberName
andteamName
. Assign any names you like to these variables. -
Declare a
String
variable greeting and assign a personalized greeting message that includes bothteamMemberName
andteamName
usingString
concatenation. For example, the message could be "Hello, " +teamMemberName
+ "! Welcome to team " +teamName
+ "." Print thegreeting
. -
Reassign different values to
teamMemberName
andteamName
, then create a newgreeting
message by again assigning to thegreeting
variable. Print the newgreeting
. This will show that you can update the contents of a string variable and print out new information.