Java Data Type
Before every program, don't forget to import the scanner class,
by typing " import java.util.Scanner; " at the top left corner to use java data type.
In addition to that, inside the main function, we need to declare a Scanner
variable and create and instance of the Scanner class.
Java Declaring Variable
In java, we must explicitly declare all variables
before using them. The basic form of a variable declaration is this:
type name;
Example)
int x;
String name;
double area;
In the examples above variable named x, name, and
area are declared. The x variable can hold integer values,
the name variable holds String values, and the area holds double values. (Note
variable declaration also ends with a semicolon).
We can declare two or more variables of the same type in a single statement, by
separating the variable name.
Example)
int x, y, z;
double a, b, c;
Java Declaring Class Variables
A class variable is a variable that any method in a class can access. Here are two basic rules for declaring a class variable.
1)
The declaration must be within the body of the class and not within any of the
class methods.
2) It must include
the word static in the declaration. The word static comes before the variable.
Example)
As we can see from the example above, the key
word static is placed before String and
the declaration is outside of main.
Java Declaring Local Variables
A local
variable is a variable that's declared
within the body of a method. Then we can
only use the variable within the method. Other methods in the class wouldn't be
able to use it.
Example)
Note that we declare String hello inside our main method and we don't use the static key word or else we would get an error.
Java Initializing Variables
In java, we are allow to initialize a variable on the same statement that
declares the variable.
In addition, we can declare more than one variable in a single statement. To do
that, we need
to use an initializer, which has the following general form:
type name = expression;
Example)
int x = 0;
String name = "Jay";
double area = 0.0;
Example)
int x = 4, y = 5;
When we declare two class variables in a single statement but
use only one initializer,
we would think that the initializer applies to both variables.
Example)
static int x, y = 5;
Here, both x and y are not initialize to 5.
Java final Variables
A final variable, which also called constant, is a variable whose value that we can't change once it's declared.
Example)
static final int x = 5;
Example)
final int x = 5;
Java Strings
A string is a sequence
of text characters, such as the message " Hello World".
We are able to combine strings using a plus sign ( + ) as a concatenation
operator.
(
Concatenation is just a nerdy term in java, meaning combining two strings
)
Enough with the definitions and small examples, let see some real programming examples.
ClickHere to download SumNumber.java
ClickHere to download Name.java
ClickHere to download Salary.java