Java Tutorial – 04 – Variables


Variables are used for storing data during
program execution. Depending on what data we need to store, there are several different
kinds of data types. Java has 8 types that are built into the language. These are called
primitives. The integer types are byte, short, int, and long. Float and double are floating
point types. Char is a Unicode character and boolean is either a true or false value. Except
for these primitive types every other type we’ll encounter is either represented by
a class or an array. To create a variable we start with the data
type we want the variable to hold followed by a variable name. The name can be anything
you want, but it’s a good idea to give your variables names that are closely related to
the values they will hold. The standard naming convention for variables is that the first
word should be lowercase and any subsequent words initially capitalized. To give the variable a value we use the equal
sign, which is the assignment operator, follower by the value. We can also combine the declaration
and assignment into a single statement. If we need multiple variables of the same type,
there’s a shorthand way to do it using the comma operator (,). Once we have declared
a variable we can use it by simply referencing the variable’s name. For example, we can
print it. As we saw earlier there are four signed integer
types we can use depending on how large values we need the variable to hold. In addition
to standard decimal notation, integers can also be assigned using octal or hexadecimal
notation. The floating-point types can store integers
as well as floats. They can also be assigned using the standard exponential notation. Note
that constant floating-point numbers in Java are always kept as doubles, so if we try to
assign it to a float we get an error since double’s have higher precision than floats.
To assign it correctly we can append an “F” character to the constant, which says that
this number is in fact a float. A more common and useful way to do this is using an explicit
cast, by adding the data type we want in parenthesis before the constant. This tells the compiler
to convert it to a float before the assignment happens. The char data type can contain a single Unicode
character which is delimited with single quotes. It can also be assigned using a special notation
that gives you access to all Unicode characters. Finally, there’s Booleans, which can only
be either true or false. The default values of these primitive data
types are as follows: numbers become zero, a char has the Unicode character for 0, and
a boolean is false.

Leave a Reply

Your email address will not be published. Required fields are marked *