![]() |
Variables and Data Types |
A typical program uses various values and these values keep changing while the program is running. For example, you create a program that is used to perform calculations, the values entered by one user will obviously be different from the values entered by another user. This also means that, when creating the program, you cannot know all possible values that will be entered in your program. You should still be able to manage the values that the users will eventually enter in your program. If you create a program used to perform calculations as introduced above, when a user enters a new value that would be involved in the calculation, to manage that value, you can (temporarily) store it in the computer memory. Since the values entered in a reserved memory area change regularly, they are called variables. Because neither you nor the compiler can predict all possible values that would be used, there are safeguards you can use. First, you must ask the compiler to reserve an area of memory for a value you intend to use. Asking the compiler to reserve an area of memory is referred to as Declaring a Variable. Remember that when you declare a variable, the compiler reserves an area of the compiler memory for you. Eventually, you can put the desired but appropriate values in that memory space. After declaring a variable, when you need the value stored in its memory area, you can ask the compiler to retrieve it and hand it to you. To effectively handle this transaction, the compiler would need two pieces of information from you: a name of your choice for the memory area that will be reserved, and the type of value that will be stored in that area of memory. Based on this, the formula to declare a variable is: TypeOfValue VariableName As done in some languages like Pascal or Basic, we will start with the name.
When you want the compiler to reserve an area of memory for some values used in your program, you must set a name, also called an identifier, that will allow you to refer to that area of memory. The name can be anything of your choice but there are rules you must follow. The name of a variable:
Beyond these rules as a foundation, you can add yours. For example, we will follow suggested standards of the Java documentation. The rules will follow are:
After declaring a variable, you can store a value in the memory reserved for it. When you have just declared a variable, it may not hold a significant value. To know the value it has, you should put an initial value into that memory space. Putting an initial value is referred to as initializing the variable. To initialize a variable, on the right side of its name, type the assignment operator, followed by the value you want to put in the reserved memory. As we will see in the next few sections, you cannot and should not put just any type of value in a variable. We will see that there are different types used for different variables. After declaring a variable and once it has a value, to display that value, you can provide the name of the variable to the parentheses (in future lessons, we will learn that this is referred to as passing) of the System.out.print() method. |
|
Data Input/Output (IO) With Strings |
|
Introduction to Data Types |
|
As introduced previously, when declaring a variable, besides its name, you must provide the type of information that the variable will hold. The role of this type is to tell the compiler how much memory will be needed to store the value(s) of that variable. Since your program is not the only one used in the computer, memory has to be effectively managed. The type of value that a variable will hold is called a data type. As you ay imagine, different variables can be meant to hold different types of values. Each data type uses a Java keyword to be characterized. As a modern language, Java provides even more support for its traditional data types. To do this, a class was created for each data type. This allows you to get more information from a variable declared with the particular data type you want to use. |
|
Introduction to Strings |
|
A string is one or more characters considered as a single value. Every entered in a program, requested from the user, or displayed as a series of characters is primarily a string. To support strings, Java is equipped with the String class. To declare a variable that would hold a string, use the String data type. To initialize the variable, assign it a double-quoted value. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
String firstName = "Johua";
}
}
|
|
Data Display |
|
To display the value of a string, you can pass the name of variable to the System.out.print() method. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
String firstName = "Johua";
System.out.print("First Name: ");
System.out.print(firstName);
}
}
We mentioned that any character or group of characters is a string. To make it easy to manage strings, you can "concatenate" one string with another to create a new string. The concatenation is done by adding one string to another, which is done using the addition operator. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
String firstName = "Johua ";
String lastName = "Yacomo";
String fullName = firstName + lastName;
System.out.print("Full Name: ");
System.out.print(fullName);
}
}
In the same way, you can concatenate as many strings as you want, using the addition operator the same way you would in algebra. When writing System.out.print("First Name: ");, the First Name value is a string. This allows you to also add strings locally where they are used, such as in the print() method. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
String firstName = "Johua";
String strSeparator = ", ";
String lastName = "Yacomo";
System.out.print("Full Name: " + lastName + strSeparator + firstName);
}
}
|
|
Natural Numbers |
|
Introduction |
|
A number is referred to as natural when it mainly contains digits. Examples are 2, 485, or 182976389. When a natural number doesn't include a sign like these ones, it is referred to as unsigned. That number is also consider positive, that is, above 0. A natural number can have a value under 0. Such a value is referred as a negative. To identify a number as negative, you must type the minus symbol "-" to its left. An example is -246. In everyday writing, when a number is too long to read, such as 182976389, you can use a special symbol to separate the thousands. In US English, this number is the comma. An example would be 182,976,389. This makes it easy to read. This writing is allowed in various scenarios but you must never use it in your Java programs. |
|
Bytes |
|
A byte is series of 8 bits. It is used to represent (very) small numbers. To declare a variable that would hold a natural number between -128 and 127, you can use the byte data type. To initialize such a variable, make sure you assign it a number in the appropriate range. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
byte temperature = -28;
System.out.print("Temperature: ");
System.out.print(temperature);
}
}
The value assigned to a byte variable must in the correct range, otherwise you would receive an error. For example, if you assign a value lower than -128 or higher than 127 to a byte variable, the program would not work. The Java class associated with the byte data type is called Byte. |
|
Regular Integers |
|
The word integer is also used for a natural number. An integer is simply a natural number. Many, if not most, languages provide different data types for various categories of integers. In Java, an integer is variable whose values are between -2,147,483,648 and 2,147,484,647. The value is also said to fit in a 32-bit range. To declare a variable that would hold numbers of that range, use the int keyword. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
int days = 468;
System.out.print("Days Passed: ");
System.out.print(days);
}
}
The Java class associated with the int data type is called Integer. |
|
Short Integers |
|
An integer is referred to as short if its value is between -32768 and 32767. This number can fit in 16 bits. To declare a variable that would hold numbers in that range, you can use the short data type. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
short numberOfStudents = 3428;
System.out.print("Number of Students: ");
System.out.print(numberOfStudents);
}
}
Just as mentioned for the byte, the value you assigned to a short variable must fit in the allowed range, otherwise you would receive an error when you compile the program. As you may realize, any number that can fit in a short can also fit in an integer. In order words, you can safely use the int keyword to declare a variable that would hold numbers intended for a short. There is no danger. Even if you think of computer memory (because a short uses less space than an int), memory is not expensive anymore. The Java class associated with the short data type is called Short. |
|
Long Integers |
|
A number that is higher than a regular integer can hold is called a long integer. To support this type of number, the Java language provides the long data type. A long integer is a variable that can hold very large number that may require 64 bits to be stored accurately. To declare a variable for such a number, use the long keyword. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
long distance = 64564;
System.out.print("Distance: ");
System.out.print(distance);
}
}
As you may realize, a number that fits in a short or an int can also fit in a long. This means that you can declare a variable as long but store very small numbers in its memory. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
long days = 24;
System.out.print("Days: ");
System.out.print(days);
}
}
This program works perfectly fine but may result in a significant waste of memory. When you declare a long variable, by default, the compiler "allocates" only enough memory for an integer so there would not be a waste. In some cases, you may want the compiler to use 64 bits for your long variable. Consider the following program: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
long days = 245885475475;
System.out.print("Days: ");
System.out.print(days);
}
}
This would produce: init:
deps-jar:
Compiling 1 source file to C:\Programs\JavaLessons\Exercise1\build\classes
C:\Programs\JavaLessons\Exercise1\src\exercise1\Main.java:24: integer number too large: 245885475475
long days = 245885475475;
1 error
BUILD FAILED (total time: 0 seconds)
The program would not work because the compiler would have reserved space for an integer but the assigned value needs more room. If you insist on using enough memory for a long integer, when initializing it, on the right side of the value, type L. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
long days = 245885475475L;
System.out.print("Days: ");
System.out.print(days);
}
}
This time, the program works fine because the compiler was explicitly asked to reserve enough memory. The Java class associated with the long data type is called Long. |
|
Real Numbers |
|
Introduction |
|
In every day language, a number is referred to as decimal when it displays a natural section and a precision. Both sections are separated by a special character called the decimal symbol, which depends on the language and can be verified in the Regional Options dialog box from the Control Panel:
The values on both sides of the decimal symbol are represented by digits. The value on the left side is expressed like a natural number: it can use a positive (+) or a negative (-) sign to show whether it is higher or lower than 0. It can also be written with commas to make it easier to read. The value on the right side of the decimal separator can be made of only digits. This value specify the level of precision allowed on the number. Normally, the more numbers, the more precise. The Java language supports two types of real numbers: single precision and double-precision |
|
Double-Precision Values |
|
One of the main concerns with decimal values used in mathematics is their level of accuracy: the number needs to be as precise as possible. To declare a variable used to hold such a decimal number, you can use the double keyword. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
double PI = 3.14159;
System.out.print("PI: ");
System.out.print(PI);
}
}
To ensure its accuracy, a double variable usually uses 64 bits to store its value. The Java class associated with the double data type is called Double. |
|
Single-Precision Values |
|
A real number qualifies as single-precision when it needs only a limited number of bits, typically half of what is needed for a double, to show its value. The value typically fits in 32 bits and the precision is not a significant factor. To declare a variable that would hold decimal values with little to no concern with precision, you can use the float data type. Because accuracy and precision are an important factor in mathematics, by default, when you declare a variable as float, you must explicitly let the compiler know that you are not concerned with precision and that the value would be dealt with single-precision. To specify this, when initializing the variable, type F to the left of the value. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
float PI = 3.14F;
System.out.print("PI: ");
System.out.print(PI);
}
}
In the same way, when declaring a double-precision variable, to reinforce the idea of its values requiring double-precision, type d or D to the right of its value. This would be done as follows: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
double PI = 3.14159D;
System.out.print("PI: ");
System.out.print(PI);
}
}
Although a double variable uses memory more than the average variable, because memory is not expensive anymore, most programmers usually use the double data type instead of the float when declaring their variables. Use float only if you must. The Java class associated with the float data type is called Float. |
|
Characters |
|
A Byte for a Character |
|
When introducing natural numbers, we saw that you could use the byte data type to declare a variable that would hold small numbers. Actually the value used for a byte represents code for a character. The character is internally recognized by its ASCII number. For this reason, you can use the byte data type to declare a variable that would be used to hold a single character. To initialize such a variable, assign a single-quoted character to it. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
byte driversLicenseClass = 'M';
}
}
|
|
The Character as a Type |
|
If you use the byte data type to represent a character, the compiler would use only 8 bits (actually 7) for the character. When this was conceived, it didn't take into consideration international characters of languages other than English. To support characters that are not traditionally used in (US) English, another character format was created: Unicode. This includes Latin-based and non-Latin-based languages. To support Unicode characters, Java provides the char data type. Based on this, to declare a variable that would be used to store characters, use the char keyword. To initialize the variable, assign it a single-quoted character. Here is an example: package exercise1;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
char driversLicenseClass = 'C';
System.out.print("Driver's License Class: ");
System.out.print(driversLicenseClass);
}
}
|
|
Final Variables |
|
Introduction |
|
A variable is referred to as final when its value doesn't change throughout the program. This is the C/C++/C# equivalent to a constant. To create a final value, type final, followed by the type of the variable, its name, the assignment operator "=", and the desired value. |
|
|
||
| Previous | Copyright © 2005 FunctionX, Inc. | Next |
|
|
||