Let’s look at some other examples we might have with Java in this quick refresher.
When using a local variable (i.e. one inside of a function, you don’t need to give an access modifier (private, protected, package, or public). However, you do need to provide it with a name (sometimes called an identifier) and a data types.
Java has several commonly used native data types including:
- int
- float
- byte
- String
- Date
- char (character)
So to create a variable you would do something like:
String greeting = "Hello World!";
You can only call a variable if you are within the block it was constructed. So if you have a variable in a function, you cannot call that variable from another function. For a variable to be available in multiple methods, you would need to be a class level variable.
Here is an example of the variable being used.
public static void main(String args[]) {
String greeting = "Hello World";
System.out.println(greeting); // prints what's in the variable
}
Here we use a variable to store information. And then print that variable to the console window. This variable can of course change, based upon other factor and inputs if the right syntax is used.
We can even concatenate strings by using the plus (+) character to join two strings, or a string and another variable together.
Consider the following example.
public static void main(String args[]) {
String greeting = "Greeting from planet earth. We're planet #";
int planet = 3;
System.out.println(greeting + planet); // prints what's in the variable
}
Java Refresher (more syntax examples) was originally found on Access 2 Learn