1. Declaring and Using Constants and Variables

    Declaring Variables
    A variable declaration is a statement that reserves a named memory location and includes the following: • A data type that identifies the type of data that the variable will store • An identifier that is the variable’s name • An optional assignment operator and assigned value, if you want a variable to contain an initial value • An ending semicolon int myAge = 25; int height = 70, weight = 190;
    Declaring Named Constants
    A variable is a named memory location for which the contents can change. If a named location’s value should not change during the execution of a program, you can create it to be a named constant: • In its declaration statement, the data type of a named constant is preceded by the keyword final. • A named constant can be assigned a value only once, and then it cannot be changed later in the program. Usually you initialize a named constant when you declare it; if you do not initialize the constant at declaration, it is known as a blank final, and you can assign a value later. Either way, you must assign a value to a constant before it is used. • Although it is not a requirement, named constants conventionally are given identifiers using all uppercase letters, using underscores as needed to separate words. For example, each of the following defines a conventionally named constant: final int NUMBER_OF_DEPTS = 20; final double PI = 3.14159; final double TAX_RATE = 0.015; final string COMPANY = "ABC Manufacturing";
    Concatenating Strings to Variables and Constants
    public class NumbersPrintln { public static void main(String[] args) { int billingDate = 5; System.out.print("Bills are sent on day "); System.out.print(billingDate); // billingDate is used alone System.out.println(" of the month"); System.out.println("Next bill: October " + billingDate); // billingDate is concatenated with a string } }
    import javax.swing.JOptionPane; public class NumbersDialog { public static void main(String[] args) { int creditDays = 30; JOptionPane.showMessageDialog(null, "" + creditDays); JOptionPane.showMessageDialog (null, "Every bill is due in " + creditDays + " days"); } }
  2. Learning About Integer Data Types

    In Java, you can use variables of data types byte, short, int, and long to store (or hold) integers;
    TypeMinimum ValueMaximum ValueSize in Bytes
    byte–1281271
    short–32,76832,7672
    int–2,147,483,6482,147,483,6474
    long–9,223,372,036,854,775,8089,223,372,036,854,775,8078
  3. Using the boolean Data Type

    Boolean logic is based on true or false comparisons. Whereas an int variable can hold millions of different values (at different times), a variable that is the boolean data type can hold only one of two values—true or false. The following statements declare and assign appropriate values to Boolean variables: boolean isItPayday = false; boolean areYouBroke = true;
    OperatorDescriptionTrue ExampleFalse Example
    <Less than3 < 88 < 3
    >Greater than4 > 22 > 4
    ==Equal to7 == 73 == 9
    <=Less than or equal to5 <= 58 <= 6
    >=Greater than or equal to7 >= 31 >= 2
    !=Not equal to5 != 63 != 3
  4. Learning About Floating-Point Data Types

    A floating-point number contains decimal positions. Java supports two floating-point data types: float and double. A float data type can hold floating-point values of up to six or seven significant digits of accuracy. A double data type requires more memory than a float, and can hold 14 or 15 significant digits of accuracy. The term significant digits refers to the mathematical accuracy of a value. float pocketChange = 4.87F; You can type either a lowercase or an uppercase F You also can type D (or d) after a floating point constant to indicate it is a double, but even without the D, the value will be stored as a double by default.
    TypeMinimumMaximumSize in Bytes
    float–3.4 * 10383.4 * 10384
    double–1.7 * 103081.7 * 103088
  5. Using the char Data Type

    You use the char data type to hold any single character. You place constant character values within single quotation marks because the computer stores characters and integers differently. For example, the following are typical character declarations: char middleInitial = 'M'; char gradeInChemistry = 'A'; char aStar = '*'; A variable of type char can hold only one character. To store a string of characters, such as a person’s name, you must use a data structure called a String. In Java, String is a built-in class that provides you with the means for storing and manipulating character strings. Unlike single characters, which use single quotation marks, string constants are written between double quotation marks. For example,the expression that stores the name Audrey as a string in a variable named firstName is as follows: String firstName = "Audrey"; You can store any character—including nonprinting characters such as a backspace or a tab—in a char variable. To store these characters, you can use an escape sequence, which always begins with a backslash followed by a character—the pair represents a single character. For example, the following code stores a newline character and a tab character in the char variables aNewLine and aTabChar: char aNewLine = '\n'; char aTabChar = '\t';
    Escape SequenceDescription
    \bBackspace; moves the cursor one space to the left
    \tTab; moves the cursor to the next tab stop
    \nNewline or linefeed; moves the cursor to the beginning of the next line
    \rCarriage return; moves the cursor to the beginning of the current line
    \'Single quotation mark; displays a single quotation mark
    \"Double quotation mark; displays a double quotation mark
    \\Backslash; displays a backslash character
    When you want to produce console output on multiple lines in the command window, you have two options: You can use the newline escape sequence, or you can use the println() method multiple times.
    public class HelloThereNewLine { public static void main(String[] args) { System.out.println("Hello\nthere"); } }
    public class HelloTherePrintlnTwice { public static void main(String[] args) { System.out.println("Hello"); System.out.println("there"); } }
  6. Using the Scanner Class to Accept Keyboard Input

    To create interactive programs that accept input from a user, you can use System.in, which refers to the standard input device (normally the keyboard). To create a Scanner object and connect it to the System.in object, you write a statement similar to the following: Scanner inputDevice = new Scanner(System.in); The Scanner class contains methods that retrieve values from an input device. Each retrieved value is a token, which is a set of characters that is separated from the next set by whitespace. Most often, this means that data is accepted when a user presses the Enter key, but it also could mean that a token is accepted after a space or tab.
    MethodDescription
    nextDouble()Retrieves input as a double
    nextInt()Retrieves input as an int
    nextLine()Retrieves the next line of data and returns it as a String
    nextShort()Retrieves input as a short
    nextByte()Retrieves input as a byte
    nextFloat()Retrieves input as a float. Note that when you enter an input value that will be stored as a float, you do not type an F. The F is used only with constants coded within a program.
    nextLong()Retrieves input as a long. Note that when you enter an input value that will be stored as a long, you do not type an L. The L is used only with constants coded within a program.
    import java.util.Scanner; public class GetUserInfo { public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); // The Scanner class is imported, and used to create an object. System.out.print("Please enter your name >> "); name = inputDevice.nextLine(); // The Scanner object is used with the nextLine() method. System.out.print("Please enter your age >> "); age = inputDevice.nextInt(); System.out.println("Your name is " + name + " and you are " + age + " years old."); } }
    import java.util.Scanner; public class GetUserInfo2 { public static void main(String[] args) { String name; int age; Scanner inputDevice = new Scanner(System.in); System.out.print("Please enter your age >> "); age = inputDevice.nextInt(); // If you accept numeric input prior to string input, the string input is ignored unless you take special action. System.out.print("Please enter your name >> "); name = inputDevice.nextLine(); System.out.println("Your name is " + name + " and you are " + age + " years old."); } }
  7. Using the JOptionPane Class to Accept GUI Input

    You also can accept input in a GUI dialog box using the JOptionPane class. Two dialog boxes that can be used to accept user input are as follows: • InputDialog—Prompts the user for text input • ConfirmDialog—Asks the user a question, providing buttons that the user can click for Yes, No, and Cancel responses
    Using Input Dialog Boxes
    An input dialog box asks a question and provides a text field in which the user can enter a response. You can create an input dialog box using the showInputDialog() method.
    import javax.swing.JOptionPane; public class HelloNameDialog { public static void main(String[] args) { String result; result = JOptionPane.showInputDialog(null, "What is your name?"); JOptionPane.showMessageDialog(null, "Hello, " + result + "!"); } }
    import javax.swing.JOptionPane; public class SalaryDialog { public static void main(String[] args) { String wageString, dependentsString; double wage, weeklyPay; int dependents; final double HOURS_IN_WEEK = 37.5; wageString = JOptionPane.showInputDialog(null, "Enter employee's hourly wage", "Salary dialog 1", JOptionPane.INFORMATION_MESSAGE); weeklyPay = Double.parseDouble(wageString) * // Statement uses parseDouble() to convert String. HOURS_IN_WEEK; dependentsString = JOptionPane.showInputDialog(null, "How many dependents?", "Salary dialog 2", JOptionPane.QUESTION_MESSAGE); dependents = Integer.parseInt(dependentsString); // Statement uses parseInt()to convert String. JOptionPane.showMessageDialog(null, "Weekly salary is $" + weeklyPay + "\nDeductions will be made for " + dependents + " dependents"); } }
    Using Confirm Dialog Boxes
    Sometimes, the input you want from a user does not have to be typed from the keyboard. When you present simple options to a user, you can offer buttons that the user can click to confirm a choice.
    A confirm dialog box that displays the options Yes, No, and Cancel can be created using the showConfirmDialog() method in the JOptionPane class.
    import javax.swing.JOptionPane; public class AirlineDialog { public static void main(String[] args) { int selection; boolean isYes; selection = JOptionPane.showConfirmDialog(null, "Do you want to upgrade to first class?"); isYes = (selection == JOptionPane.YES_OPTION); JOptionPane.showMessageDialog(null, "You responded " + isYes); } }
  8. Performing Arithmetic Using Variables and Constants

    Table describes the five standard arithmetic operators that you use to perform calculations with values in your programs. A value used on either side of an operator is an operand. For example, in the expression 45 + 2,the numbers 45 and 2 are operands. The arithmetic operators are examples of binary operators, so named because they require two operands. The operators / and % deserve special consideration. Java supports two types of division: • Floating-point division occurs when either or both of the operands are floating-point values. For example, 45.0 / 2 is 22.5. • Integer division occurs when both of the operands are integers. The result is an integer, and any fractional part of the result is lost. For example, the result of 45 / 2 is 22. As another example, 39 / 5 is 7 because 5 goes into 39 seven whole times; 38 / 5, 37 / 5, 36 / 5, and 35 / 5 all evaluate to 7.
    OperatorDescriptionExample
    +Addition45 + 2, the result is 47
    -Subtraction45 – 2, the result is 43
    *Multiplication45 * 2, the result is 90
    /Division45.0 / 2, the result is 22.5
    %Remainder (modulus)45 % 2, the result is 1 (that is, 45/2 5 22 with a remainder of 1)
  9. Associativity and Precedence

    When you combine mathematical operations in a single statement, you must understand both associativity and precedence. The associativity of arithmetic operators with the same precedence is left to right. In a statement such as answer = x + y + z;, the x and y are added first, producing a temporary result, and then z is added to the temporary sum. After the sum is computed, the result is assigned to answer. Operator precedence refers to the rules for the order in which parts of a mathematical expression are evaluated. The multiplication, division, and remainder operators have the same precedence, and it is higher than the precedence of the addition and subtraction operators. In other words, an arithmetic expression is evaluated from left to right, and any multiplication, division, and remainder operations take place. Then, the expression is evaluated from left to right again, and any addition and subtraction operations execute.
    OperatorsDescriptionsRelative Precedence
    * / %Multiplication, division, remainderHigher
    + –Addition, subtractionLower
    For example, the following statement assigns 14 to result: int result = 2 + 3 * 4; The multiplication operation (3 * 4) occurs before adding 2. You can override normal operator precedence by putting the operation to perform first in parentheses. The following statement assigns 20 to result: int result = (2 + 3) * 4; The addition within the parentheses takes place first, and then the intermediate result (5) is multiplied by 4. When multiple pairs of parentheses are used in a statement, the innermost expression surrounded by parentheses is evaluated first. For example, the value of the following expression is 46: 2 * (3 + (4 * 5)) First, 4 * 5 evaluates to 20, and then 3 is added, giving 23. Finally, the value is multiplied by 2, giving 46.
  10. Understanding Type Conversion

    When you perform arithmetic with variables or constants of the same type, the result of the operation retains the same type. For example, when you divide two ints, the result is an int, and when you subtract two doubles, the result is a double. Often, however, you might want to perform mathematical operations on operands with unlike types. The process of converting one data type to another is type conversion. Java performs some conversions for you automatically or implicitly, but other conversions must be requested explicitly by the programmer. Automatic Type Conversion When you perform arithmetic operations with operands of unlike types, Java chooses a unifying type for the result. The unifying type is the type to which all operands in an expression are converted so that they are compatible with each other. Java performs an implicit conversion; that is, it automatically converts nonconforming operands to the unifying type. Implicit conversions also are called promotions double Highest float long int Lowest (short and byte are automatically converted to int when used in expressions.) Explicit Type Conversions You can purposely override the unifying type imposed by Java by performing a type cast. Type casting forces a value of one data type to be used as a value of another type. To perform a type cast, you use a cast operator, which is created by placing the desired result type in parentheses. Using a cast operator is an explicit conversion. The cast operator is followed by the variable or constant to be cast. For example, a type cast is performed in the following code: double bankBalance = 189.66; float weeklyBudget = (float) (bankBalance / 4); // weeklyBudget is 47.415, one-fourth of bankBalance
  11. You Do It Exercises

    public class DataDemo { public static void main(String[] args) { int aWholeNumber = 315; final int STATES_IN_US = 50; System.out.print("The number is "); System.out.println(aWholeNumber); System.out.println("The number of states is " + STATES_IN_US); } }
    public class IntegerDemo { public static void main(String[] args) { int anInt = 1234; byte aByte = 12; short aShort = 12345; long aLong = 1234567890987654321L; int anotherInt = anInt * 10000000; System.out.println("The int is " + anInt); System.out.println("The byte is " + aByte); System.out.println("The short is " + aShort); System.out.println("The long is " + aLong); System.out.println("Another int is " + anotherInt); } }
    public class CharDemo { public static void main(String[] args) { char initial = 'A'; System.out.println(initial); System.out.print("\t\"abc\\def\bghi\n\njkl"); } }
    import java.util.Scanner; public class IntegerDemoInteractive { public static void main(String[] args) { int anInt; byte aByte; short aShort; long aLong; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer >> "); anInt = input.nextInt(); System.out.print("Please enter a byte integer >> "); aByte = input.nextByte(); System.out.print("Please enter a short integer >> "); aShort = input.nextShort(); System.out.print("Please enter a long integer >> "); aLong = input.nextLong(); System.out.println("The int is " + anInt); System.out.println("The byte is " + aByte); System.out.println("The short is " + aShort); System.out.println("The long is " + aLong); } }
    import java.util.Scanner; public class IntegerDemoInteractiveWithName { public static void main(String[] args) { int anInt; byte aByte; short aShort; long aLong; String name; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer >> "); anInt = input.nextInt(); System.out.print("Please enter a byte integer >> "); aByte = input.nextByte(); System.out.print("Please enter a short integer >> "); aShort = input.nextShort(); System.out.print("Please enter a long integer >> "); aLong = input.nextLong(); System.out.print("Please enter your name >> "); input.nextLine(); name = input.nextLine(); System.out.println("Thank you, " + name); System.out.println("The int is " + anInt); System.out.println("The byte is " + aByte); System.out.println("The short is " + aShort); System.out.println("The long is " + aLong); } }
    import java.util.Scanner; public class ArithmeticDemo { public static void main(String[] args) { int firstNumber; int secondNumber; int sum; int difference; int average; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer >> "); firstNumber = input.nextInt(); System.out.print("Please enter another integer >> "); secondNumber = input.nextInt(); sum = firstNumber + secondNumber; difference = firstNumber - secondNumber; average = sum / 2; System.out.println(firstNumber + " + " + secondNumber + " is " + sum); System.out.println(firstNumber + " - " + secondNumber + " is " + difference); System.out.println("The average of " + firstNumber + " and " + secondNumber + " is " + average); } }
    import java.util.Scanner; public class ArithmeticDemo2 { public static void main(String[] args) { double firstNumber; double secondNumber; double sum; double difference; double average; Scanner input = new Scanner(System.in); System.out.print("Please enter a double >> "); firstNumber = input.nextDouble(); System.out.print("Please enter another double >> "); secondNumber = input.nextDouble(); sum = firstNumber + secondNumber; difference = firstNumber - secondNumber; average = sum / 2; System.out.println(firstNumber + " + " + secondNumber + " is " + sum); System.out.println(firstNumber + " - " + secondNumber + " is " + difference); System.out.println("The average of " + firstNumber + " and " + secondNumber + " is " + average); } }
    import java.util.Scanner; public class ArithmeticDemo3 { public static void main(String[] args) { int firstNumber; int secondNumber; int sum; int difference; double average; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer >> "); firstNumber = input.nextInt(); System.out.print("Please enter another integer >> "); secondNumber = input.nextInt(); sum = firstNumber + secondNumber; difference = firstNumber - secondNumber; average = (double) sum / 2; System.out.println(firstNumber + " + " + secondNumber + " is " + sum); System.out.println(firstNumber + " - " + secondNumber + " is " + difference); System.out.println("The average of " + firstNumber + " and " + secondNumber + " is " + average); } }
  12. Case Problems

    import java.util.Scanner; public class CarlysEventPrice { public static void main(String[] args) { final double GUEST_PRICE = 35.00; final int LARGE_EVENT = 50; double price; int guests; Scanner input = new Scanner(System.in); System.out.print("Enter number of guests >> "); guests = input.nextInt(); System.out.println("****************************************************"); System.out.println("* *"); System.out.println("* Carly's makes the food that makes it a party. *"); System.out.println("* *"); System.out.println("****************************************************"); price = guests * GUEST_PRICE; System.out.println("The price for an event with " + guests + " guests at $" + GUEST_PRICE + " per guest is $" + price); System.out.println("Whether this is a large event is " + (guests >= LARGE_EVENT)); } }
    import java.util.Scanner; public class SammysRentalPrice { public static void main(String[] args) { final int MINUTES_IN_HOUR = 60; final int HOUR_RATE = 40; int minutes; int hours; int extraMinutes; int price; Scanner input = new Scanner(System.in); System.out.print("Enter minutes >> "); minutes = input.nextInt(); hours = minutes / MINUTES_IN_HOUR; extraMinutes = minutes % MINUTES_IN_HOUR; price = hours * HOUR_RATE + extraMinutes; System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); System.out.println("S S"); System.out.println("S Sammy's makes it fun in the sun. S"); System.out.println("S S"); System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); System.out.println("For a rental of " + hours + " hours and " + extraMinutes + " minutes, the price is $" + price); } }