Download CMPS 322 Intro Programming Notes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 1
Memory (page 5): Data is encoded as a series of bits (zeros and ones). Memory stores data and program
instructions for the CPU to execute. A memory unit is an ordered sequence of bytes each holding 8 bits.
If a computer needs to store a large number that cannot fit into a single byte, it uses several adjacent bytes. No two
data items can share or split the same byte. A byte is the minimum storage unit.
A program and its data must be brought to memory before they can be executed. A memory byte is never empty, but
its initial content may be meaningless to your program. The current content of a memory byte is lost whenever new
information is placed in it.
Every byte has a unique address. The address is used to locate the byte for storing and retrieving data. Since bytes
can be accessed in any order, the memory is also referred to as RAM – random access memory.
Programs (page 7): Computer programs, known as software, are instructions to the computer. Computers are told
what to do via programs. Without programs, a computer is an empty machine.
A computer speaks machine language which is a set of primitive instructions built into every computer. The
instructions are in the form of binary code, so binary codes must be entered for various instructions. Programming
this is tedious and is highly difficult to read and modify.
Assembly language is a low-level programming language in which a mnemonic is used to represent each of the
machine-language instructions. Assembly languages were developed to make programming easy. A computer
cannot understand assembly language, so a program called an assembler is used to convert assembly language
programs into machine codes.
High-level languages are English-like and easy to learn and program. There are over 100 high-level languages that
include:









COBOL (Common Business Oriented Language)
FORTRAN (Formula Translation)
BASIC (Beginner All-purpose Symbolic Instructional Code)
Pascal (named for Blaise Pascal)
C (whose developer designed B first)
Visual Basic
C++ (an object-oriented language based on C)
C# (a Java-like language developed by Microsoft)
Java
A program written in high-level language is called a source program. Since a computer cannot understand a source
program, a program called a compiler is used to translate the source program into machine language program. The
machine language program is often then linked with other supporting library code to form an executable file. The
executable file can be executed on the machine.
A source program can be ported/moved to any machine with appropriate compilers. The source program must be
recompiled, however, because the machine language program can only run on a specific machine. Java was
designed to run on any platform. With Java, you write the program once and compile the source program into a
special type of machine language code known as bytecode. The bytecode can then run on any computer with a
Java Virtual Machine (JVM). The Java Virtual Machine is software that interprets the Java bytecode. Java
bytecode can run on a variety of hardware platforms and operating systems
Java bytecode is interpreted. The difference between compiling and interpreting is as follows: Compiling
translates the high-level code into a target language code as a single unit. Interpreting translates the individual steps
in a high-level program one at a time rather than the whole program as a single unit. Each step is executed
immediately after it is translated.
Introduction to Java Programming
Summer Quarter I 2008
Page 1 of 30
Number Systems (page 11): Computers use binary numbers internally because storage devices like memory and
disk are made to store 0s and 1s. A number or character inside a computer is stored as a sequence of 0s and 1s.
Each 0 or 1 is called a bit. The binary number system has two digits, 0 and 1. Binary numbers are not intuitive.
When you write a number like 20 in a program, it is assumed to be a decimal number. Internally, computer software
is used to convert decimal number into binary numbers and vice versa. Binary numbers tend to be long and
cumbersome.
Hexadecimal numbers are often used to abbreviate binary numbers with each hexadecimal digit representing
exactly four binary digits. The hexadecimal number system has 16 digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F
A, B, C, D, E and F correspond to the decimal numbers 10, 11, 12, 13, 14 and 15 respectively.
The decimal number system has 10 digits, and the position values are integral powers of 10. We say that 10 is the
base or radix of the decimal number system. Similarly, the base of the binary number system is 2 since the binary
number system has two digits, and the base of the hex number system is 16 since the hex number system has 16
digits.
A table of conversions between binary numbers and hexadecimal numbers is on page 13.
Java, the World Wide Web and Beyond (page 14)
The World Wide Web is an electronic information repository that can be accessed on the Internet from anywhere in
the world. The Internet is the infrastructure of the Web.
Java was developed by a team led by James Gosling at Sun Microsystems. Originally called Oak, it was designed in
1991 for use in embedded consumer electronic appliances. It was renamed Java in 1995 and was redesigned for
developing Internet applications.
Java is a full-featured, general-purpose programming language that is capable of developing mission-critical
applications. It is not only used for Web programming, but also for developing standalone applications across
platforms on servers, desktops and mobile devices.
Java programs that run from a web browser are called applets. Applets use a modern graphical user interface with
buttons, text fields, text areas, radio buttons, etc., to interact with users and process their requests. Applets make the
Web responsive, interactive and fun to use.
Java can also be used to develop applications on the server side. These applications, called Java servlets or
JavaServer Pages (JSP) can be run from a web server to generate dynamic web pages.
The Java Language Specification, API, JDK and IDE (page 16)
The Java language specification is a technical definition of the language that includes the syntax and semantics of
the Java programming language.
The application program interface (API) contains predefined classes and interfaces for developing Java programs.
There are three editions of the Java API:
1.
2.
3.
Java 2 Standard Edition (J2SE) (can be used to develop client-side standalone applications or applets)
Java 2 Enterprise Edition (J2EE) (can be used to develop server-side application such as Java servlets and
JavaServer Pages)
Java 2 Micro Edition (J2ME) (can be used to develop applications for mobile devices)
J2SE is used to introduce Java programming. There are many versions of J2SE the latest being 5.0. Sun releases
each version of J2SE with a Java Development Toolkit (JDK). For J2SE 5.0, the Java Development Toolkit is
called JDK 5.0. JDK consists of a set of separate programs for developing and testing Java programs, each of which
is invoked by a command line.
Introduction to Java Programming
Summer Quarter I 2008
Page 2 of 30
Three major development tools are:
1.
2.
3.
Jbuilder by Borland (www.borland.com)
NetBeans Open Source by Sun (www.netbeans.org)
Eclipse Open Source by IBM (www.eclipse.org)
A Java development tool is software that provides an integrated development environment (IDE) for rapidly
developing Java programs. Editing, compiling, building, debugging, and online help are integrated into one graphical
user interface.
A Simple Java Program (page 17)
A Java program can be written in many ways:



Applications are standalone executable programs on any computer with a JVM
Applets are special kinds of Java programs that run from web browser
Servlets are special kinds of Java programs that run from a web server to generate dynamic web content
Every Java program must have at least one class. A class is a construct that defines data and methods. Each
class has a name. Class names start with an uppercase letter. Every Java program begins with a class declaration
in which the keyword Class is followed by the class name. For example
public class ComputeArea {
// Some code here
}
In order to run a class, the class must contain a method named main. The JVM executes the program by
invoking the main method.
A method is a construct that contains statements. The main method in the program on page 17 contains the
System.out.printIn statement. This statement prints a message “Welcome to Java!” to the console. ln places a line
break after the statement.
Creating, Compiling and Executing a Java Program (page 18)
The Java programming development process consists of creating/modifying source code, compiling and executing
programs. Like other programming languages, it is subject to syntax errors.
Java source files must end with the extension .java and must have the exact same name as the public class
name. In the example on page 18, the public class name is Welcome, so the source file should be named
Welcome.java.
A Java compiler translates a Java source file into a Java bytecode file. The following command compiles a Java
source file: javac [source filename].java
If there are no syntax errors, the compiler generates a bytecode file with a .class extension. To execute a Java
program is to run the program’s bytecode. The following command runs the bytecode: javac [source filename]
Do not use the extension .class in the command line when executing the program. The JVM assumes that the first
argument in the command is the filename and then fetches filename.class to execute. It would attempt to fetch
filename.class.class if you used java filename.class in the command line. In short, .class is assumed.
When executing a Java program, the JVM first loads the bytecode of the class to memory using a program called the
class loader. If your program uses other classes, the class loader dynamically loads them just before they are
needed. After a class is loaded, the JVM uses a program called bytecode verifier to check the validity of the
bytecode and ensure the bytecode does not violate Java’s security restrictions. Java enforces strict security to make
sure that Java programs arriving from the network do not harm your PC.
Introduction to Java Programming
Summer Quarter I 2008
Page 3 of 30
Anatomy of a Java Program (page 20)
A Java application program is comprised of the following components:
Comments:
Document what the program is and how the program is constructed. Comments help
programmers to communicate and understand the program.
Reserved Words:
A.K.A. keywords, are words that have specific meaning to the compiler and cannot be used for
other purposes in the program. When the compiler sees the word class, it understands that the
word after class is the name for the class.
Modifiers:
These specify the properties of the data, methods, and classes and how they can be used.
Examples of modifiers are public and private.
Statements:
Statements represent an action or a sequence of actions. The statement
System.out.println(“Welcome to Java”); is a statement to display the greeting “Welcome to
Java!” EVERY statement ends with a semicolon.
Blocks:
The braces{ } in the program form a block that groups the components of the program. Each
Java program begins and ends with a brace. Nested classes and methods also have open and
closing braces.
Classes:
The class is the essential Java construct. A program is defined by using one or more classes.
Methods:
System.out is known as the standard output object. println is a method in the object which
consists of a collection of statements that perform a sequence of operations to display a
message to the standard output device
main Method:
Every Java application must have a user-declared main method that defines where the program
execution begins. The JVM executes the application by invoking the main method. The main
method is as follows:
public static void main(String[ ] args) {
//Statements
}
Introduction to Java Programming
Summer Quarter I 2008
Page 4 of 30
Class Lecture – May 10, 2008 – Week 1
What are Java Programs?

A Java program is made up of class definitions.

A class definition contains a header and a body.

The body contains methods and properties/attributes.

A method is a named section of code that can be called by its name (i.e., a function).

A property is a variable defined within the class.

Java programs come in a variety of application formats and contexts:
– Java applications (what we will focus on).
– Java applets (run on web pages).
– Beans (components).
– Enterprise Java (back end server applications).
What are the states or stages of Java Programs?

A Java program starts with source code.

The Java program is compiled into bytecode.

The Java program is executed within the Java runtime environment.
– Bytecode is interpreted by JRE.
– This is different than a C++ EXE.
– Enables the Java platform independence.
Java Applications and Applets

Java Applications
– A Stand-alone program.
– Runs independently at command line (under JRE).
– Has a main() method that is starting point of application.
– No HTML file.

Java Applets
– Embedded program.
– Runs in a Web browser.
– No main() method.
– Requires an HTML file.
– Run using JDK’s appletviewer or via web browser.
Java Class Libraries

To make use of any of the libraries, you must use an import statement.
– The exception here is java.lang, which is automatically included in all programs.
– Difference between these two statements is that first imports all class definitions of java.util, while second
imports just JApplet.
import java.util.*;
import javax.swing.JApplet;
Java Language Fundamentals

Java IS case sensitive.

Statements normally end with a semi-colon.

Statements can be grouped into blocks with braces {}.

Statements are free format -- spaces can be freely used and code can be broken up into multiple lines.

Indentation is commonly used to improve code readability.
Introduction to Java Programming
Summer Quarter I 2008
Page 5 of 30
Class Lecture – May 10, 2008 – Week 1 (Continued)
Java Data Types

Your programs will need to store and use data.


In programming, we must map the data types available in the language to the problem domain.
–
With OOP, we can create our own data types that map more directly to the problem domain.
–
However, we must eventually work with the types available in the language.
There are two general categories of data in a computer program:
–
–
–




Numeric.

Whole numbers (integers).

Decimal numbers (floating point).
Non-numeric.

Strings of characters.

Single characters.

Boolean (true/false).
These are the intrinsic data types of the language.
Your programs will also eventually use classes.
Text reference begins at Page 34.
Four integer types available:
– byte
– short
– int
– long
See Table 2.1 for value ranges for these types and for the memory requirements.
Declaring Variables

Variables are storage locations in memory that you can refer to by a name that has meaning to you for the
context of the application.

Variables are declared by selecting data type and variable name:
int myintvalue, j, k3;
double salary = 10000.0;



Variables are NOT initialized automatically.
Use of a variable before initialization is illegal in Java.
May be initialized at time of declaration, or via assignment statement
Arithmetic Expressions

Most programs will need to support numeric calculations.

This is accomplished via statements that combine variables with the arithmetic operators.
–

These operators are the binary operators.
–

They require left and right operands.
There are also a number of unary operators, notably:
–

+, -, *, /, %.
++, --, +=, -=, *=, /=.
The complete set of Java operator’s precedence is shown on Page 86.
Introduction to Java Programming
Summer Quarter I 2008
Page 6 of 30
Class Lecture – May 10, 2008 – Week 1 (Continued)
Type Casting

Java sometimes allows mixed arithmetic expressions and sometimes it doesn’t.

When it doesn’t, we can usually convince it to do so by type casting.

Type casting involves stating what your target data type is.

Syntax is to place target data type within parentheses, in front of data to be converted:
int j;
j = (int) 3.24;
mycode.java
Compile yields .class (bytecode)
javac mycode.java
To run
java mycode
'A' ==> single byte character
"A" ==> String literal object
Both of above are literal constants.
Our two sweet spot data types for numbers:
int
double
Remainder/modulus
20 % 5 ==> 0
21 % 5
==> 1
int b = 10;
int c = 2;
int d = 5;
int a = b + c * d;
|
|
10
|
|
20
Operator precendence: For example, multiplication trumps addition. Parentheses change the rules of operator
precedence. Items in parentheses are evaluated first.
int a = (b + c)*d;
int temp;
temp = b + c;
int a = temp * d;
These statements all add 1 on to a:
a++; ==> post increment
++a; ==> pre increment
a += 1;
a = a + 1;
double x = 3.14;
double y = x + 10;
int z = x + 10;
==> OK, automatic conversion
==> illegal
int z = (int) (x + 10);
int z = (int) x + 10;
==> explicit type cast
Introduction to Java Programming
Summer Quarter I 2008
Page 7 of 30
Class Lecture – May 10, 2008 – Week 1 (Continued)
JavaDoc is Java Documentation for programmers. The following is an example of JavaDoc:
/**
* @param args the command line arguments
*/
Single quote is used for a single character: ‘A’  single byte character
Double quote is used for a string:
“A”  String object
Both of the above are literal constants. Literal constants can be any intrinsic data type
Introduction to Java Programming
Summer Quarter I 2008
Page 8 of 30
Chapter 2
Algorithm (page 28): Describes how a problem is solved in terms of the actions to be executed, and it specifies the
order in which the actions should be executed. Algorithms help the programmer plan a program before writing it in a
programming language. An algorithm is as follows:
1) Read the radius.
2) Compute the area using the following formula:
3) Display the area
area = radius X radius X pi
Data Structures (page 28): These involve data representation and manipulation. Java provides data types for
representing:




Integers
Floating-point numbers (numbers with a decimal point)
Characters
Boolean
These data types are known as primitive data types.
Variables (page 29): Variables are used to store data and computational results in a program.
public class ComputeArea {
public static void main(String[] args){
double radius; (radius is a variable)
double area; (area is a variable)
// Some code here
}
}
Double is a reserved word that indicates that radius and area are double-precision floating-point values stored in
the computer
The variables radius and area correspond to memory locations. Every variable has a name, type, size and value.
double radius declares that the variable radius can store a double value. The value is not defined until you
assign a value.
The plus sign (+) (page 30) has two meanings: one for addition and the other for concatenating strings. The plus
sign is called a string concatenation operator. The string concatenation operator connects two strings if two
operands are strings. If one of the operands is a non-string (e.g., a number) the non-string value is converted into a
string and concatenated with the other string. The following is a concatenated string:
System.out.println(“The area for the circle of radius “ +
radius + “is” + area);
A string constant CANNOT cross lines in the source code. The following statement would result in a compilation
error:
System.out.println(“Introduction to Java Programming,
by Y. Daniel Liang”);
To fix the error, break the string into substrings and use the concatenation operator (+) to combine them:
System.out.println(“Introduction to Java Proramming, “ +
“by Y. Daniel Liang”);
Introduction to Java Programming
Summer Quarter I 2008
Page 9 of 30
Identifiers (page 30): Identifiers are special symbols used to name such programming entities as variables,
constans, methods, classes and packages. Rules for naming identifiers is as follows:





An identifier is a sequence of characters that consist of letters, digits, underscores and dollar signs.
An identifier MUST start with a letter, underscore or dollar sign. It CANNOT start with a digit.
An identifier CANNOT be a reserved word.
An identifier CANNOT be true, false or null
An identifier CAN be of any length
$2, ComputeArea, area, radius and showMessagedialog are LEGAL identifiers whereas 2A and d+4 are ILLEGAL
identifiers.
Declaring Variables (page 31): To use a variable, you declare it by telling the compiler the variable’s name as well
as the data type it represents. This is called variable declaration. Declaring a variable tells the compiler to allocate
appropriate memory space for the variable based on its data type. Examples of variable declaration are as follows:
int x ;
double radius;
double interestRate;
char a;
//Declare
//Declare
//Declare
//Declare
x to be an integer variable
radius to be a double variable
interestRate to be a double variable
a to be a character variable
Variables of the same type can be declared together as follows:
int i, j, k;
Variable names are typically lowercase. Multiple worded variables are to start with a capital letter except for the first
word in the variable, e.g., interestRate.
Assignment Statements and Assignment Expressions (page 32): After a variable is declared, a value can be
assigned to is by using an assignment statement. In Java, the equal sign (=) is used as the assignment operator.
The syntax for an assignment statement is as follows:
variable = expression
An expression represents a computation involving values, variables and operators that together evaluates to a
value. For example:
int x = 1;
double radius = 1.0
x = 5 * (3 / 2) + 3 * 2;
x = y + 1;
area = radius * radius * 3.14159
//Assign 1 to variable x
//Assign 1.0 to variable radius
//Assign the value of the expression to x
//Assign the addition of y and 1 to x
//Compute area
An assignment statement an also be treated as an expression that evaluates to the value being assigned to the
variable on the left side of the assignment operator. For this reason, represents a computation involving values,
variables and operators that together evaluates to a value. For example:
System.out.println(x = 1);
which is equivalent to
X = 1
System.out.println(x);
Introduction to Java Programming
Summer Quarter I 2008
Page 10 of 30
This statement is also correct:
i = j = k = l;
which is equivalent to:
k = l;
j = k;
I = j;
Declaring and Initializng Variables in One Step (page 33): Variables often have initial values. However, the
declaration and initialization can be declared in one step. For example:
int x = l;
is equivalent to:
int x;
x = 1;
Declaration and initialization of same variable types can be done together:
int i = l, j = 2;
A variable must be declared before it can be assigned a value. A variable declared in a method must be assigned a
value before it can be used. Declare a variable and assign its initial value in one step whenever possible.
Constants (page 33): A constant represents permanent data that NEVER changes. For example, pi is a constant.
The syntax for declaring a constant is as follows:
final datatype CONSTANTNAME = VALUE;
A constant must be declared and initialized in the same statement. final is a Java keyword which mean that
the constant cannot be changed.
The benefits of using constants is that you do not have to repeatedly type the same value, the value can be changed
in a single location if necessary, and a descriptive name for a constant makes the program easier to read.
Numeric Data Types and Operations (page 34): Every data type has a range of values. The compiler allocates
memory space to store each variable or constant to its data type. Java provides eight primitive data types for
numeric values, characters and Boolean values. Numeric data types, their range and storage sizes are in table 2.1
on page 34.
Java’s four data types used for integers are byte, short, int and long.
Java’s two data types used floating-point numbers are float and double. Double is known as double precision
because it is as twice as big as float. Float is known as single precision. The double type should be used because it
is more accurate than the float type.
Java’s remaining two data types are char and Boolean.
Introduction to Java Programming
Summer Quarter I 2008
Page 11 of 30
Numeric Operators (page 35): A table of operators for numeric data is on page 35. The result of integer
division is an integer. The fractional part is truncated. For example, 5/2 yields 2, not 2.5
The % operator yields the remainder AFTER division. The left operand is the dividend, and the right operand is the
divisor. Therefore, 7 % 3 yelds 1, 12 % 4 yields 0, 26 % 8 yields 2 and 20 % 13 yields 7.
The % operator is often used for positive integers but also can be used with negative integers and floating-point
values. The remainder is negative only if the dividend is negative. Remainder is very useful in programming. For
example, an even number %2 is always 0, and an odd number %2 is always 1. So, this property can be used to
determine whether a number is even or odd.
Numeric Literals (page 36): A literal is a constant value that appears directly in a program. For example, 34,
1000000 and 5.0 are literals in the following statements:
int i = 34
long k = 1000000;
double d = 5.0
An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error
would occur if the literal were too large for the variable to hold. The statement byte b = 128 would cause a
compilation error because 128 cannot be stored in a variable of the byte type (byte value is from -128 to 127).
An integer literal is assumed to be of the int type whose value is between -231 (-2147483648) and 231 -1
(2147483648). The statement System.out.println(2147483648) would cause a compilation error because
2147483648 is too long as an int value.
To denote an integer literal of the long type, append the letter L to it (2147483648L) and use the capital L because
the lowercase l could be confused for the number one. Since 2147483648 exceeted the range for the int type, it
must be denoted as 2147483648L.
Floating-Point Literals (page 37): Floating-point literals are written with a decimal point. By default, a floating-point
literal is treated as a double type value. For example, 5.0 is considered a double value not a float value. The
number can be made a float value by appending the letter f or F, and you can make a number a double by appending
the letter d or D. For example, you can use 100.2f or 100.2F for a float number and 100.2d or 100.2D for a double
number.
Arithmetic Expressions (page 37): The numeric operators in a Java expression are applied the same way as in an
arithmetic expression. Operators contained within pairs of parentheses are evaluated first. Parentheses can be
nested in which case the expression in the inner parenthses is evaluated first. Multiplication, division, and remainder
operators are applied next. If an expression contains several multiplication, division and remainder operators, they
are applied from left to right. Addition and subtraction operators are applied last. If an expression contains several
addition and subtraction operators, they are applied from left to right.
Shorthand Operators (page 38): Java allows you to combine assignment and addition operators using a shorthand
operator. Consider the following:
i = i + 8
is equivalent to:
i += 8
The += is called the addition assignment operator. Other shorthand operators are shown in table 2.3 on page
38.
Introduction to Java Programming
Summer Quarter I 2008
Page 12 of 30
Increment and Decrement Operators (page 39): There are also shorthand operators for incrementing and
decrementing a variable by 1. These two operators are ++ and --. They can be used in prefix or suffix notation.
Refer to table on page 39 for these operators and their descriptions.
If the operator is before (prefixed) the variable, the variable is incremented or decremented by 1, then the new value
of the variable is returned. If the operator is after (suffixed) to the variable, the old original variable is returned, then
the variable is incremented or decremented by 1. As a result, the prefixes:
++x are referred to as a preincrement operators
--x are referred to as a predecrement operator
The suffixes:
x++ are referred to as a postincrement operators
x-- are referred to as a postdecrement operators
The prefix and suffix forms are the same if they are used in isolation, but they cause different effects when used in an
expression.
Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to
read. Avoid using these operators in expressions that modify multiple variables or the same variable multiples times
such as int k = ++i + i
Numeric Type Conversions (page 39): Java automatically coverts the operand based on the following rules:




If one of the operands is a double, the other is converted into double
Otherwise, if one is a float, the other is converted into a float
Otherwise, if one is a long, the other is converted into long
Otherwise, both are converted into int.
The range of numeric types increases in this order:
byte  short  int  long  float  double
You can always assign a value to a numeric variable whose type supports a larger range of values, e.g., long can
always be assigned to float. However, you cannot assign a value to a variable of a type with smaller range unless
type casting is used. Casting is an operation that converts a value of one data type into a value of another
data type. Casting a variable of a type with a small range to a variable of a type with a larger range is known as
widening a type. Casting a variable of a type with a larger range to a variable of a type with a smaller range is known
as narrowing a type. Widening CAN be performed WITHOUT explicit casting. Narrowing MUST be performed
explicitly.
Character Data Type and Operations (page 40): the character data type, char, is used to represent a single
character. A character literal is enclosed in single quotation marks:
char letter = ‘A’;
char numChar = ‘4’;
//Assigns character A to the char variable letter
//Assigns digit character 4 to the char variable numChar
A string literal must be enclosed in quotation marks, so “A” is a string
A character literal is a single character enclosed in single quotes, so ‘A’ is a character
Information about Unicode and ASCII Code is on page 42.
Escape Sequence for Special Characters (page 43): Special characters include backspace, tab and linefeed.
Table 2.5 on page 43 illustrates these characters.
Introduction to Java Programming
Summer Quarter I 2008
Page 13 of 30
Casting Between char and Numeric Types (page 43): A char can be cast into any numeric type and vice versa.
Refer to the book for additional information and explanation.
All numeric operators can be applied to char operands. The char operand is automatically cast into a number if the
other operand is anumber or a character. If the other operand is a string, the character is concatenated with the
string.
The String Type (page 44): String represents a string of characters. The following code declares the message to
be a string whose initial value is “Welcome to Java”.
String message = “Welcome to Java”;
String is a predefined class in the Java library just like System and JOptionPane class. The String type IS NOT a
primitive type. Is is known as a reference type. Any Java class can be used as a reference type for a variable.
Two strings can be concatenated. The concatenation operator (+) comes into play if one of the operands is a string.
If one of the operands is a non-string (e.g., a number) the non-string value is converted into a string and
concatenated with the other string. See page 44 for examples.
If neither operands is a string, the plus sign the becomes the addition operator.
The short += operator can also be used for string concatenation:
message += “ and Java is fun”;
Converting Strings to Numbers (page 46): The input returned from the input dialog box is a string. If a numeric
value such as 123 is entered, it returned “123”. This string must be converted into a number to obtain the input as a
number.
To convert a string into an int value, the parseInt method in the Integer class is used:
int intValue = Integer.parseInt(intString);
To convert a string into a double value, the parseDouble method in the Double class is used:
double doubleValue = Double.parseDouble(doubleString);
Getting Input from the Console (page 52): Java uses System.out to refer to the standard output device, and
System.in to the standard input device. By default, the output device is the console and the input device is the
keyboard. To perform console output, the println method is used to display a primitive value or string to the console.
Console input is not directly supported in Java, bu the Scanner class can be used to create an object to read input
from System.in as follows:
Scanner scanner = new Scanner (System.in);
The syntax new Scanner (System.in) creates an object of the Scanner type. The syntax Scanner scanner
declares that scanner is a variable whose type is Scanner. The entire line of Scanner scanner = new Scanner
(System.in); creates a Scanner object and assigns its reference to the variable scanner. An object may contain
methods. Invoking a method on an object is to ask the object to perform a task.
Introduction to Java Programming
Summer Quarter I 2008
Page 14 of 30
A Scanner object contains the following methods for reading an input:







next():
nextByte():
nextShort():
nextInt():
nextLong():
nextFloat():
nextDouble():
reading a string. A string is delimited by spaces
reading an integer of the byte type
reading an integer of the short type
reading an integer of the int type
reading an integer of the long type
reading anumber of the float type
reading a number of the double tpye
Note: The print method is identical to the println method except that println moves the cursor to the next line
AFTER displaying the string. print DOES NOT advance the cursor to the next line when completed.
Refer to the text on pages 55 through 58 for the following:







Programming style and documentation
Appropriate comments and comment style
Naming conventions
Proper indentation and spacing
Block styles
Programming errors which include:
o Syntax errors
o Runtime errors
o Logic errors
Debugging
Introduction to Java Programming
Summer Quarter I 2008
Page 15 of 30
Class Lecture – May 17, 2008 – Week 2
Java Data Types Variables: Java variables fall into two categories:
1) Intrinsic data types:

byte, short, int, long

char

double, float

boolean
Intrinsic types are declared in this manner:
int myvar1;
double total = 0.0;
The second category of Java variables are known as reference variables. Reference variables are typically known
as objects.




The data types of reference variables a Java classes.
Variables to store string data are reference variables.
When we declare them, they actually aren’t ready to use yet.
We must initialize them by tying them to an instance of the class
String myname; // This is an unintialized variable.
myname = new String(“Fred Flintstone”);
String yourname = new String();
//
An empty string.
Declaring Variables

Variables are not initialized automatically.

Use of a variable before initialization is illegal in Java.

May be initialized at time of declaration, or via assignment statement
Java Variable Names: Variable names or identifiers:

Can contain letters, digits, underscores and dollar signs.

Must start with letter, underscore or dollar sign. (Not a digit.)

Cannot be a reserved word.

See Appendix A of text for list of reserved words.

Cannot be true, false or null.

Have no limit to length.
int myvar1;
double total = 0.0;
String _StudentNameValue;
int ___placemarker;
Arithmetic Expressions

Most programs will need to support numeric calculations.

This is accomplished via statements that combine variables with the arithmetic operators.
+, -, *, /, %.

These operators are the binary operators.
They require left and right operands.

There are also a number of unary operators, notably:
++, --, +=, -=, *=, /=.

The complete set of Java operators, and their precedence, is shown on Page 86.
Introduction to Java Programming
Summer Quarter I 2008
Page 16 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
Type Casting

Type casting involves stating what your target data type is.

Syntax is to place target data type within parentheses, in front of data to be converted.
int j;
j = (int) 3.24;
Formatting Numbers

Unless you request it, numeric output is raw and often ugly.

Formatting numbers in Java is not hard, but it is not intuitive.

Must make use of the NumberFormat object.

We create a variable that acts as the formatting tool.

When we want to display the number formatted, as ask the tool to do its job.
NumberFormat numberformat =
NumberFormat.getInstance(Locale.US);
System.out.print(numberformat.format(dblFarenheit));
Must import the java.util.NumberFormat package, or java.util.*.
There are different types of formatting instances available to you. Each customized to different types of numbers.
form
form
form
form
=
=
=
=
NumberFormat.getInstance();
NumberFormat.getIntegerInstance();
NumberFormat.getCurrencyInstance();
NumberFormat.getPercentInstance();
NumberFormat also supports several methods to control such things as number of decimal places.
form.setMaximumFractionDigits(2);
form.setMinimumFractionDigits(2);
See the Java Online documentation for full information.
See the solutions to last weeks in-class work on Blackboard.
Getting User Input
Unfortunately, not as easy as it should be in Java. Two choices:
1) Use a Scanner object (newer technique). Easier but cranky
2) Use an InputStream object (older technique). Bulletproof but harder to use.
Input Via Scanner

Must import the java.util.Scanner package, or java.util.*.

See Section 2.13 of text for discussion on use (page 52)

To actually get input, must use of the “next” methods.

Text does not list nextLine(), but it is another string input method
Scanner scanner = new Scanner(System.in); (System.in is tied to keyboard)
System.out.print("Enter an integer value: ");
int intval = scanner.nextInt();
Input entered by user is referred to as tokens: 34 543 22 44 (there are four tokens in this example). Tokens indicate
how you want numbers to be displayed. Input broken up by spaces, commas, etc. Whatever you set up. However,
you have to allow for character strings.
Introduction to Java Programming
Summer Quarter I 2008
Page 17 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
Scanner Secret
next() method only gets first chunk of a string if it has spaces.

Must use nextLine() if you want a whole line of input that includes spaces.

But nextLine() will be fooled by any previous input of numeric values.

This is because nextInt(), nextDouble() leave the enter key character(s) in the keyboard buffer.

To successfully use the Scanner to get strings from the keyboard, clear it before asking for input only if you
have previous input.
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // This clears things out first.
System.out.print("Enter your full name: ");
String fullname = scanner.nextLine(); (brings in value and converts to integer)
next.Line reads data input including and up to carriage return.
The Input Stream Approach
This is the original way that Java console input was conducted. It requires several things to be done with your code
to get it set up properly.
Step 1: Indicate that your main() method throws an IOException.
public static void main(String args[])
throws IOException
Step 2: Create a BufferedReader object. Means input is going to be gathered and placed into a buffer/holding area.
InputStreamReader is based upon an input stream.
// Set up input channel.
BufferedReader in =
new BufferedReader(new
InputStreamReader(System.in));
Step 3: Read in a line of input. All input that comes in is a character string.
String input;
System.out.print("Enter adjusted gross income: ");
input = in.readLine();
Step 4: Converting to your target data type. All intrinsic data types have a partner reference type (class) that
supports parsing of values from a string. This is very similar to what you did in HTML class with JavaScript.
income = Double.parseDouble(input);
Introduction to Java Programming
Summer Quarter I 2008
Page 18 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
Full Code:
public static void main(String args[])
throws IOException
{
// Set up input channel.
BufferedReader in =
new BufferedReader(new
InputStreamReader(System.in));
// Declare support variables.
double income,taxdue;
String input;
System.out.print("Enter adjusted gross income: ");
input = in.readLine();
income = Double.parseDouble(input);
To run your code in cmd.exe, enter java – jar and the path of the program enclosed in quotes:
java – jar “C:\Folder\etc.
This can be obtained by selecting Build > Build Main Project
Relational Operators:
==
Equal to
!=
Not equal to
<
Less than
>
Greater than
<=
Less than or equal
>=
Greater than or equal
These are complemented by the compound operators:
&&
And
||
Or (will not be used in this class)
Defined on Page 68.
If Statements

Refer to Chapter 3 in text.

Used to code decision making statements in programs.

Result of an if test is true or false.

Syntax requires use of parentheses.
if (g > 2)
g = 14;
General Syntax
IF statement only ever works on the statement immediately following it. Every ELSE statement MUST be paired to
an IF statement.
if ()
{
}
else if()
{
}
else
{
}
Introduction to Java Programming
Summer Quarter I 2008
Page 19 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
IF Blocks
When more than one statement is to be executed (if the logical test is true), braces are used to form a block:
if (a >= b)
{
a = 3*b;
i = i + 1;
}
The Else Clause
Many times it is necessary to take actions both when a condition is true or if it is false. The else clause allows
expansion of the if to accommodate this situation.

When more than one statement is to be executed (if the logical test is true), braces are used to form a block:
if (a < b + 10)
{
System.out.println(“Curing too rapidly.”);
}
else
{
iter = iter + 1;
}
Else IF Extension
Multiple tests can be constructed through use of else if. The order in which these statements are placed IS important.
Compiler is procedural/sequential in nature.
if (g +
g
else if
g
else if
g
else
g
1 != a*b)
= g + 1;
(a < 10)
= 2*g;
(a*b > 350)
= g*g;
= 0;
Nested IF Statements
Nested IF statements are placed within other IF statements
if (g + 1 != a*b)
{
g = g + 1;
{if (a < 10)
g = 2*g;}
{else if (a*b > 350)
g = g*g;}
{else
g = 0};
}
Introduction to Java Programming
Summer Quarter I 2008
Page 20 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
Be wary of how you structure nested ifs. An else always belongs to the nearest preceding if that’s not already
associated with another else. What does the following code do?
int g
int a
if (g
{
if
= 3;
= 0;
!= 3)
(a < 10)
System.out.println(“a < 10”);
}
else
System.out.println(“a not < 10”);
Compound IF Statements
Simple relational expressions can be joined into more complex expressions via the compound operators.
&&
||
Logical AND (both must be true)
Logical OR (either one can be true)
These operators have a precedence - and takes precedence over or.
if (a < 10 && b == 3)
System.out.printf(“%d %d\n”,a,b);
if (a > b && c == d || g < 10)
First: c == d || g < 10
Next: a > b && result of above
Alternative to compound:
if ( a > b)
{
If (c ++ d)
{
//Do something.
}
}
else if (g < 10)
{
// Do the same something.
}
System.out.printf("\n\n\n");
\ == The escape character.
==> Three CR LF pairs.
\n == newline
\t == tab
\0 == null character
System.out.println("Today is Saturday\nTommorrow is Sunday");
or
System.out.println("Today is Saturday");
System.out.println("Tommorrow is Sunday");
Introduction to Java Programming
Summer Quarter I 2008
Page 21 of 30
Class Lecture – May 17, 2008 – Week 2 (Continued)
Switch Statements
Switch statements are like if statements in many ways. Limited to integer values or values that can be closely related
to an integer:

They clean up the syntax a little bit.

Similar to case statements of other languages.

Means to compare an integer value against a list of cases.

Refer to Page 81 of text.

The break statement needed to prevent fall through execution
General syntax:
switch (expression)
{
case constant1: statement sequence
case constant2: statement sequence
.
.
default: statement sequence
}
Specific Example:
switch (a)
{
case 1 : System.out.println(“a = 1”);
break; (purpose is to break out of the flow of a block of code)
case 2 : System.out.println(“a = 2”);
break;
default : System.out.println(“a is not 1 or 2”);
}
Formatting Output

This is alternative to using NumberFormat object.

The printf statement together with formatting codes can achieve a limited degree of output formatting.

See Tables 3.8 and 3.9 for available codes (pages 84 and 85).
System.out.printf(“The value is %d dollars”,dblDollar);
System.out.printf(“The value is %10.2f dollars”,
dblDollar);
(% output of floating point item w/width of at least 10 including decimal point and two digits after the point.)
System.out.printf(“%25s\n”,”Bob”);
Introduction to Java Programming
Summer Quarter I 2008
Page 22 of 30
Chapter 3
Boolean Data type and Operations (page 68): Selection statement use conditions. Conditions are Boolean
expressions.
boolean Data Type and Operations (page 68): Java provides six comparison operators – also known as relational
operators that can be used to compare two values. The result of the comparison is a Boolean value: true or
false.
Relational Operators:
==
Equal to
!=
Not equal to
<
Less than
>
Greater than
<=
Less than or equal
>=
Greater than or equal
A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare
Boolean variables. The domain of the boolean type consists of two literal values: true and false.
Boolean Operators, also known as logical operators operate on Boolean values to create a new Boolean value.
Boolean Operators
Operator
Name
!
not
&&
and
||
or
^
exclusive or
Function/Description
Negates true to false and false to true
The and (&&) of two Boolean operands is true if and only if BOTH operands are true.
The or (||) of two Boolean operands is true if at least ONE of the operands is true.
The exclusive or(^) of two Boolean operands is true if and only if the two operands
have DIFFERENT Boolean values.
if Statements (page 73): Java has several types of selection statements: simple if statements, if…else statements,
nested if statements, switch statements and conditional expressions.
A simple if statement executes and action if and only if the condition is true. The syntax for a simple if statement is
as follows (note, the booleanExpression is enclosed in parentheses for all fors of the if statement):
if (booleanExpression) {
statement(s);
}
If the booleanExpression evaluates to true, the staements in the block are executed.
CAUTION: Forgetting the braces when they are needed for grouping multiple statements is a common programming
error. If you modify the code by adding new statements in an if statement without braces, you will have to insert the
braces if they aren’t already in place.
if…else Statements (page 74): The actions than an if…else statement specifies differ based on whether the
condition is true or false. The syntax for a simple if…else statement is as follows:
if (booleanExpression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Introduction to Java Programming
Summer Quarter I 2008
Page 23 of 30
An if…else statement executes, if the booleanExpression evaluates to true, the statement(s) for the true case is
executed, otherwise, the statement(s) for the false case is executed.
Nested if Statements (page 76): An inner if statement is said to be nested inside the outer if statement. The inner
if statement can contain another if statement. There is no limited to the depth of the nesting. The following is an
example of a nested if statement.
if (score >= 90.0)
grade = 'A';
else if (score>=80.0)
grade = 'B';
else if (score >=70.0)
grade ='C';
else if (score >=60.0)
grade = 'D';
else
grade = 'F';
In this statement, if the first statement evaluates to true, the statement ends. If the first statement evaluates to false,
the second condition is evaluated. In short, a nested if statement evaluates down the line until a statement
evaluates to true.
To test whether a boolean variable is true or false in a test condition, it is redundant to use the equality comparison
operator. Instead, use the boolean variable directly. This assists in avoiding errors that are difficult to detect. Using
the = operator instead of the == operator to compare equality of two items ina test condition is a common error.
switch Statements (page 81): Java provides a switch statement to handle multiple conditions efficiently. Consider
the following code:
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married filed jointly;
break;
case 2: compute taxes for married filed separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
The switch statement checks all cases and executes the staetments in the matched case.
Introduction to Java Programming
Summer Quarter I 2008
Page 24 of 30
The switch statement observes the following rules:

The switch-expression must yield a value of char, byte, short or int type and MUST ALWAYS be
enclosed in parentheses.

When the value in a case statement matches the value of the switch-expression, the staetments, starting
from this case, are executed until either a break statement or the end of the switch statement is reached.

The keyword break is optional. The break statement immediately ends the switch statement.

The default case, which is optional, can be used to perform action when none of the specified cases
matches the switch-expression.

The case statements are checked in sequential order, but the order of the cases (including the default case)
DOES NOT matter. However, it is good programming style to follow the logical sequence of the cases and
place the default case at the end.

Do not forget to use a break statement when one is required. Once a case is matched, the statements
starting from the matched case are executed until a break statement or the end of the switch statement is
reached. This phenonmenon is referred to as fall-through behavior.
Formatting Console Output and Strings (page 84): A format specifier specifies how an item should be displayed.
An item may be a numeric value, a character, a boolean value or a string. Each specifier begins with a percent
sign.
Frequently Used Specifiers
Specifier
Output
%b
A boolean value
%c
A character
%d
A decimal integer
%f
A floating-point number
%e
A number in standard scientific notation
%s
A string
Example
true or false
'a'
200
45.460000
4.556000e+01
"Java is cool"
An example using specifiers is as follows:
int count = 5;
double amount = 45.56;
System.out.printf("count is %d and amount is %f, count, amount);
Display:
count is 5 and amount is 45.560000
d% equates to count variable and %f equates to amount variable.
Items must match the specifiers in order, in number and in exact type. For example, the specifier for count is
%d and for amount is %f. By default, a floating-point value is displayed with six digits after the decimal point.
The width and precision in a specifier can be defined. A table of examples of specifying width and precision is
on page 85.
Introduction to Java Programming
Summer Quarter I 2008
Page 25 of 30
Chapter 4
Loops (page 96): A loop is a control structure that controls how many times an operation or sequence of operations
is performed in succession. Loops are structures that control repeated executions of a block of statements.
Java provides three types of loop statements:
1) while loops
2) do-while loops
3) for loops
The while Loop (page 96): The syntax for the while loop is as follows:
while (loop-continuation-condition){
//Loop body
Statements;
}
Loop Body is the part of the loop that contains the statements to be repeated. Iteration of the Loop is how a onetime execution of the loop is referred.
Each loop contains a loop-continuation condition - a Boolean expression that controls the execution of the
body. It is ALWAYS evaluated BEFORE the loop body is executed. If its evaluation is true, the loop body is
executed. If its evaluation is false, the entire loop terminates, and the program control turns to the statements that
follows the while loop. Consider the following code that prints "Welcome to Java" 100 times.
int count = 0
while (count < 100) {
System.out.println("Welcome to Java!");
}
In short, the while loop repeatedly executes the statements in the loop body when the loop-continuation-condition
evaluates to true.
Notes:

The loop-continuation-condition MUST always appear inside the parentheses. The braces enclosing the loop
body can be omitted ONLY if the loop body contains one or no statements.

Make sure that the loop-continuation-condition eventually becomes false so that the program will terminate.
A common programming error involves infinite loops.
The do-while Loop (page 100): The syntax for the do-while loop is as follows:
do {
//Loop body
Statements;
} while (loop-continuation-condition);
The flow/order of a do-while loop is as follows:
1) The loop body is executed first
2) Then, the loop-continuation-condition is evaluated.
3) If the evaluation is true, the loop body is executed again. If it is false, the do-while loop terminated.
In short, the do-while loop executes the loop body first and then checks the loop-continuation-condition to
determine whether to continue or terminate the loop. The major difference between a while loop and a do-while
loop is the order in which the loop-continuation-condition is evaluated and the loop body executed.
Tip: Use the do-while loop if you have statements inside the loop that must be executed at least once.
Introduction to Java Programming
Summer Quarter I 2008
Page 26 of 30
The for Loop (page 102): The syntax for the for loop is as follows:
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
//Loop body
Statement(s);
}
A for loop performs an initial action once then repeatedly execute the statements in the loop body and performs an
action after an iteration when the loop-continuation-condition evaluates to true.
The for loop:
1. Starts with the keyword for.
2. Is followed by a pair of parentheses enclosing the initial-action, loop-continuation-condition, and actionafter-each-iteration (these items separated by semicolons)
3. Then followed by the loop body enclosed inside braces.
A for loop generally uses a control variable to control how many times the loop body is executed and when the loop
terminates:

The initial-action often initializes a control variable.

The action-after-each-iteration usually increments or decrements the control variable

The loop-continuation-condition tests whether the control variable has reached a termination value
Again, consider the following for loop code that prints "Welcome to Java" 100 times.
int i
for (i = 0; i < 100; i++) {
System.out.println("Welcome to Java!");
}
The for loop initializes i to 0, then repeatedly executes the println statement and evaluates the i++ while i is less
than 100.
In this code:

i = 0 is the initial action and initializes the control variable

i < 100 is the loop-continuation-condition and is a Boolean expression. The expression is evaluated
at the beginning of each iteration. If this condition is true, the loop body is executed. If ths condition is
false, the loop terminates and the program control turns to the line following the loop

i++ is the action-after-each-iteration statement that adjusts the contorl variable. This statement is
executed AFTER each iteration. It increments the control variable. Eventually, the value of the control
variable should force the loop-continuation-condition to beome false. Otherwise the loop is infinite : (
Tip: The control variable must ALWAYS be declared inside the control structure of the loop or BEFORE the loop.
If the loop control variable is ued onlly in the loop and not elsewhere, it is good programming practice to declare it in
the initial-action of the for loop. If the variable is declared inside the loop control structure, it cannot be referenced
outside the loop. For example, in the code about i cannot be referenced outside the for loop because it is declared
inside the for loop.
Notes:

The initial-action in a for loop can be a list of zero or more comma-separated variable declaration statements or
assignment expressions:
for (i = 0; j = 0; (i + j < 10 ); i++, j++) {
//Do something
}
Introduction to Java Programming
Summer Quarter I 2008
Page 27 of 30

The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements:
for (int i = l; i < 100; System.out.println(i), i++);

If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus an infinite loop would
generate and would be correct.
Which Loop to Use? (page 104): The while and for loops are called pre-test loops because the continuation
condition is checked BEFORE the loop body is executed. The do-while loop is called a post-test loop because the
condition is checked AFTER the loop body is executed.



A for loop may be used if the number of repetitions is known.
A while loop may be used if the number of repetitions is now known
A do-while loop can be used to replace a while loop if the loop body to be executed before the continuation
condition is tested.
Nested Loops (page 105): Nested loop consist of an outer loop and one or more inner loops. Each time the outer
loop is repeated, the inner loops are reentered and started anew.
Keywords break and continue (page 113): Two statements, break and continue, can be used in loop statements
to provide the loop with additional control:


break immediately ends the innermost loop that contains it. It is generally used with an if statement.
continue only ends the current iteration. Program control goes to the end of the loop body. This is also
generally used with an if statement.
The continue statement is always inside a loop. In the while and do-while loops, the loop-continuation-condition
is evaluated immediately after the continue statement. In the for loop, the action-after-each-iteration is
performed, then the loop-continuation-condition is evaluated immediately after the continue statement.
(Optional) Statement Labels and Breaking with Labels (page 115): Every statement in Java can have an optional
labels as an identifer. Labels are often associated with loops. The break statement can be used with a label to
break out of the labeled loop. The continue statement can be used with a label to break out of the current iteration of
the labeled loop.
The break statement shown below breaks out of the outer loop if
statement immediately following the outer loop.
(i * j > 50) and transfers control to the
outer:
for (int i = l; i < 10; i++) {
inner:
for (int j = l; j < 10; j++) {
if (i * j > 50)
continue outer;
System.out.print.ln(i * j);
}
}
Introduction to Java Programming
Summer Quarter I 2008
Page 28 of 30
Class Lecture – May 24, 2008 – Week 3
Introduction to Java Programming
Summer Quarter I 2008
Page 29 of 30
Chapter 5
Creating a Method (page 130):
Introduction to Java Programming
Summer Quarter I 2008
Page 30 of 30