Chapter 2
Java Fundamentals
Short Review
• Java is a case-sensitive language.
• All Java programs must be stored in a file with a .java file
extension.
• Comments are ignored by the compiler.
• A .java file may contain many classes but may only have
one public class.
• If a .java file has a public class, the class must have the
same name as the file.
• Java applications must have a main method.
Special Characters
Marks the beginning of a single
// double slash
line comment.
open and close Used in a method header to
()
parenthesis mark the parameter list.
Encloses a group of statements,
open and close curly
{} such as the contents of a class
braces
or a method.
Encloses a string of characters,
“” quotation marks such as a message that is to be
printed on the screen
Marks the end of a complete
; semi-colon
programming statement
Console Output
• Many of the programs that you will
write will run in a console window.
• The console window that starts a Java
application is typically known as the
standard output device.
• The standard input device is typically
the keyboard.
• The previous example uses the line:
System.out.println("Hello World!");
• The value inside the parenthesis will be sent to the output device (in this case,
a string).
• The println method places a newline character at the end of whatever is
being printed out. However, the print statement does not put a newline
character at the end of the output.
Java Escape Sequences (1 of 2)
Advances the cursor to the next line for subsequent
\n newline
printing
\t tab Causes the cursor to skip over to the next tab stop
Causes the cursor to back up, or move left, one
\b backspace
position
Causes the cursor to go to the beginning of the
\r carriage return
current line, not the next line
\\ backslash Causes a backslash to be printed
\’ single quote Causes a single quotation mark to be printed
\” double quote Causes a double quotation mark to be printed
Java Escape Sequences (2 of 2)
• Even though the escape sequences are comprised of two characters,
they are treated by the compiler as a single character.
Would result in the following output:
• With these escape sequences, complex text output can be achieved.
2.3 Variables and Literals (1 of 2)
• A variable is a named storage location in the computer’s memory.
• A literal is a value that is written into the code of a program.
• Programmers determine the number and type of variables a program will
need.
// This program has a variable.
• See example: Variable.java
public class Variable
{
public static void main(String[] args)
{
int value;
value = 5;
System.out.print("The value is ");
System.out.println(value);
}
}
2.3 Variables and Literals (2 of 2)
The + Operator
• The + operator can be used in two ways.
– as a concatenation operator
– as an addition operator
• If either side of the + operator is a string, the result will be
a string.
Identifiers (1 of 2)
• Identifiers are programmer-defined names for:
– classes
– variables
– methods
• Identifiers may not be any of the Java reserved keywords.
Identifiers (2 of 2)
• Identifiers must follow certain rules:
– An identifier may only contain:
▪ letters a–z or A–Z,
▪ the digits 0–9,
▪ underscores (_), or
▪ the dollar sign ($)
– The first character may not be a digit.
– Identifiers are case sensitive.
▪ itemsOrdered is not the same as
itemsordered.
– Identifiers cannot include spaces.
Java Reserved Keywords
abstract double instanceof static
assert else int strictfp
boolean enum interface super
break extends long switch
byte false native synchronized
case for new this
catch final null throw
char finally package throws
class float private transient
const goto protected true
continue if public try
default implements return void
do import short volatile
while
Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more readable;
therefore, the code is more maintainable.
• Which of the following is more descriptive?
• Java programs should be self-documenting.
Java Naming Conventions
• Variable names should begin with a lower case letter and then
switch to title case thereafter:
• Class names should be all title case.
• More Java naming conventions can be found at:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc
8.html
• A general rule of thumb about naming variables and classes
are that, with some exceptions, their names tend to be nouns
or noun phrases.
2.4 Primitive Data Types
• Primitive data types are built into the Java language and are
not derived from classes.
• There are 8 Java primitive data types.
– byte
– short
– int
– long
– float
– double
– boolean
– Char
Numeric Data Types
byte 1 byte Integers in the range
−128 to +127
short 2 bytes Integers in the range of
−32,768 to +32,767
int 4 bytes Integers in the range of
−2,147,483,648 to +2,147,483,647
long 8 bytes Integers in the range of
−9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
float 4 bytes Floating-point numbers in the range of ±3.410 -38 to ±3.41038 , with 7
plus or minus 3.4 times 10 to the negative thirty eighth power to plus or minus 3.4 times 10 to the thirty eighth power
digits of accuracy
double 8 bytes Floating-point numbers in the range of 1.710 308 to 1.710308,
plus or minus 1.7 times 10 to the power of 308, to plus or minus 1.7 times 10 to the power of 308.
with 15 digits of accuracy
Floating Point Data Types
• Data types that allow fractional values are called
floating-point numbers.
– 1.7 and −45.316 are floating-point numbers.
• In Java there are two data types that can represent
floating-point numbers.
– float - also called single precision (7 decimal
points).
– double - also called double precision (15 decimal
points).
Floating Point Literals (1 of 3)
• When floating point numbers are embedded into Java
source code they are called floating point literals.
• The default type for floating point literals is double.
– 29.75, 1.76, and 31.51 are double data types.
• Java is a strongly-typed language. which means that it
only allows you to store values of compatible data types
in variables
• See example: Sale.java
Scientific and E Notation
Decimal Notation Scientific Notation E Notation
2.4791 times 10 to the second power.
247.91 2.4791E2
2.4791 10 2
0.00072 7.2E−4
4 fourth power.
7.2 times 10 the negative
7.2×10
2,900,000 6
2.9E6
2.9
2.9 times ×10
10 to the sixth power.
See example: SunFacts.java
The boolean Data Type
• The Java boolean data type can have two possible
values.
– true
– false
• The value of a boolean variable may only be copied into
a boolean variable.
See example: TrueFalse.java
The char Data Type
• The Java char data type provides access to single
characters.
• char literals are enclosed in single quote marks.
– ‘a’, ‘Z’, ‘\n’, ‘1’
• Don’t confuse char literals with string literals.
– char literals are enclosed in single quotes.
– String literals are enclosed in double quotes.
See example: Letters.java
Unicode (1 of 5)
• Internally, characters are stored as numbers.
• Character data in Java is stored as Unicode characters.
• The Unicode character set can consist of 65536 (216 )
individual characters.
• This means that each character takes up 2 bytes in memory.
• The first 256 characters in the Unicode character set are
compatible with the ASCII* character set.
See example: Letters2.java
*American Standard Code for Information Interchange
Unicode (2 of 5)
Unicode (4 of 5)
Unicode (5 of 5)
2.5 Arithmetic Operators (1 of 2)
• Java has five (5) arithmetic operators.
Operator Meaning Type Example
+ Addition Binary total = cost + tax;
total equals cost plus tax semicolon.
− Subtraction Binary cost = total – tax;
cost equals total minus tax semicolon.
* Multiplication Binary tax = cost rate;
Computer code reads, tax equals cost multiplied by rate
semicolon.
sale Price equals start fractionoriginal
/ Division Binary salePrice
semicolon. = original over 2 end;fraction
2
% Modulus Binary remainder = value % 5;
remainder equals value percent sign 5 semicolon.
Integer Division
• Division can be tricky.
1
– In a Java program, what is the value of ?
2
• You might think the answer is 0.5…
• But, that’s wrong.
• The answer is simply 0.
• Integer division will truncate any decimal remainder.
Operator Precedence
• Mathematical expressions can be very complex.
• There is a set order in which arithmetic operations will be carried out.
Higher Priority
Operator Associativity Example Result
−
(unary negation)
Right to left x = -4 + 3;
x equals negative plus 3 semicolon. −1
Lower Priority
Operator Associativity Example Result
asterisk forward slash percent
sign. */% Left to right x =negative
x equals -4 +4 4
plus 2 semicolon.
plus%4 percent
3 * 13 sign+ 2; 13
3 asterisk
11
plus minus Left to right x = 6 + 3 – 4 + 6 * 3; 23
x equals 6 plus 3 minus 4 plus 6 asterisk 3 semicolon.
Grouping with Parenthesis
• When parenthesis are used in an expression, the inner
most parenthesis are processed first.
• If two sets of parenthesis are at the same level, they are
processed left to right.
•
2.6 Combined Assignment Operators
2.7 Creating Constants
• Many programs have data that does not need to be
changed.
• Littering programs with literal values can make the
program hard do read and maintain.
• Constants are identifiers that can hold only a single
value.
• Constants are declared using the keyword final.
2.8 The String Class
• Java has no primitive data type that holds a series of
characters.
• The String class from the Java standard library is used
for this purpose.
• In order to be useful, the a variable must be created to
reference a String object.
• Notice the S in String is upper case.
• By convention, class names should always begin with an
upper case character.
String Objects
• A variable can be assigned a String literal.
• Strings are the only objects that can be created in this
way.
• A variable can be created using the new keyword.
• This is the method that all other objects must use when
they are created.
See example: StringDemo.java
The String Methods
• Since String is a class, objects that are instances of it
have methods.
• One of those methods is the length method.
• This statement runs the length method on the object
pointed to by the value variable.
See example: StringLength.java
2.9 Scope
• Scope refers to the part of a program that has access to
a variable’s contents.
• Variables declared inside a method (like the main
method) are called local variables.
• Local variables’ scope begins at the declaration of the
variable and ends at the end of the method in which it
was declared.
See example: Scope.java (This program contains an
intentional error.)
2.10 Commenting Code (1 of 3)
• Java provides three methods for commenting code.
Comment Description
Style
Single line comment. Anything after the // on the line will be
//
ignored by the compiler.
Block comment. Everything beginning with /* and ending with the
/* … */ first */ will be ignored by the compiler. This comment type cannot
be nested.
Javadoc comment. This is a special version of the previous block
comment that allows comments to be documented by the
/** … */ javadoc utility program. Everything beginning with the /** and
ending with the first */ will be ignored by the compiler. This
comment type cannot be nested.
2.10 Commenting Code (2 of 3)
• Javadoc comments can be built into HTML
documentation.
• See example: Comment3.java
• To create the documentation:
– Run the javadoc program with the source file as an
argument
–
• The javadoc program will create index.html and
several other documentation files in the same directory
as the input file.
2.12 The Scanner Class (1 of 2)
• To read input from the keyboard we can use the
Scanner class.
• The Scanner class is defined in java.util, so we will
use the following statement at the top of our programs:
2.12 The Scanner Class (2 of 2)
• Scanner objects work with System.in
• To create a Scanner object:
• Scanner class methods are listed in Table 2-18 in the
text.
• See example: Payroll.java
2.13 Dialog Boxes
• A dialog box is a small graphical window that displays a
message to the user or requests input.
• A variety of dialog boxes can be displayed using the
JOptionPane class.
• Two of the dialog boxes are:
– Message Dialog - a dialog box that displays a
message.
– Input Dialog - a dialog box that prompts the user for
input.
The Joptionpane Class (1 of 2)
• The JOptionPane class is not automatically available to
your Java programs.
• The following statement must be before the program’s
class header:
• This statement tells the compiler where to find the
JOptionPane class.
The Joptionpane Class (2 of 2)
• The JOptionPane class provides methods to display
each type of dialog box.
Message Dialogs
• JOptionPane.showMessageDialog method is used to
display a message dialog.
• The first argument will be discussed in Chapter 7.
• The second argument is the message that is to be
displayed.
Input Dialogs (1 of 2)
• An input dialog is a quick and simple way to ask the user
to enter data.
• The dialog displays a text field, an Ok button and a
Cancel button.
• If Ok is pressed, the dialog returns the user’s input.
• If Cancel is pressed, the dialog returns null.
Input Dialogs (2 of 2)
• The argument passed to the method is the message to display.
• If the user clicks on the OK button, name references the string entered
by the user.
• If the user clicks on the Cancel button, name references null.
The System.exit Method (1 of 2)
• A program that uses JOptionPane does not
automatically stop executing when the end of the main
method is reached.
• Java generates a thread, which is a process running in
the computer, when a JOptionPane is created.
• If the System.exit method is not called, this thread
continues to execute.
The System.exit Method (2 of 2)
• The System.exit method requires an integer
argument.
• This argument is an exit code that is passed back to the
operating system.
• This code is usually ignored, however, it can be used
outside the program:
– to indicate whether the program ended successfully
or as the result of a failure.
– The value 0 traditionally indicates that the program
ended successfully.
Converting a String to a Number
• The JOptionPane’s showInputDialog method always
returns the user's input as a String
• A String containing a number, such as “127.89, can be
converted to a numeric data type.
The Parse Methods (1 of 2)
• Each of the numeric wrapper classes, (covered in
Chapter 10) has a method that converts a string to a
number.
– The Integer class has a method that converts a
string to an int,
– The Double class has a method that converts a
string to a double, and
– etc.
• These methods are known as parse methods because
their names begin with the word “parse.”
The Parse Methods (2 of 2)
Reading an Integer with an Input Dialog
Reading a double with an Input Dialog
See example: PayrollDialog.java