What We Will Cover
Illuminations
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?
^ top
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
|
^ top
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
^ top
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:
- Description of the code
- 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
^ top
2.1.3: Primitive Data Types
Integer data types: byte, short, int, long
Floating-point types: float, double
Character data type: char
Boolean type: boolean
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 |
^ top
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;
Note that you must declare and assign a value to a constant in one statement
^ top
2.1.5: Arithmetic Operators and Variables
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
- 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 |
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:
- Parentheses ( )
- Unary operations: +, -, ++, --
- Multiplication, division, modulus: *, /, %
- 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))
^ top
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
^ top
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 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);
^ top
2.1.8: Strings
Declaring and Assigning string Variables
Joining Strings (Concatenation)
String Conversions
^ top
2.1.9: Summary
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
- Parenthesis:
( )
- Unary operators:
+, -
- Multiplication, division, modulus:
*, /, %
- 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
- Where does every Java program start executing?
- What styles of comments does Java allow?
- What is the purpose of Javadoc comments?
- What is the purpose of a data type?
- What are the eight primitive data types that Java supports?
- What are the rules for creating an identifier?
- What is the code to declare an
int variable named foo and assign it a value of 10?
- What is the code to declare a constant
double named BIG_NUM and assign it a value of 100,000?
- What are the five operators Java uses for arithmetic?
- How do you calculate the square root of a number like
27?
- What is meant by the term casting? coercion?
- What data type is returned from an expression when an
int and a double are added together?
- What is wrong with the following code?
double x = 1;
int y = x;
- What type of delimiters are used to encapsulate literal strings?
- What is the code to declare a string variable named
foo?
- What operator is used to join two strings?
^ top
Exercise 2.1
Lets go through these one at a time. Take one minute to prepare an answer and then we will discuss it.
- Given the following code, which statement is true?
int a, b = 1;
- Variable
a is not declared
- Variable
b is not declared
- Variable
a is declared but not initialized
- Variable
b is declared but not initialized
- Neither variable is declared nor initialized
- What is the value returned by the following expressions?
- -1-3 * 10 / 5-1;
-8
-6
7
8
10
- 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?
result = n * ++m; //preincrement m
result = n * m++; //postincrement m
result = n * --m; //predecrement m
result = n * m--; //postdecrement m
- What does the following code do?
char ch7 = '7';
int num7 = ch7 - '0';
System.out.println("answer: " + num7 + 2);
- Error
- prints
72
- prints
9
^ top
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
|
^ top
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
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
^ top
2.2.2: Creating Objects and Calling Methods
Scanner input = new Scanner(System.in);
Calling Object Methods
^ top
2.2.3: Printing to a Console
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 |
^ top
2.2.4: Reading Interactive Input
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
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
^ top
2.2.5: Summary
import java.util.*;
Alternatively, you can use the fully qualified package name
import java.util.Scanner;
To create an object for a class, you:
- Define a variable to store the object
- 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
- How do you include libraries in your Java programs?
- What library do you include to create
Scanner objects?
- What does the acronym "API" stand for? What does it mean?
- How do you create an object?
- How do you call a method of an object?
- What is the code to create a
Scanner object?
- What is the code to get an
int value from the keyboard using a Scanner object?
^ top
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.
^ top
Wrap Up
Due Next: A2-Metabolic Energy (2/25/09)
^ top
Home
| Blackboard
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: March 29 2009 @18:00:18
|