Java supports eight different primitive data types.
Java provides four ways to deal with numbers for different applications.
Real Numbers with decimals: The `float` and the `double` data types.
Real whole numbers: The int data type
Any ASCII value that can be represented in the machine is called a character (i.e., a char) . The char data type holds a single character and it must be enclosed inside the single quotes ' ' and represents a numeric value. For example:
> char c = 'a'
> c
'a'
> (int)c
97
The value 97 is obtained by typecasting to an integer the character c. Type casting means to force Java to transform a data type into another data type by specifying the data type inside the parenthesis, as shown (int). You can find the decimal value for the character 'a' and all the characters on your keyboard in the following table.
Java supports an additional data type called `String`. The String is a collection of characters that represent words or phrases.
Table 1. Java's eight primitive data types
A variable is a placeholder for a value that can eventually change. You probably remember using variables in your math classes, such as x and y, and solving for each of them. A variable in programming refers to a piece of memory in the computer, where we store a value that we can use in the future.
Variables are used to store information in your programs that you will probably use later. To start, you need to specify the data type of a variable and provide a value that corresponds to that particular data type. For example, suppose that you would like to store the value 5 into a variable called x. the way to do it in Java is:
int x = 5;
it reads as follows: "store in memory a whole number (int) called x, that will “get” the value 5, end the command (;)”
Let us interact with Java to demonstrate the different variable manipulations by declaring two integer variables, x and y, with the values of 5 and 3 respectively.
> int x = 5
> int y = 3
We can take advantage that Java stores the values of `x` and `y` into memory, so we can use variables to perform operations such as:
> x + y
8
> x * y
15
> x % y
2
Furthermore, we can store the results of operations into new variables
> int z = x + y
> z
8
The variables are stored in memory based on their data types. Each data type has a capacity and properties that are used in different forms through programming. In the next section, we discuss this in more detail.
Because variables are placeholders, we must consider that the computer memory will keep track of the value and that we can change those values eventually. For example, considering the last interaction, the value of `z` is 8 because of the result of adding the variable `x` and `y`, whose values are `5` and `3` respectively. After that, we can still use the value of `z` including to the same `z`, like this
> int z = x + y
> z
8
> z = z - 2
> z
6
The statement `z = z - 2` it reads as follows: the variable z will be changed by using the old value of z (that is 8) and then subtract 2 (which will be 8 - 2 = 6) when the value of `z` is called, it will return the value of `6`.
A String is an Object that contains "functionalities" that allow you to do certain operations. These functionalities are called methods.
Methods are functionalities that belong to objects, such as String, which we will discuss more in detail on Ch. 4. Some of the popular methods can be seen in Table 3. Let us demonstrate these functionalities by testing them into the interactions window:
The length() method retrieves the total number of characters in the String. Let us define a String called s1, that will hold the String "hello", after calling the method, we obtain 5, since the String s1 has 5 characters, i.e., 'h', 'e', 'l', 'l', and 'o'.
> String s1 = "hello"
> s1
"hello"
> s1.length()
5
Java is a zero-based numbering language, meaning that we start counting from 0 and not from 1. Let us access each character from the String `hello` starting from index 0
> s1.charAt(0)
'h'
> s1.charAt(1)
'e'
> s1.charAt(2)
'l'
> s1.charAt(3)
'l'
> s1.charAt(4)
'o'
Although the String `hello` has a length of 5, a typical error into access the index representing the length of the String, in this case, is 5. This mistake will lead us to an exception (discussed on detail on Ch. Ch. 8) as follows:
> s1.charAt(5)
java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source)
Let us now redefine the variable s1, by providing a different value for the String.
> s1 = "hElLo gUyS hOw aRe yOu"
"hElLo gUyS hOw aRe yOu"
Notice that the variable s1 has a combination of the upper and lower case. The String counts with methods that change the case for the string. For example:
> s1.toUpperCase()
"HELLO GUYS HOW ARE YOU"
changes the String into upper case, where the toLowerCase() changes to a lower case.
> s1.toLowerCase()
"hello guys how are you"
It is important to recognize that if we call the variable s1, it will continue with the original state since we never update the variable.
> s1.toLowerCase()
> s1
"hElLo gUyS hOw aRe yOu"
Remember that the s1 is a variable, and the purpose of a variable is that its value eventually change. If that is the objective, then we need to assign (=) the new value of s1 to s1 as follows:
> s1 = s1.toLowerCase()
> s1
"hello guys how are you"
In addition to the functions (methods) listed above for the String, there is one additional called the substring that is quite useful for your programming projects.
The substring is a method from the object String that provides a partial subpart of the string depending on the two methods you use.
There are two methods for substring:
substring(pos): the substring from position 0 to position ‘pos’. E.g.,
If String s = “hello”, s.substring(3) will give you back the String: “lo”
substring(pos1, pos2): the substring from `pos1` to `pos2`. E.g.,
If String s = “hello”, s.substring(1,3) will give you back the String: “el”
In our previous example, we can demonstrate the two substring methods as follows:
> s1.substring(11)
"Lo gUyS hOw aRe yOu"
> s1.substring(6,11)
"gUyS h"
This is called concatenation. Concatenation is the process of gluing Strings with any other data type, including objects, such as Strings. The process to concatenate must be done through the '+' operand.
> String x = "hello" // defining a String x
> String y = "world" // defining a String y
Let us create another variable, z that will concatenate the value of x and y by using the `+` operator.
> String z = x + y
> z
"helloworld"
But also, you can incorporate more Strings or variables in between,
> z = x+" "+y
"hello world"
Writing programs with defined variables is essential to demonstrate and test small and simple programs. However, in most cases, we need to perform operations based on the user's input. Therefore, we need to understand how to interact with the computer user through a program. In this section, we will discuss three popular ways to interact with the computer user: Command line arguments (args), where the terminal/command line is used; Scanner, a mechanism that scans a prompt from the computer user; and through JOptionPane, a dialog that permits the user to interact with the computer user through a Graphical User Interface (GUI).
Java programs can run directly from the command line or the terminal, depending on the computer user's operating system.
The part responsible for *holding* the arguments passed through the command-line is an array called args (we will discuss this in Chapter 4) String [] args. The variable `args` will contain 0 or more Strings based on the number of arguments that are passed through the command line/terminal. There are several ways you can access information from the arguments.
args.length: will provide the total number of arguments passed
args[0]: will provide the first argument passed
args[1]: will provide the second argument passed and so on.
Example: A basic program that processes two arguments from the command line and prints them
Suppose that we have a program called ArgsProcessor01.java and it looks like this:
1. public class ArgsProcessor01{
2. public static void main(String [] args){
3. System.out.println(args[0]);
4. System.out.println(args[1]);
5. }
6. }
when the program is called from the command line, it looks like this:
java ArgsProcessor01 hello world
hello
world
where:
java is the command to run the program
ArgsProcessor01 is the name of the program we want to execute
hello is the first argument for the program ArgsProcessor01
world is the second argument for the program ArgsProcessor01
once we run the program, Line 3 and Line 4 will execute, and it will print the args[0], which corresponds to "hello", and args[1], which corresponds to "world". Therefore, the program will print hello and world.
The String [] args explicitly mentions Strings. In our previous example, the hello and the world arguments both were Strings. But, how can we process values that are not Strings? For example, integers or real numbers?
For that, we need to use "helpers" called wrappers. There is one wrapper for each primitive data type. Table 4 provides some examples of these.
Example: transforming Strings into numbers using wrappers
Suppose that we have a program called ArgsProcessor02.java and it looks like this:
1. public class ArgsProcessor02{
2. public static void main(String [] args){
3. int x = Integer.parseInt(args[0]);
4. int y = Integer.parseInt(args[1]);
5. int z = x + y;
6. System.out.println("The sum of "+x+" + "+y+" is "+z);
7. }
8. }
This basic program processes two arguments from the command line, transforms them into integers using the Integer wrapper and then uses concatenation to construct an informative output.
when the program is called from the command line, it looks like this:
java ArgsProcessor02 5 2
The sum of 5 + 2 is 7
One of the most popular and useful Objects that a computer programmer will use is called Scanner. The Scanner is used to scan or inspect an input from the computer user token by token. The Scanner has several purposes other than simply scanning the user's input; it can also be used to scan a String or to read a file.
To use Scanner you must incorporate the following three steps into your code:
Import the Scanner library
Create a Scanner object -- a scanning handler
Use Methods to Scan User's Input
Import the Scanner Library
To use the Scanner object, it is important to request assistance from the Java Library that contains the Scanner by typing the following line at the very top of the program
import java.util.Scanner;
The import line is important to consider as the very first line of code in a program. If you don't include this line, Java will not recognize the functionality of Scanner and Errors will be thrown.
Create a Scanner object
Anytime that a Scanner is required, an object of type Scanner must be created. In Java, the notion of "creating a new object" means that the program will store a mechanism in memory to use functionalities and other characteristics in the program. The way is done this is by using the keyword new after the = sign, as follows:
Scanner input = new Scanner(System.in);
where:
Scanner is the object being created.
input is the variable name assigned to this object.
The = is an assignation operator
new is the keyword used to create a new *instance* of the object Scanner
System.in is the mechanism that will permit to interact with the computer user. The Scanner will use the "input from the system (i.e., System.in).
This is the general format in which we will be creating objects in Java.
Use Methods to Scan User's Input
Scanner counts with several methods used to extract data from the computer user. A complete list of the methods can be found at [Java API](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html). Some of the methods are shown in Table 5.
In contrast to interacting with the computer user through args, Scanner has the ability to open a dialog with the computer user and provide the opportunity to input an answer based on the question the program requests.
Example
Let us translate the example ArgsProcessor01; instead of providing arguments, have the program request two strings to the computer user. The program shall be called ScannerExample01.java.
1. import java.util.Scanner;
2. public class ScannerExample01{
3. public static void main(String [] args){
4. Scanner input = new Scanner(System.in);
5. System.out.print("Enter the first word");
6. String first = input.nextLine();
7. System.out.print("Enter the second word");
8. String second = input.nextLine();
9. System.out.println(first);
10. System.out.println(second);
11. }
12. }
By compiling and running this program, the program looks like this:
>javac ScannerExample01.java
>java ScannerExample01
Enter the first word: [hello]
Enter the second word: [world]
hello
world
Java counts with several Graphical User Interfaces (GUI) libraries. These libraries provide "more user-friendly" applications. One of these libraries is the JOptionPane. To use this library is important to import the library javax as follows:
import javax.swing.JOptionPane;
Similar to what we did with Scanner.