2: Java Basics

What We Will Cover


Illuminations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  • Where do you turn in programming assignments?
  • What was your impression of Blackboard?
  • What is scholastic dishonesty?
  • What is an example of acceptable help on programming assignments
  • What is an example of unacceptable help on programming assignments
  • What was your experience installing the JDK?

2.1: Language Basics

Learner Outcomes

At the end of the lesson the student will be able to:

  • Make comments in code
  • Print data to a console
  • Create program variables and assign them values
  • Declare the data type of a variable
  • Identify the data type of various literal values
  • Create code to perform arithmetic
  • Convert the data type of a primitive value to another type
  • Distinguish between pre and post operators for both increment and decrement operations
  • Generate code that uses literal strings

2.1.1: Example Program

  • Here is the example program like the one we looked at before
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Hello.java
 * Purpose: Displays a greeting.
 *
 * @author Ed Parrish
 * @version 1.1 8/17/08
 */
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    } // end of main method
} // end of Hello class

Brief Explanation by Line Number

  • Lines 1-7: comments about the class -- notes to programmers
  • Line 8: the class declaration
  • Line 9: the main() method where all programs start
  • Line 10: a programming statement to display data to the console
  • Line 11: the end of the main() method followed by another comment
  • Line 12: the end of the Hello class followed by another comment

2.1.2: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by the compiler
  • You use comments to document blocks of code and to describe unusual code
  • One form of comments starts with // and lasts to end of the line
    // this is a comment
  • Another form affects a section of code: /* ... */
  • This form can span multiple lines or just a portion of one line:
    /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    

Javadoc Comments

  • Java also has a third type of comment known as a Javadoc comment
  • Javadoc comments are used to generate documentation automatically
  • Syntax:
    /**
     * Description part of a Javadoc comment
     *
     * @tag Comment for the tag
     */
    
  • Note the extra star (*) in the opening of the comment
  • Javadoc comments have two parts:
    1. Description of the code
    2. Followed by zero or more tags
  • For example, you should put a Javadoc comment like the following at the beginning of every class:
    /**
     * Hello.java
     * Purpose: Prints a message to the screen.
     *
     * @author Ed Parrish
     * @version 1.0 8/30/05
     */
    
  • In this example, we have two tags:
    • @author followed by the name of the author
    • @version followed by the version number or date
  • In addition, you put Javadoc comments like the following before every method:
    /**
     * The main method for the Hello program.
     *
     * @param args Not used
     */
    
  • Then you use a tool, known as Javadoc, to automatically create program documentation
  • Also, a tool known as CheckStyle will check your comments (among other things) for correct usage
  • I have some instructions for setting up TextPad to run these tools:
  • Also, you can run CheckStyle from the command line following the instructions here: Running CheckStyle

More Information

2.1.3: Primitive Data Types

  • One of the things you need to know is the rules for handling data
  • We tell a compiler how to handle data by using a data type

    data type: a set of values from which a variable may take its value.

  • Java has two main classifications of data types: primitive and class
    • We will cover class types later
  • A data type is important because it tells the compiler:
    • How much memory to allocate
    • The format to use when storing the data in memory
    • The operations permitted on the data
  • We categorize primitive types into: integer, floating point, character and boolean

Integer data types: byte, short, int, long

  • Integer types are positive or negative numbers without fractional parts
  • Literal numbers are written as you would expect: a series of digits optionally preceded by a minus sign
  • The compiler stores all literal integers as an int data type by default
  • The range of an int is from -2147483648 to 2147483647
  • For larger integer values, like the number of people on our planet, you need to use a long
  • To specify a long integer type, you add an "L" or "l" after the number
  • For example:
    int number = -215;
    long population = 6717431078L; // As of 08/17/08
    
  • Note that without the "L", the above would not compile

Floating-point types: float, double

  • You use floating-point types for numbers with fractional parts
  • The two floating-point types are: float and double
  • The name double refers to the fact that a double has twice the precision of float
  • Precision refers to the number of digits of accuracy for the number
  • Literal values are a series of numbers with a decimal point
  • Precision is usually important when using floating-point numbers
  • Thus the compiler stores all literal floating-point numbers as a double by default
  • This means that if you want a float you must type an "F" (or "f") after the number
  • However, you normally use double because float is too imprecise for many situations
  • For example:
    double fraction = 1.0 / 3.0;
    float small = 1.125F;
    

Character data type: char

  • You use the char data type to store a single symbol like a letter or digit
  • The char data type is stored using the Unicode UTF-16 character set
  • Unicode includes all ASCII codes plus additional ones for languages with symbols other than English
  • Literal values are enclosed in single quotes
  • For example:
    char A = 'A';
    char B = 66;
    char C = '\u0043';
    System.out.println("Letters: " + A + B + C);
    
  • The second example above shows that Java will convert an integer to the UTF-16 code

Boolean type: boolean

  • You use type boolean to store the values: true and false
  • For example:
    boolean truth = true;
    boolean lies = false;
    
  • Note that you cannot convert between integers and boolean values, like you can in C/C++
  • This prevents you from making mistakes like:
    if (x = 0) // oops, should be x == 0

Table of Primitive Data Types

Type Name Format Size Range
byte integer 1 byte -128 to 127
short integer 2 bytes -32768 to 32767
int integer 4 bytes -2,147,483,648 to 2,147,483,647
long integer 8 bytes -9,223,372,036,854,775,808 to 9,223,374,036,854,775,807
float floating point 4 bytes +/- 1.4023... x 10-45 to +/- 3.4028... x 1038
double floating point 8 bytes +/- 4.940... x 10-324 to +/- 1.767... x 10308
char UTF-16 2 bytes All Unicode characters
boolean true or false 1 byte Not applicable

2.1.4: Variables and Assignment

  • A variable is the name of a location in main memory
  • All Java program variables must be declared before using them
  • A declaration statement both names a variable and specifies the data type it can store
  • General syntax:
    dataType VariableName1, VariableName2, ...;
    
  • Where:
    • dataType: one of the Java data types
    • VariableNameX: the name of the variable
  • For example:
    int num1, num2, total;
    long dateNum;
    float firstNum;
    double secNum;
    char letter;
    
  • Variable names must follow the rules for valid identifiers

Naming a Variable

  • A variable name is a sequence of letters, digits, underscores ( _ ) and currency symbols like: $, ¢, £, ¥
  • However, Java has some limitations on what you chose for a variable name
  • Specifically, the first character must be either a letter, underscore character "_" or currency symbol
    • Cannot be a number
    • A currency symbol is allowed but its use is discouraged
  • Also, the variable name cannot be one of the Java reserved words (keywords)
    • For a list of reserved words, see: keywords
  • Note that you cannot have spaces in a variable name
  • A space is NOT a letter, digit, underscore character or currency symbol
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

Assigning Values to Variables

  • When variables are declared, the computer allocates storage space for them
  • Your program must then assign values to the variables
  • To change the value of a variable, you use the assignment operator ("equals sign"): =
    variable = expression;
  • The value of the expression on the right side gets assigned to the variable on the left side
  • For example:
    int counter;   // declare variable counter
    counter = 10;  // initialize counter to ten
    
  • You can combine variable declaration and assignment into one statement:
    int counter = 10; // declare and initialize counter
    
  • Note that if you try to use an uninitialized local variable, the code fails to compile:
    // These may not be initialized when declared
    // and have unknown values
    int sum, number1, number2;
    sum = number1 + number2;
    
  • Instead, you must initialize local variables
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    sum = number1 + number2;
    

Shortcut Assignment Operators

  • You can use additional operators to calculate values and assign them to the variable on the left all in one statement
    • Known as shortcut assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is one of the five arithmetic operators: +, -, *, /, %
  • For example, the following two statements produce the same result:
    x = x + 3;
    x += 3;
    

Constant Variables

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Sounds oxymoronic, but is actually quite useful
  • Java uses the keyword final to indicate a variable that cannot change
    final int MY_CONSTANT = 10;
  • Most of the time you declare and assign a value to a constant in one statement
  • However, this is not necessary in Java
  • When you do not assign an initial value, it is called a blank final variable
  • The compiler is smart enough to ensure that:
    • A blank final variable is assigned a value eventually
    • A blank final variable is not used until after it is assigned a value
    • A blank final variable is never reassigned another value
  • Thus, you can write code like the example below

Example of a Blank Final Variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Scanner;

public class BlankFinal {
    public static void main(String[] args) {
        final int CONST;
        // Following causes a compiler error
        //System.out.println("CONST = " + CONST);
        System.out.print("Enter an integer number: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        CONST = num;
        System.out.println("CONST = " + CONST);
        //CONST = 9; // Compiler error
    }
}

2.1.5: Arithmetic Operators and Variables

  • Like most other languages, simple arithmetic is performed with operators
  • An operator is a symbol that acts upon a number or a variable
  • You combine operators, items and variables into a part of a statement known as an expression

    Expression -- a part of a program statement that is evaluated and that returns a value

  • For example:
    x + y - 3
  • Shown below are the five binary arithmetic operators with examples of how they are used
  • These operators are known as binary operators because they work with two items

Arithmetic Operators (Binary)

Operator Description Example
+ Adds or combines two items men = 10;
women = 15;
total = men + women;
- Subtracts one item from another income = 1000;
expenses = 750;
profit = income - expenses;
* Multiplies two items width = 20;
height = 30;
area = width * height;
/ Divides one item by another persons = 20;
cost = 30;
costPerPerson = cost / persons;
% Calculates the remainder after dividing one item by another numEggs = 65;
cartonSize = 12;
eggsLeft = numEggs % cartonSize;

Truncation in Integer Division

  • Integer division truncates the remainder
    • 7 / 5 evaluates to 1
  • You need to use the modulus operator % to know the remainder
  • The modulus operator returns the remainder after the division of two numbers
  • For example:
    int a = 15; b = 12, c;
    c = a % b;
    
  • c has the value 3, which is the remainder when 15 is divided by 12

Mixed-Mode Arithmetic

  • No truncation occurs if at least one of the values is of type float or double
  • Instead, both values are promoted to the highest data type of the two using the following hierarchy:
    byte => short => int => long => float => double
    
  • For example:
    int a = 4, b = 5, c;
    double x = 1.5, y;
    y = b / x; // value returned by b is promoted to double
               // value of y is about 3.33333
    c = b / a; // all values are ints so the division
               // truncates: the value of c is 1
    

Arithmetic Operators (Unary)

  • Java also has unary operators that work on only one item
  • Shown below are three unary arithmetic operators with examples of how they are used
Operator Description Example Equivalent To
- Changes the sign of (negates) an item's value -x x = 0 - x
++ Increases the item's value by one x++ x = x + 1
-- Decreases the item's value by one x-- x = x - 1
  • Unary operators can make your code more compact but can give unexpected results if you are not careful
  • For example, consider the code:
    int x, y;
    x = 5;
    y = x++;
    System.out.println("x=" + x + " y=" + y);
    
  • You may expect y to be 6 after this code executes
  • However, the code produces the following output:
    x=6 y=5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    x = y;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    x = y;
    

Check Yourself

  • Lets check our understanding of the increment and decrement operators with the following code
  • Write down what you think the program will display before you check the answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class PrePost {
    public static void main(String[] args) {
        int a, b, c;

        // Prefix order
        a = 10;
        b = ++a;
        System.out.println("a=" + a + ", b=" + b);
        c = b + --a;
        System.out.println("a=" + a + ", c=" + c);
        --a;
        System.out.println("a=" + a + "\n");

        // Postfix order
        a = 10;
        b = a++;
        System.out.println("a=" + a + ", b=" + b);
        c = b + a--;
        System.out.println("a=" + a + ", c=" + c);
        a--;
        System.out.println("a=" + a);
    }
}

Parenthesis and Precedence

  • Some arithmetic operators act before others (e.g., multiplication before addition)
    • Java follows rules similar to real-number algebra
  • Arithmetic operations are processed in algebraic order:
    1. Parentheses ( )
    2. Unary operations: +, -, ++, --
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Binary operators of same precedence are evaluated from left to right
  • To change the usual order, you can use parenthesis to group expressions
    • Anything within parenthesis is evaluated first
  • For example, to find the average of three variables a, b and c
    • Do not use: a + b + c / 3
    • Instead use: (a + b + c ) / 3
  • You can have parenthesis within parenthesis
    • The innermost parenthesis is evaluated first:
      (2 * (10 + 5))

2.1.6: Magic Numbers

  • Imagine that you are a programmer hired to modify a payroll program
  • You come across the following section of code:
    double pay;
    pay = hours * 7.5 + (hours / 40)
          * (hours - 40) * 7.5 * 0.5;
    
  • The numbers are important to the program, but what do they mean?
  • Numbers like these are called "magic numbers"
  • They are magic because the value or presence is unexplainable without more knowledge
    • Often, no one knows what they mean after 3 months, including the author
  • A programmer can often infer the meaning of numbers after reading the code carefully
  • Much better code is to use named constants rather than literal numbers
  • For example:
    final double WAGE = 7.5;
    final double OVERTIME_ADDER = 0.5;
    final int HOURS_PER_WEEK = 40;
    double pay;
    pay = hours * WAGE + (hours / HOURS_PER_WEEK)
          * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
    
  • Now it is much easier to read and understand the code
    • And see any problems or limitations

Programming Style: Constant Variables and Magic Numbers

  • Since the meaning of literal ("magic") numbers is hard to remember, you should declare constants instead
    final int FEET_PER_YARD = 3;
    final double PI = 3.14159;
    final double WAGE = 7.5;
    final double OVERTIME_ADDER = 0.5;
    final int HOURS_PER_WEEK = 40;
    
  • Note that the name is all uppercase letters with an underscore separator
  • This is a common coding convention that you must follow

2.1.7: Type Conversion

  • We often find ourselves converting one data type into another
  • This process is called type conversion or typecasting
  • Java is a strongly-typed language and checks for compatible data types both when compiling and while running
  • To put a value of a different type in a variable, you must convert the type
  • There are two types of conversion: implicit and explicit
  • The term for implicit conversion is sometimes called coercion
  • The most common form of explicit conversion is know as casting

Coercion

  • Type conversion is done automatically (implicitly) when a narrower-type is assigned to a broader-type:
    • Narrower means a smaller number of bytes
    • Broader means a larger number of bytes
  • Data type hierarchy (from narrowest to broadest):
    byte => short => int => long => float => double
                    /
             char =/
    
  • For example:
    double x;
    int n = 5;
    x = n;
    
  • Since n is an integer and x is a double, the value returned by n must be converted to type double before it is assigned to x
  • Note that casting only changes the type of an expressions's returned value
    • Not the type of the variable
  • Thus the data type of variable n is unchanged -- it is still an int

Coercion in an Arithmetic Expression

  • Some arithmetic expressions have a mix of data types
  • All values implicitly cast to the highest level before the calculation
  • For example:
    double a;
    int n = 2;
    float x = 5.1F;
    double y = 1.33;
    a = (n * x) / y;
    
  • n and x are automatically cast to type double before performing the arithmetic

Explicit Casting

  • Explicit casting changes the data type for a single use of the variable
  • To cast, precede the variable name with the new data type in parentheses:
    (typeName) variableName
    
  • Where:
    • typeName: one of the Java data types
    • variableName: the name of the variable
  • For example:
    int n;
    double x = 2.0;
    n = (int) x;
    
  • The value of x is converted from type double to int before assigning the value to n
  • Note that explicit casting is required to assign a broader type to a narrower type
  • ILLEGAL: Implicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = x; // illegal in Java
    

    Illegal since x is double, n is an int, and double is a higher data type than int

  • LEGAL: Explicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = (int) x; // legal in java
    
  • You can use an explicit cast even when an implicit one will be done automatically

Truncation When Casting double to Integer type

  • Converting (casting) a double to integer type does not round -- it truncates
  • The fractional part is lost (discarded, ignored, thrown away)
  • For example:
    int n;
    double x = 3.99999;
    n = (int) x; // x truncated
    
  • Value of n is 3

Converting Between char and int Values

  • Casting a char value to int produces the ASCII/Unicode value
  • For example, what would the following display?
    char answer = 'Y';
    System.out.println(answer);
    System.out.println((int) answer);
    
  • Answer:
    y
    89
    
  • You can convert characters to integer numbers as well:
    char ch7 = '7';
    char ch9 = (char) (ch7 + 2);
    int num7 = ch7 - '0';
    int num9 = num7 + 2;
    System.out.println("ch9: " + ch9);
    System.out.println("num9: " + num9);
    

2.1.8: Strings

  • A string is a series of characters
  • To make working with strings easier, Java provides the String data type
  • Strings are enclosed in double quotes, which are not part of the string
  • For example:
    "Hello"  "b"  "3.24159"  "$3.95"  "My name is Ed"
    
  • We use double quotes (") to mark the beginning and end of a string

Declaring and Assigning string Variables

  • We declare and assign values to string variables like numeric types
  • For example:
    String message = "Please enter an identification code";
    System.out.println(message);
    

Joining Strings (Concatenation)

  • You can join two strings together using the '+' operator
  • The join operation is called concatenation
  • For example:
    String cool = "Java" + " rules!"
    System.out.println(cool);
    

String Conversions

  • We can easily convert numerical data types, like int or double, to strings using the + operator
  • If an expression starts with a String type then the compiler converts other types to String automatically
  • For example:
    System.out.println("The result is: " + 7 + 2);
    
  • Produces the output:
    The result is: 72
    
  • If you want to add 7 + 2, you need to use parenthesis:
    System.out.println("The result is: " + (7 + 2));
    

2.1.9: Summary

  • Every Java program starts at a main() method
    public static void main(String[] args) {
        // statements to execute
    }
    
  • Java has three styles of comments
    • //
    • /* ... */
    • /** ... */
  • Java has two classifications of data types: primitive and class
  • Data types are important because they tell the computer:
    • How much memory to allocate
    • The format to use when storing the data in memory
    • The operations permitted on the data
  • Java has eight primitive data types in four categories:
    • Integer: byte, short, int and long
    • Floating point: float and double
    • Character: char
    • Boolean: boolean
  • Variables store a value that can change as a program executes.
  • Constants store a value that cannot change.
  • Variables and constants must be declared before use.
  • To declare a variable or constant, specify a data type and a name.
  • You assign values to a variable using an assignment statement
  • Simple assignment statements have a variable, equals sign and an expression:
    variable = expression;
  • The expression is computed before the assignment
  • Java has assignment variations of the form:
    variable <op>= expression;
  • Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • Results of integer division is truncated
  • Must use modulus operator (%) to get the remainder value
  • Operators have the same precedence as in algebra:
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • You can explicitly cast values of an expression to a different type.
  • You must use an explicit cast when assigning a broader type to a narrower type:
    int count = input.nextInt();
  • Even though strings are objects in Java, you can assign them to a variable using the assignment operator
  • Also, you can concatenate two strings using the "+" operator

Check Yourself

  1. Where does every Java program start executing?
  2. What styles of comments does Java allow?
  3. What is the purpose of Javadoc comments?
  4. What is the purpose of a data type?
  5. What are the eight primitive data types that Java supports?
  6. What are the rules for creating an identifier?
  7. What is the code to declare an int variable named foo and assign it a value of 10?
  8. What is the code to declare a constant double named BIG_NUM and assign it a value of 100,000?
  9. What are the five operators Java uses for arithmetic?
  10. How do you calculate the square root of a number like 27?
  11. What is meant by the term casting? coercion?
  12. What data type is returned from an expression when an int and a double are added together?
  13. What is wrong with the following code?
    double x = 1;
    int y = x;
    
  14. What type of delimiters are used to encapsulate literal strings?
  15. What is the code to declare a string variable named foo?
  16. What operator is used to join two strings?

Exercise 2.1

Lets go through these one at a time. Take one minute to prepare an answer and then we will discuss it.

  1. Given the following code, which statement is true?
    int a, b = 1;
    
    1. Variable a is not declared
    2. Variable b is not declared
    3. Variable a is declared but not initialized
    4. Variable b is declared but not initialized
    5. Neither variable is declared nor initialized
  2. What is the value returned by the following expressions?
    - -1-3 * 10 / 5-1;
    
    1. -8
    2. -6
    3. 7
    4. 8
    5. 10
  3. Starting with the code:
    int n = 3;
    int m = 4;
    int result;
    

    What will be the value of m and result after each of these executes?

    1. result = n * ++m; //preincrement m
    2. result = n * m++; //postincrement m
    3. result = n * --m; //predecrement m
    4. result = n * m--; //postdecrement m
  4. What does the following code do?
    char ch7 = '7';
    int num7 = ch7 - '0';
    System.out.println("answer: " + num7 + 2);
    
    1. Error
    2. prints 72
    3. prints 9

2.2: Libraries, Classes and Console I/O

Learner Outcomes

At the end of the lesson the student will be able to:

  • Import standard API classes
  • Create objects and call methods
  • Display information to a console
  • Get user input from the console

2.2.1: Importing Classes

  • To make it easier to write programs, Java has many libraries
  • These libraries contain prewritten code
  • Collectively, these libraries are referred to as the Java Application Programming Interface (API)
  • Recall that all Java code is stored in classes
  • Groups of related classes are organized into packages

Some Commonly Used Packages

Package Name Description
java.lang Provides classes fundamental to Java.
java.io Provides classes to read and write files.
java.txt Provides classes to handle text, dates, and numbers
java.util Provides classes to work with collections and miscellaneous utilities.
javax.swing Provides classes to create graphical user interfaces and applets.

Importing Classes and Packages

  • Classes in the java.lang package are always available
  • To use other classes, you must import them
    import packagename.ClassName;
        or
    import packagename.*;
    
  • Using the '*' wildcard will import all classes in a package
  • For example:
    import java.text.NumberFormat;
    import java.util.Scanner;
    import java.util.*;
    import javax.swing.*;
    

Navigating the API

  • The Java API is located at: http://java.sun.com/javase/6/docs/api/index.html
  • Related classes are organized into packages
    • Shown in the upper left frame
  • When you select a package, all the classes for that package are shown in the lower left frame
  • Once you select a class, it is shown in the right frame
  • Each class shows a variety of information including a summary of all its methods
  • To view the information about a method, either click on its hyperlink or scroll down the page

2.2.2: Creating Objects and Calling Methods

  • To use a Java class, you usually start by creating an object of the class
    • Also known as creating an instance of the class
  • There are two steps to creating an object:
    1. Define a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • To define the variable, you code the class name followed by an identifier
  • For example:
    Scanner input;
  • To create the object, you use the new operator followed by the class name to assign a value to the variable:
    input = new Scanner(System.in);
  • When you create the object, you often pass it an argument like System.in as shown
  • The arguments are specified by the constructor as shown in the API documentation
  • You can combine both steps into one statement, like:
    Scanner input = new Scanner(System.in);

Calling Object Methods

  • One you create an object, you can call its methods
  • To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
  • For example:
    input.nextInt();
  • When you call a method, the method may require one or more arguments
  • These arguments must be coded in the correct sequence separated by commas:
    System.out.println("Hello, World!");
  • After the method is finished, the program flow returns to the point from which the method was called

2.2.3: Printing to a Console

  • Two useful prewritten methods are print() and println()
  • Their function is to display data
  • The difference between the two methods is that:
    • print() leaves the cursor positioned after the last character
    • println() positions the cursor on a new line
  • The cursor position determines where the next character is displayed
  • For example:
    System.out.print("Hello, ");
    System.out.println("world!");
    
  • In these statements, out is the name of an object variable in a Java class named System
  • System is automatically created whenever a Java program is executed
  • System.out lets a program know to send data to the standard output stream
    • Usually the video display screen
  • The data to display is passed to the method within the parenthesis

Escape Sequences

  • Some characters are more difficult to code output for than others
  • For example, what would the compiler do with the following statement?
    System.out.println("Say, "Hey!"");
    
  • Some characters cannot be output directly in a string
  • Also, Not all of first 32 ASCII characters are visible on our monitors
    • Known as control codes because they control the output device
  • Even though these characters are not visible, we sometimes need to use them
  • For example: a newline character
  • We need some way to "print" invisible and hard-to-print characters
  • Java can access some of the control codes and hard-to-print characters using escape sequences
  • A backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
  • Some examples:
    System.out.print('\u0007');
    System.out.print('\n');
    System.out.print("Left\tRight");
    System.out.print("one\ntwo\nthree");
    
  • The following table lists some nonprinting and hard-to-print characters:

Common Escape Sequences

Sequence Meaning Unicode Value
  Alert \u0007
\b Backspace \u0008
\f Formfeed \u000C
\n Newline \u000A
\r Carriage return \u000D
\t Horizontal tab \u0009
\\ Backslash \u005C
\" Double quote \u0022
\' Single quote \u0027

2.2.4: Reading Interactive Input

  • Oftentimes you want a program to ask a user questions and read the input from the user
  • You can read input interactively from the command line (console) using a Scanner object
  • Scanner is located in the java.util package, so you need to import the class using either:
    import java.util.Scanner;
    or
    import java.util.*;
  • You then create a scanner object like:
    Scanner input = new Scanner(System.in);
  • Note that System.in is used to get data from the standard input stream
  • To use one of the methods of a Scanner object, call it like the following:
    int count = input.nextInt();
    
  • When you call a method of a Scanner object, the program waits for the user to enter data with the keyboard
  • Each group of characters that a user enters is called a token
  • The program waits until the user presses the Enter key
  • The user can enter multiple tokens by separating them with whitespace
  • If the user enters the wrong type, an error occurs and the program aborts
  • When you combine different scanner methods, you sometimes have to include an extra call to nextLine() to get rid of a newline

Some Commonly Used Methods of a Scanner Object

Method Description
next() Returns the next token as a String object.
nextLine() Returns the rest of the current line as a String object and positions the input cursor at the beginning of the next line.
nextDouble() Returns the next token as an double value.
nextInt() Returns the next token as an int value.

Example Program Using Scanner for Processing User Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;

public class InputApp {
    public static void main(String[] args) {
        String name;
        int age;
        double weight;
        Scanner input  = new Scanner(System.in);

        System.out.print("Enter your name: ");
        name = input.next();
        System.out.print("Enter your age: ");
        age = input.nextInt();
        System.out.print("Enter your weight: ");
        weight = input.nextDouble();

        System.out.println("\nYou entered:");
        System.out.println("Name:" + name);
        System.out.println("Age:" + age);
        System.out.println("Weight:" + weight);
    }
}

Scanner Pitfall: Working with Newlines

  • Notice the difference between method nextLine() and the other input methods
  • Method nextLine() positions the input cursor at the beginning of the next line, but the other methods do not
  • Instead, these methods remove whitespace and then read a token
  • Also, these methods stop as soon as they encounter whitespace after starting to read the token
  • Thus, you use nextLine() if you want to allow spaces in the input
    System.out.print("Enter your name: ");
    String name = input.nextLine();
    
  • Method nextLine() reads the remainder of a line of text, starting wherever the last read left off, including the '\n' at the end of the line
  • Note that you may need to code an "extra" nextLine() to clear a '\n' left by next(), nextInt() or nextDouble()

Other Input Methods

  • The Scanner class was introduced in Java version 5.0 (JDK 1.5)
  • For console input without the Scanner class, see: Using System.in

2.2.5: Summary

  • To make it easier to write programs, Java has many libraries of prewritten code
  • You can make use of this code by importing packages:
    import packagename.ClassName;
        or
    import packagename.*;
    
  • For example, to import all the java.util libraries:
    import java.util.*;
  • Alternatively, you can use the fully qualified package name:
    import java.util.Scanner;
  • To create an object for a class, you:
    1. Define a variable to store the object
    2. Create the object using the new operator and assign it to the variable
  • You can combine both steps into one statement, like:
    Scanner input = new Scanner(System.in);
  • One you create an object, you can call its methods
  • To call a method, you use the object name, a dot (period), the method name and a set of parenthesis
  • For example:
    input.nextInt();
  • You can use the System.out object to print to the console
    • System.out.print() leaves the cursor positioned after the last character
    • System.out.println() positions the cursor on a new line
  • You can use a Scanner object to read data from the console
  • To use Scanner, you need to need to import the java.util.Scanner class
  • You then create a Scanner object like:
    Scanner input = new Scanner(System.in);
  • Each group of characters that a user enters is called a token
  • To read each token, you call a method of a Scanner object like:
    int count = input.nextInt();

Check Yourself

  1. How do you include libraries in your Java programs?
  2. What library do you include to create Scanner objects?
  3. What does the acronym "API" stand for? What does it mean?
  4. How do you create an object?
  5. How do you call a method of an object?
  6. What is the code to create a Scanner object?
  7. What is the code to get an int value from the keyboard using a Scanner object?

Exercise 2.2

Take one minute to prepare an answer to the following problem.

Write a complete program to read a single int from the keyboard and display it to the console.

Wrap Up

Due Next:
A2-Metabolic Energy (2/24/10)

Home | Blackboard | Schedule | Room Policies | Syllabus
Help | FAQ's | HowTo's | Links
Last Updated: February 15 2010 @16:48:34