Variables in Java
Variables in Java are used to store information that may change through the course of the program, either through computation or user input. There are two main types of variables: primitive and reference. The concepts of declaring a variable (giving it a type and name) and initializing a variable (giving it an initial value) remain the same in java. A new term in Java is intantiation. Instantiating a variable means to call a constructor method (used for reference type variables).
origin=new Point(0,0);
Scanner reader=new Scanner(System.in); //combining the declaration and instantiation
When naming variables, programmers should choose names that indicate the value that the variable holds. For example, itemCost is much more descriptive than x. Also, when naming a variable in Java the following rules apply:
- The variable name must begin with a letter
- Variable names can only contains letters, numbers and underscores
- Variable names cannot be reserved words (e.g. class, double, main, etc).
- It is a convention in Java to name variables beginning with lower case letters and using capitalization to enhance readability (camelCase)
Primitive type variables are native to Java and include byte, char, short, int, long, float, double and boolean. Byte, short, int and long are used to store integer values of different ranges. Char type variables store single character entities, such as 'G' or '&'. Float and double type variables store decimal numbers of different ranges. Boolean type variables store a value of true or false. Primitive type variables store the value in the variables memory location.
The most commonly used variable types in learning programming are int, double, char and boolean. Below, you will see examples of variable initializations for each of these types:
int zip=19462;
double weight=1.5;
char initial='M';
boolean isMale=true;
Reference type variables are object instances of classes. When declared, they need to be instantiated using the keyword new and the class constructor. Reference type variables store a reference to the objects memory location in the variables memory location.
The middle ground between these two types of variables is the String type. In reality, the String class is a reference type variable, but the creators of Java realized its importance and allow it to often work more like a primitive. For example, a String type variable can be declared and initialized without a constructor call.
String name=new String("Jim");
String name="Jim";
When assigning a variable, we use the = assignment operator. The variable should be on the left side with the value on the right. There are other assignment operators such as +=, -=, /=, *=, and %=. An example of use for these operators is that total=total + num is the same as total += num.
Variables can be assigned to literals, input results, or computations. Basic computation operators include +, -, *, /, and %. Modulus (%) is an operation that gives the remainder when two values are divided.
Some variables, we want to make sure that their values do not change through the course of the program. These are called constants and are denoted in all caps and use the keyword final in their declaration. An example is:
final double SALES_TAX = 06;
Console Output
Basic console output is a simple concept in Java. You have a choice of two methods: System.out.print() and System.out.println(). The only difference is that the println() method attaches a line break to the end of your output. To use these methods, you simply insert a string, calculation, method call or variable inside the parenthesis as a parameter of the method. Examples:
System.out.print("Hello");
System.out.println("What is your name?");
System.out.println(firstName);
System.out.print(4*8);
System.out.println(5.00*salesTax);
To show a string and the value of a variable, use the '+' symbol to concatenate the information together. Either side of the concatenation operator needs to be either a quoted string, variable name, number or calculation. However, since the '+' operator is overloaded in Java, there can be side effects as the order of operations dictates that '+' be completed from left to right. To avoid such issues, be sure to place addition in parenthesis so that it happens prior to any concatenation.
In Java, there are some special characters that we can place inside of quotation marks to produce some special characters. For example, if we wanted to display This is a quotation mark - ". We would have some difficulty with Java because Java would see the second quotation mark and end the string. So, we need to 'escape' the rules temporarily. The way that we escape the rules is using the '\' character. When the computer sees this character, it looks at the next character to complete the code. Below is a list of escape sequences:
- \n - new line
- \t - tab
- \r - carriage return
- \" - double quote
- \' - single quote
- \\ - backslash
Note the need for \\ to show a backslash. This is because if you show '\' in the code, the computer will be looking for an escape sequence.
Console Input
Starting in Java 5, a built int class to take input was incorporated. This class is called the Scanner class and takes care of the back end intricacies of input and creates a simple way to get console information from a user. To use the Scanner class you must create a Scanner variable. Scanner variables are reference type variables, so they need to be declared and instantitated. When instantiating a Scanner variable, System.in must be passed as a parameter so that the Scanner knows to read from the keyboard. Also, there is an import required in order to use the Scanner class. So, programs that need to take user input will begin as follows:
import java.util.Scanner;
public class Input{
public static void main(String [] args){
Scanner reader=new Scanner(System.in);
...remainder of program follows
The variable reader in the program above can be named anything the programmer desires, as long as they follow the Java language rules for naming identifiers. Other options that are often used are input, io, read, etc.
The following methods are part of the Scanner class:
- nextInt(); //returns an int
- nextDouble(); //returns a double
- nextBoolean(); //returns a boolean
- nextLine(); //returns a String, terminated by a newline
- next(); //returns a String, terminated by whitespace
At a basic level, Scanner input would look like this:
System.out.println("Enter your age:");
int age=reader.nextInt(); //use next Int because the age variable is an int
System.out.println("You are "+age+" years old.");
Since there is no method to read a character variable, we have to read a string and find the character at its first spot.
System.out.println("What is your first initial?");
char initial=reader.nextLine().charAt(0);
There is a problem with the Scanner class that can be easily fixed. The issue comes in how the object reads from the stream. When an integer or double is read, the Scanner object reads the next number until it encounters whitespace (space, tab, return, etc). If we are reading multiple number consecutively, no problem. But, if we read a number followed by a string - big problem. What happens is the program will read the number and leave the users return on the stream. So, when it goes to read the nextLine(), it first finds the return character and stores nothing in the String variable. This can be fixed with a dummy read - a call to read input that is not stored in a variable.
System.out.println("Enter your age:");
int age=reader.nextInt();
reader.nextLine(); //dummy read to take the return off the stream
System.out.println("Enter your name:");
String name=reader.nextLine();
This practice is only necessary when you are going to take a String AFTER you have read an integer or Double.
Dialog IO (Optional)
Output can also be sent to the screen using a GUI dialog box called a message box. This message box is part of thw swing package in a class called JOptionPane, so be sure to import javax.swing.JOptionPane when trying to use this type of output. The method needed is called showMessageDialog and it takes four parameters:
- Component parentComponent - identifies the parent of the dialog box. we will always write null for this parameter
- String text - this is the actual output. The message that you want to send to the user.
- String title - this is the title for the message box. It must be in quotes.
- int icon - an int value that represents the icon that will appear in the box. JOptionPane has several constant variables that represent the different icons. They are listed below:
- JOptionPane.ERROR_MESSAGE - error icon
- JOptionPane.INFORMATION_MESSAGE - info icon
- JOptionPane.PLAIN_MESSAGE - no icon
- JOptionPane.QUESTION_MESSAGE - question icon
- JOptionPane.WARNING_MESSAGE - exclamation point icon
A typical call to show a message dialog box would look like this:
JOptionPane.showMessageDialot(null, "output information", "Box Title", JOptionPane.INFORMATION_MESSAGE);
JOptionPane also allows for easy dialog input in three formats: showInputDialog, showConfirmDialog, showOptionDialog.
The showInputDialog method takes only 1 parameter, the string prompt. It always returns a string, so information that needs to be treated as a number must be parsed. An example of the showInputDialog method is as follows:
int num =Integer.parseInt( JOptionPane.showInputdialog("Enter a number:"));
The showConfirmDialog allows the programmer to ask a simple yes/no questions. In its simplist form, there are three buttons: Yes, No and Cancel. This dialog returns an integer, 0 for yes, 1 for no and 2 for canel. This way, programmers can account for users not givein appropriate input by liminteg their choices. This method takes two parameters, the parentComponent (always null) and the string prompt. An example of the code is as follows:
int choice=JOptionPane.showConfirmDialog(null, "Would you like to continue?");
There are more advanced versions of the method available that allow programmers to show icons on the dialog and/or change the labels on the buttons.
The showOptionDialog method is the most versitile, and most complicated, of the dialog input choices. This method allows users to sepcify what type of input they want to take and it can be adapted to fit many needs. The method takes eight parameters and returns an int value of the button that is selected (starting at 0). The parameters are:
- Component parentComponent - usually null
- String dialogText - the question to be asked
- String dialogTitle - the title of the dialog box
- int buttonSet - the type of buttons in the box, typically JOptionPane.YES_NO_OPTION
- int icon - see the dialog output icon options
- null
- String [] options - the text for the buttons
- String default - the default selected/highlighted button
An example of the showOptionDialog method is as follows:
String [] buttons = {"Male", "Female", "Undecided"};
int choice = JOptionPane.showOptionDialog(null, "Are you male or female?", "Choice", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, buttons, buttons[0]);