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:
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.
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. Retrieving a value in Java is not particularly busy. As seen in our introduction, to do anything, you have to go through a class. To retrieve a value, you have to go through different classes. When you type a value in a program, to retrieve it, you can the in object of the System package: System.in After getting that value, you must first store it somewhere. One of the classes you can use is called Scanner. Before using the Scanner class, you must import the java.util.Scanner package into your program. This would be done by writing the following in the top section of the file: import java.util.Scanner; To use the Scanner class to retrieve a value, use the following formula: Scanner VariableName = new Scanner(System.in); The only think we need to mention at this time is that, after the Scanner class, you must give a variable name. An example would be: Scanner scnr = new Scanner(System.in); The other details, such as why System.in is written in the parentheses after new Scanner, will be explained in future lessons. After declaring a Scanner class, its variable is ready to receive the value. The value depends on a type. We will see in the next lessons. When getting a value, the Scanner class must be able to convert it to its appropriate type. To support this, the Scanner class is equipped with a mechanism (actually called a method) for each type of value. To retrieve a value, you will write the name of the Scanner variable, followed by a period, followed by the mechanism as we will indicate, then assign it to the variable whose value you want to retrieve. The formula will be: VariableName = ScannerVariable.Mechanism(); Notice the parentheses and the semi-colon.
To display a value, you can write it in the parentheses of System.out.print(). If the value is a character, include it between single-quotes. Here is an example: public class Exercise { public static void main(String[] args) { System.out.print('Q'); } } This would produce: Q If the value is a word or a sentence, include it between double-quotes. Here is an example: public class Exercise { public static void main(String[] args) { System.out.print("James Harding"); } } This would produce: James Harding If the value is a (constant) number, simply type that number in the parentheses of System.out.print() or System.out.println(). Here is an example: public class Exercise { public static void main(String[] args) { System.out.print(248); } } This would produce: 248 If the value is stored in a variable, you can write the name of that variable in the parentheses of System.out.print(). We will see various examples in the next sections. Instead of a constant value in the parentheses of System.out.print() or System.out.println(), you may want to add other items, such as a sentence that is made of words and values that would come from variables. Fortunately, you have many options. If you want to exercise some control as to how a value is formatted, instead of using System.out.print() or System.out.println(), use System.out.printf(). This allows you to format how data should appear when displayed to the user. Data types are divided in categories: characters, integers, floating-point numbers, and strings. To display a particular type, you type the percent operator “%”, followed by the category of data. The basic formula to follow is: System.out.printf("blah blah blah %Character blah blah", variable); Any blah represents anything word or sentence you want to include in the display. At some point, you will write % followed by a character. We will see the examples in the appropriate section. The first section ends with a closing double-quote followed by a comma. After the comma, you must include the name of the variable whose value will be displayed in the Character placeholder. Instead of one value, you can create as many placeholders as you want. The formula to follow is: System.out.printf("blah %Char1 blah %Char1 blah %Char1 blah", var1, var2, var3); Once again, you will replace each blah with whatever you want to add as part of your sentence. Each Char is a placeholder for a character as we will see in various examples. After the comma, you must include a variable name (or a value) for each Char placeholder, in the order they appear in the double-quotes, no more, no less.
A string is one or more characters considered as a single value. Everything 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 retrieve a string, you can apply next() to your Scanner class. Here is an example: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String firstName; System.out.print("Enter the First Name: "); firstName = scnr.next(); System.out.print("First Name: "); System.out.print(firstName); } } Here is an example of running the program: Enter the First Name: James First Name: James next() is used to get only one word that is considered terminated by an empty space. To retrieve a string made of different words, you must assume that it would be terminated by a new line. To get such a string, use nextLine(). To initialize a String variable, assign it a double-quoted value. Here is an example: public class Exercise { public static void main(String[] args) { String firstName = "Johua"; } } To display the value of a string, you can pass the name of variable to the System.out.print() method. Here is an example: public class Exercise { public static void main(String[] args) { String firstName = "Johua"; System.out.print("First Name: "); System.out.print(firstName); } } As an alternative, to display a string using System.out.printf(), add a %s expression in the double-quotes ass the placeholder of the variable. Here is an example: public class Exercise { public static void main(String[] args) { String fullName = "Patricia Katts"; System.out.printf("Full Name: %s", fullName); } } This would produce: Full Name: Patricia Katts An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n. An escape can be included in single-quotes as in '\n', in double-quotes as "\n", or as part of a string. The Java language recognizes other escape sequences:
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: public class Exercise { public static void main(String[] args) { 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: public class Exercise { public static void main(String[] args) { String firstName = "Johua"; String strSeparator = ", "; String lastName = "Yacomo"; System.out.print("Full Name: " + lastName + strSeparator + firstName); } } |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
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. A byte is series of 8 bits. It is used to represent small numbers. To declare a variable that would hold a natural number between -128 and 127, you can use the byte data type. To retrieve the value of a byte variable, apply nextByte() to the Scanner variable. Here is an example: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); byte temperature; System.out.print("Enter the temperature: "); temperature = scnr.nextByte(); System.out.print("Temperature: "); System.out.println(temperature); } } Here is an example of running the program: Enter the temperature: 32 Temperature: 32 To initialize a byte variable, make sure you assign it a number in the appropriate range. Here is an example: public class Exercise { public static void main(String[] args) { byte temperature = -28; System.out.print("Temperature: "); System.out.println(temperature); } } This would produce: Temperature: -28 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. In the parentheses of System.out.print() or System.out.println(), you can concatenate a string a byte variable. To do this, us the + operator between them. Here is an example: public class Exercise { public static void main(String[] args) { byte temperature = -28; System.out.println("Temperature: " + temperature); } } To display the v alue of a byte variable using System.out.printf(), use the %d expression. Here is an example: public class Exercise { public static void main(String[] args) { byte temperature = -28; System.out.printf("Temperature: %d", temperature); } } 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. To retrieve the value a variable of type int, apply nextInt() to the Scanner variable. Here is an example: import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int days; System.out.print("Enter number of days: "); days = scnr.nextInt(); System.out.print("Days Passed: "); System.out.println(days); } } Here is an example of running the program: Enter number of days: 42 Days Passed: 42 After declaring an int variable, to initialize it, assign a number to it. Here is an example: public class Exercise { public static void main(String[] args) { int days = 468; System.out.print("Days Passed: "); System.out.println(days); } } In the parentheses of System.out.print() or System.out.println(), you can concatenate a string an a natural number. To do this, use the + operator. Here is an example: public class Exercise { public static void main(String[] args) { int days = 468; System.out.print("Days Passed: " + days); } } Instead of a normal decimal number, you can initialize an int variable with a hexadecimal number. The number must be preceded with 0x. Here is an example: public class Exercise { public static void main(String[] args) { int number = 0xA2EE; System.out.print("Number: " + number); } } This would produce: Number: 41710 To display the value of an int variable using System.out.printf(), use the %d format to represent a character variable. Here is an example: public class Exercise { public static void main(String[] args) { int number = 41710; System.out.printf("Number: %d", number); } } To display the number in hexadecimal format, use the %x or %X expression. Here is an example: public class Exercise { public static void main(String[] args) { int number = 41710; System.out.printf("Number: %x", number); } } This would produce: Number: a2ee As you can see, if you use %x, the characters in the result would appear in lowercase. If you want the characters to appear in uppercase, use %X. 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. To retrieve a short integer, apply nextShort() to the Scanner variable. Here is an example: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); short numberOfStudents; System.out.print("Enter number of students: "); numberofStudents = scnr.nextShort(); System.out.print("Number of Students: "); System.out.println(numberOfStudents); } } After declaring a short variable, to initialize it, assign the desired number to it. Here is an example: public class Exercise { public static void main(String[] args) { short numberOfStudents = 3428; System.out.print("Number of Students: "); System.out.println(numberOfStudents); } } 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. You can concatenate a string a short variable in the parentheses of System.out.print() or System.out.println(). To do this, use the + operator. Here is an example: public class Exercise { public static void main(String[] args) { short numberOfStudents = 3428; System.out.print("Number of Students: " + 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. Instead of a normal decimal integer, you can initialize a short variable with a hexadecimal number. Here is an example: public class Exercise { public static void main(String[] args) { short number = 0x4A8; System.out.print("Number: " + number); } } To display the v alue of a short variable using System.out.printf(), use the %d expression. Here is an example: public class Exercise { public static void main(String[] args) { short number = 30208; System.out.printf("Number: %d", + number); } } If you want the result to appear as a hexadecimal number, use %x or %X. 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 a very large number that may require 64 bits to be stored accurately. To declare a variable for such a number, use the long keyword. To retrieve a long value, apply nextLong to the Scanner variable. After declaring a long variable, to initialize it, assign the desired value to it. Here is an example: public class Exercise { public static void main(String[] args) { long distance = 64564; System.out.print("Distance: "); System.out.print(distance); } } This would produce: Distance: 64564 In the parentheses of System.out.print() or System.out.println(), you can concatenate a string with a long variable. This is done using the + operator. Here is an example: public class Exercise { public static void main(String[] args) { long distance = 64564; System.out.print("Distance: " + distance); } } You can also initialize a long variable with a hexadecimal number. Here is an example: public class Exercise { public static void main(String[] args) { long number = 0xACE882; System.out.print("Number: " + number); } } To display the v alue of a long variable using System.out.printf(), use the %d expression. Here is an example: public class Exercise { public static void main(String[] args) { long number = 30208; System.out.printf("Number: %d", + number); } } If you want the result to appear as a hexadecimal number, use %x or %X. 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: public class Exercise { public static void main(String[] args) { long days = 24; System.out.print("Days: " + 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: public class Exercise { public static void main(String[] args) { long days = 245885475475; System.out.print("Days: " + 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: public class Exercise { public static void main(String[] args) { 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.
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. 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. To retrieve a double-precision value, you apply nextDouble to your Scanner variable. To initialize a double variable, assign a decimal number to it. Here is an example: public class Exercise { public static void main(String[] args) { 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. In the parentheses of System.out.print() or System.out.println(), you can concatenate a string with a double variable. This is done using the + operator. Here is an example: public class Exercise { public static void main(String[] args) { double number = 2685.404; System.out.print("Number: " + number ); } } This would produce: Number: 2685.404 You can also initialize a long variable with a hexadecimal number. Here is an example: public class Exercise { public static void main(String[] args) { double number = 0xDDF402; System.out.print("Number: " + number ); } } This would produce: Number: 1.4545922E7 To display the v alue of a double variable using System.out.printf(), you have various options. You can use %g or %G. The compiler would use what is referred to as the general fixed number formal, which in US English uses two digits after the decimal separator. Here is an example: public class Exercise { public static void main(String[] args) { double number = 2685.404; System.out.printf("Number: %g", number ); } } This would produce: Number: 2685.40 As an alternative, you can use the %f expression. If this case, the compiler would use a fixed standard format. Here is an example: public class Exercise { public static void main(String[] args) { double number = 2685.404; System.out.printf("Number: %f", number ); } } This would produce: Number: 2685.404000 As you can see, the compiler would decide how many digits to display after the decimal separator, which is the period in US English. If you want to specify how many digits to display after the decimal separator, use an expression that follows this format: %.Numberf Notice the period after the % symbol. Between the period and f, you use the Number placeholder to enter the desired number of digits. Here is an example: public class Exercise { public static void main(String[] args) { double number = 2685.404; System.out.printf("Number: %.8f", number ); } } In this example, we used 8. This indicates to the compiler that we want to see 8 placeholders for digits after the decimal separator. In this case, there would be 8 placeholders. If the number includes 8 or more digits after the decimal separators, they would be displayed. If there are less than 8, there would be 0s in the remaining placeholder. The above code would produce: Number: 2685.40400000 If you want to display the number in scientific (exponential) format, use %e or %E. Here is an example: public class Exercise { public static void main(String[] args) { double number = 2685.404; System.out.printf("Number: %e", number ); } } This would produce: Number: 2.685404e+03 As you can see, the number appears with e. If you want the E (uppercase), use %E. 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. To retrieve a float value, apply nextFloat to your Scanner variable. 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: public class Exercise { public static void main(String[] args) { 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 side of its value. This would be done as follows: public class Exercise { public static void main(String[] args) { double PI = 3.14159D; System.out.print("PI: "); System.out.print(PI); } } Although a double variable uses more memory than the average variable, because memory is not expensive anymore, you should usually use the double data type more than the float when declaring a variable for a decimal value. Use float only if you must. The float follows the same rules as the double regarding concatenation, hexadecimal, or formatting with System.out.printf().
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 variable 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: public class Exercise { public static void main(String[] args) { byte driversLicenseClass = 'M'; } } 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: public class Exercise { public static void main(String[] args) { char driversLicenseClass = 'C'; System.out.print("Driver's License Class: "); System.out.print(driversLicenseClass); } } To display a character using System.out.printf(), use the %c format.
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 constant value in Java, type final, followed by the type of the variable, its name, the assignment operator "=", and the desired value. |
|
|||||||||||||||||||||||||||||||||
|