Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 1
Objects and Primitive data
1
Java
A programming language specifies the words and symbols
that we can use to write a program
A programming language employs a set of rules that dictate
how the words and symbols can be put together to form valid
program statements
The Java programming language was created by Sun
Microsystems, Inc.
It was introduced in 1995 and it's popularity has grown quickly
since
2
Futures of Java
Java is secure
Java is a platform –independent language
Java is an Internet programming language
Java is a high-performance language
Java is simple
3
Java Program Structure
In the Java programming language:
A program is made up of one or more classes
A class contains one or more methods
A method contains program statements
These terms will be explored in detail throughout the course
A Java application always contains a method called main
See Lincoln.java (page 28)
4
Java Program Structure
//
comments about the class
public class MyProgram
{
class header
class body
Comments can be placed almost anywhere
}
5
Java Program Structure
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main (String[] args)
{
method body
method header
}
}
6
Comments
Comments in a program are called inline documentation
They should be included to explain the purpose of the
program and describe processing steps
They do not affect how a program works
Java comments can take three forms:
// this comment runs to the end of the line
/*
this comment runs to the terminating
symbol, even across line breaks
/** this is a javadoc comment
*/
*/
7
Identifiers
Identifiers are the words a programmer uses in a program
An identifier can be made up of letters, digits, the underscore
character ( _ ), and the dollar sign
Identifiers cannot begin with a digit
Java is case sensitive - Total, total, and TOTAL are
different identifiers
By convention, programmers use different case styles for
different types of identifiers, such as
title case for class names - Lincoln
upper case for constants – MAXIMUM
A reserved word cannot be used in any other way.
8
Reserved Words
The Java reserved words:
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
9
White Space
Spaces, blank lines, and tabs are called white space
White space is used to separate words and symbols in a
program
Extra white space is ignored
A valid Java program can be formatted many ways
Programs should be formatted to enhance readability, using
consistent indentation
See Lincoln2.java (page 34)
See Lincoln3.java (page 35)
10
Program Development
The mechanics of developing a program include several
activities
writing the program in a specific programming language
(such as Java)
translating the program into a form that the computer can
execute
investigating and fixing various types of errors that can
occur
Software tools can be used to help with all parts of this
process
11
Language Levels
There are four programming language levels:
machine language
assembly language
high-level language
fourth-generation language
Each type of CPU has its own specific machine language
The other levels were created to make it easier for a human
being to read and write programs
12
Programming Languages
Each type of CPU executes only a particular machine
language
A program must be translated into machine language before
it can be executed
A compiler is a software tool which translates source code
into a specific target language
Often, that target language is the machine language for a
particular CPU type
The Java approach is somewhat different
13
Java Translation
The Java compiler translates Java source code into a special
representation called bytecode
Java bytecode is not the machine language for any traditional
CPU
Another software tool, called an interpreter, translates
bytecode into machine language and executes it
Therefore the Java compiler is not tied to any particular
machine
Java is considered to be architecture-neutral
14
Java Translation
Java source
code
Java
compiler
Java
bytecode
Bytecode
interpreter
Bytecode
compiler
Machine
code
15
Errors
A program can have three types of errors
The compiler will find syntax errors and other basic problems
(compile-time errors)
If compile-time errors exist, an executable version of the
program is not created
A problem can occur during program execution, such as trying
to divide by zero, which causes a program to terminate
abnormally (run-time errors)
A program may run, but produce incorrect results, perhaps
using an incorrect formula (logical errors)
16
Character Strings
A string of characters can be represented as a string literal by
putting double quotes around the text:
Examples:
"This is a string literal."
"123 Main Street"
"X"
Every character string is an object in Java, defined by the
String class
Every string literal represents a String object
17
The println Method
In the Lincoln program, we invoked the println method to
print a character string
The System.out object represents a destination (the monitor
screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
object
method
name
information provided to the method
(parameters)
18
The print Method
The System.out object provides another service as well
The print method is similar to the println method, except
that it does not advance to the next line
Therefore anything printed after a print statement will
appear on the same line
See Countdown.java (page 63)
19
String Concatenation
The string concatenation operator (+) is used to append one
string to the end of another
"Peanut butter " + "and jelly"
It can also be used to append a number to a string
A string literal cannot be broken across two lines in a program
See Facts.java (page 65)
20
String Concatenation
The + operator is also used for arithmetic addition
The function that it performs depends on the type of the
information on which it operates
If both operands are strings, or if one is a string and one is a
number, it performs string concatenation
If both operands are numeric, it adds them
See Addition.java (page 67)
21
Escape Sequences
What if we wanted to print a the quote character?
The following line would confuse the compiler because it
would interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");
An escape sequence is a series of characters that represents
a special character
An escape sequence begins with a backslash character (\)
System.out.println ("I said \"Hello\" to you.");
22
Escape Sequences
Some Java escape sequences:
Escape Sequence
\b
\t
\n
\r
\"
\'
\\
Meaning
backspace
tab
newline
carriage return
double quote
single quote
backslash
See Roses.java (page 68)
23
Primitive Data
There are eight primitive data types in Java
Four of them represent integers:
Two of them represent floating point numbers:
float, double
One of them represents characters:
byte, short, int, long
char
And one of them represents boolean values:
boolean
24
Numeric Primitive Data
The difference between the various numeric primitive types
is their size, and therefore the values they can store:
Type
Storage
Min Value
Max Value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
float
double
32 bits
64 bits
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
25
Characters
A char variable stores a single character
Character literals are delimited by single quotes:
'a'
'X'
'7'
'$'
','
'\n'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
Note the distinction between a primitive character variable,
which holds only one character, and a String object, which
can hold multiple characters.
26
Character Sets
A character set is an ordered list of characters, with each
character corresponding to a unique number
A char variable in Java can store any character from the
Unicode character set
The Unicode character set uses sixteen bits per character,
allowing for 65,536 unique characters
It is an international character set, containing symbols and
characters from many world languages
27
Characters
The ASCII character set is older and smaller than Unicode,
but is still quite popular
The ASCII characters are a subset of the Unicode character
set, including:
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
A, B, C, …
a, b, c, …
period, semi-colon, …
0, 1, 2, …
&, |, \, …
carriage return, tab, ...
28
Boolean
A boolean value represents a true or false condition
The reserved words true and false are the only valid
values for a boolean type
boolean done = false;
A boolean variable can also be used to represent any two
states, such as a light bulb being on or off
29
Type Casting
In type casting, a data type is converted into another data
type.
Example
float c = 34.89675f;
int b = (int)c + 10;
30
Automatic type and Casting
There are two type of data conversion: automatic type
conversion and casting.
When one type of data is assigned to a variable of another
type then automatic type conversion takes place provided it
meets the conditions specified:
The two types are compatible
The destination type is larger than the source type.
Casting is used for explicit type conversion. It loses
information above the magnitude of the value being
converted.
31
Type Promotion Rules
All byte and short values are promoted to int type.
If one operand is long, the whole expression is promoted to
long.
If one operand is float then the whole expression is
promoted to float.
If one operand is double then the whole expression is
promoted to double.
32
Variables
A variable is a name for a location in memory
Three components of a variable declaration are:
Data type
Name
Initial value to be assigned (optional)
Syntax
datatype identifier [=value][, identifier[=value]...];
A variable can be given an initial value in the declaration
int sum = 0;
int base = 32, max = 149;
When a variable is referenced in a program, its current
value is used
33
Scope and Lifetime of Variables
Variables can be declared inside a block.
The block begins with an opening curly brace and ends with
a closing curly brace.
A block defines a scope.
A new scope is created every time a new block is created.
Scope specifies what objects are visible to other parts of
the program.
It also determines the life of an object.
34
Constants
A constant is an identifier that is similar to a variable except
that it holds the same value during its entire existence
As the name implies, it is constant, not variable
The compiler will issue an error if you try to change the value
of a constant
In Java, we use the final modifier to declare a constant
final int MIN_HEIGHT = 69;
35
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Logical Operators
Conditional Operators
Assignment operators
36
Arithmetic Operators
Operands of the arithmetic operators must be of numeric type.
Boolean operands cannot be used, but character operands
are allowed.
These operators are used in mathematical expressions.
An expression is a combination of one or more operators and
operands
Arithmetic expressions compute numeric results and make
use of the arithmetic operators:
Addition
Subtraction
Multiplication
Division
Remainder
+
*
/
%
If either or both operands used by an arithmetic operator are
floating point, then the result is a floating point
37
Division and Remainder
If both operands to the division operator (/) are integers, the
result is an integer (the fractional part is discarded)
14 / 3
equals
4
8 / 12
equals
0
The remainder operator (%) returns the remainder after
dividing the second operand into the first
14 % 3
equals
2
8 % 12
equals
8
38
Operator Precedence
Operators can be combined into complex expressions
result
=
total + count / max - offset;
Operators have a well-defined precedence which
determines the order in which they are evaluated
Multiplication, division, and remainder are evaluated prior to
addition, subtraction, and string concatenation
Arithmetic operators with the same precedence are
evaluated from left to right, but parentheses can be used to
force the evaluation order
39
Operator Precedence
What is the order of evaluation in the following expressions?
a + b + c + d + e
a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
a + b + c + d + e
1
2
3
4
a + b * c - d / e
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
1
40
Expression Trees
The evaluation of a particular expression can be shown using
an expression tree
The operators lower in the tree have higher precedence for
that expression
+
a + (b – c) / d
/
a
b
d
c
41
Increment and Decrement
The increment and decrement operators use only one operand
The increment operator (++) adds one to its operand
The decrement operator (--) subtracts one from its operand
The statement
count++;
is functionally equivalent to
count = count + 1;
42
Increment and Decrement
The increment and decrement operators can be applied in
postfix form:
count++
or prefix form:
++count
When used as part of a larger expression, the two forms can
have different effects
Because of their subtleties, the increment and decrement
operators should be used with care
43
Assignment Operators
Often we perform an operation on a variable, and then store
the result back into that variable
Java provides assignment operators to simplify that process
For example, the statement
num += count;
is equivalent to
num = num + count;
44
Assignment Operators
There are many assignment operators in Java, including the
following:
Operator
+=
-=
*=
/=
%=
Example
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
Equivalent To
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
45
Assignment Operators
The behavior of some assignment operators depends on the
types of the operands
If the operands to the += operator are strings, the assignment
operator performs string concatenation
The behavior of an assignment operator (+=) is always
consistent with the behavior of the corresponding operator (+)
46
Class Libraries
A class library is a collection of classes that we can use when
developing programs
There is a Java standard class library that is part of any Java
development environment
These classes are not part of the Java language per se, but
we rely on them heavily
The System class and the String class are part of the Java
standard class library
47
Packages
The classes of the Java standard class library are organized
into packages
Some of the packages in the standard class library are:
Package
Purpose
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities and components
Network communication
Utilities
48
The import Declaration
When you want to use a class from a package, you could use
its fully qualified name
java.util.Random
Or you can import the class, then just use the class name
import java.util.Random;
To import all classes in a particular package, you can use the *
wildcard character
import java.util.*;
49
The import Declaration
All classes of the java.lang package are automatically
imported into all programs
That's why we didn't have to explicitly import the System or
String classes in earlier programs
The Random class is part of the java.util package
It provides methods that generate pseudo-random numbers
50
Input/Output
To print output to the "standard output stream" just by calling
System.out.println
To read input from the console window you first construct a
Scanner that is attached to the "standard input stream"
System.in.
Scanner in = new Scanner(System.in);
The Scanner class provides convenient methods for reading
input values of various types
A Scanner object can be set up to read input from various
sources, including the user typing values on the keyboard
Keyboard input is represented by the System.in object
The new operator creates the Scanner object
51
Input/Output (cont)
Once created, the Scanner object can be used to invoke
various input methods of Scanner class, such as:
in.nextLine();
in.next();
in.nextInt();
in.nextdouble();
The Scanner class is part of the java.util class library,
and must be imported into a program to be used
See Echo.java (page 91)
52
Thank you for your attention!
53