Weekly Report Chapter 2 Java Fundamentals 1 Contents 1 The Parts of a Java Program 2 The print and println Methods, and the Java API 3 Variables and Literals 4 Primitive Data Types 5 Arithmetic Operat.
Trang 1Chapter 2
Java Fundamentals
Trang 21 The Parts of a Java Program
2 The print and println Methods, and
the Java API
3 Variables and Literals
4 Primitive Data Types
5 Arithmetic Operators
6 Combined Assignment Operators
7 Conversion between Primitive Types
8 Creating Named Constraints with final
Trang 41 The Parts of a Java
Program
Write a Java program to display a message (Programming is great fun!) on the screen
Trang 51 The Parts of a Java
Program (Cont’d)
Enter the project name: MyFirstProject
Enter the class name: Simple
This will create a source code file Simple.java
Trang 61 The Parts of a Java
Program (Cont’d)
Trang 71 The Parts of a Java
Program (Cont’d)
Trang 81 The Parts of a Java
Program (Cont’d)
//This is a simple Java program
// :
marks the beginning of a comment
The compiler ignores everything from the double-slash to the end of the line You can type anything you want.
Comments help explain what’s going on.
Trang 91 The Parts of a Java
Program (Cont’d)
A blank line
Programmers often insert blank lines in
programs to make them easier to read
public class Simple
This is a class header, and it marks the
beginning of a class definition
Trang 101 The Parts of a Java
Program (Cont’d)
A Java program must have at least one
class definition
public:
public is a Java keyword
must be written in all lowercase letters
public is an access specifier , and it controls where the class may be accessed from The public specifier means access to the class is unrestricted (the class is “open to the public”).
Trang 111 The Parts of a Java
Simple is the class name which is made up
by the programmer Programmer-defined names may be written in lowercase letters, uppercase letters, or a mixture of both.
Trang 121 The Parts of a Java
Program (Cont’d)
public class Simple
tell the compiler that a public accessible class named Simple is being defined.
We can create more than one class in a file, but
we may only have one public class per Java file.
When a Java file has a public class, the name of the public class must be the same as the name
of the file (without the java extension).
Java is a case-sensitive language.
Public ≠ public ≠ puBlic ≠ pUblic …
Trang 131 The Parts of a Java
Program (Cont’d)
Line 4:
{
is a left brace, or an opening brace, and is
associated with the beginning of the class
definition.
All programming statements that are parts of class are enclosed in a set of braces In line 9,
we will have the closing brace.
Everything between the two braces is the
body of the class named Simple.
Trang 141 The Parts of a Java
Program (Cont’d)
Trang 151 The Parts of a Java
Program (Cont’d)
public static void main(String[] args)
a method header, the beginning of a
Trang 161 The Parts of a Java
Program (Cont’d)
{
This opening brace belongs to the main
method Every opening brace must have a accompanying closing brace
We will have a closing brace in line 8 that corresponds with this opening brace
Everything between these braces is the
body of the main method
Trang 171 The Parts of a Java
Program (Cont’d)
Line 7:
System.out.println("Programming is great fun!");
This line is a statement It displays a message
on the screen The message, “ Programming is great fun!” , is printed without the quotation marks
The group of characters inside the quotation marks is called a string literal.
There is a semicolon at the end of this line Semicolon marks end of a statement in Java.
Trang 181 The Parts of a Java
Program (Cont’d)
Not every line of code ends with a semicolon:
Comments do not have to end with a semicolon
Class headers and method headers do not end with
a semicolon.
The brace characters, { and }, are not statements,
so we do not place a semicolon after them.
Lines 8 and 9 contain the closing braces
for main method and the class definition.
Trang 191 The Parts of a Java
Program (Cont’d)
Java is a case-sensitive language.
All Java program must be stored in a file
with a name that ends with java
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.
Trang 201 The Parts of a Java
Program (Cont’d)
Every Java application program must
have a method named main.
For every brace, or opening brace, there
must be a corresponding right brace, or closing brace.
Statements are terminated with
semicolons This does not include
comments, class headers, method
headers, or braces.
Trang 212 The print and println
Methods, and Java API
The print and println methods
are used to display text output.
are parts of the Java API (Application
Programmer Interface).
API is a collection of prewritten classes and methods for performing specific operations.
The console
Standard output: the monitor
Standard input: the keyboard
Trang 222 The print and println
Methods, and Java API
System.out.println("Programming is great fun!");
Hierarchical Relationship
among the System class,
the out object, and the
print and println
methods
Trang 232 The print and println
Methods, and Java API
The System class is part of the java API It has member
objects and methods for performing system-level
operations, such as sending output to the console.
The out object is a member of the System class It
provides methods for sending output to the screen.
The print and println methods are members of the
out object They actually perform the work of writing characters on the screen.
We use the period to separate System, out and print
or println The period is pronounced “dot”.
Trang 242 The print and println
Methods, and Java API
The value that is to be displayed on the
screen is places inside the parentheses This value is known as an argument
System.out.println(“King Arthur”);
The println method is that after it
displays its message, it advances the
cursor to the beginning of the next line.
Trang 252 The print and println
Methods, and Java API
Trang 26The print Method
part of the System.out object
serves a purpose to display output on the screen
does not advance the cursor to the next
line after its message is displayed
Trang 27The print Method
Trang 28The print Method
Trang 29The print Method
There are two ways to fix the Unruly
program:
use escape sequences to separate the output into different lines
An escape sequence starts with the blackslash
character (\), and is followed by one or more
control characters.
The escape sequence that causes the output
cursor to go to the next line is \n
\n is called the newline escape sequence.
Trang 30The print Method
Trang 31The print Method
Trang 32Common Escape Sequences
Trang 333 Variables and Literals
in the computer’s memory.
A literal is a value that is written into
the code of a program.
Trang 343 Variables and Literals
(Cont’d)
Trang 353 Variables and Literals (Cont’d)
A variable declaration tells the compiler
the variable’ name
the type of data the variable will hold
variable’s name
data type
Trang 363 Variables and Literals
After this line executes, the value variable will contain the value 5
Trang 373 Variables and Literals
(Cont’d)
Trang 383 Variables and Literals
(Cont’d)
System.out.println(value);
The method println will display the
variable’s contents on the console
There are no quotation marks around
variable value
Compare with
System.out.println(“value”);
Trang 39Display Multiple Items with
the + Operator
The + operator is used with strings:
String concatenation operator
System.out.println(“This is ” + “one string.”);
This is one string.
The + operator can be used to
concatenate the contents of a variable to
a string
number = 5;
System.out.println(“The value is ” + number);
The value is 5
Trang 40Display Multiple Items with the + Operator (Cont’d)
line and end on another
System.out.println(“Enter a value that is
greater than zero and less than 10.”);
string literals, and use the + operator
System.out.println(“Enter a value that” +
“ is greater than zero and less “ +
“than 10.”);
Error
Trang 41Display Multiple Items with
the + Operator (Cont’d)
Trang 42 Represents some element of a program.
Variable names, class names, name of
methods, …
Trang 43Identifiers (Cont’d)
Should choose names that give an
indication of what they are used for, what the purpose is
Number of ordered items
int x; not good int itemsOrdered;
Trang 44Identifiers (Cont’d)
identifiers:
The first character must be one of the
letters a-z, A-Z, _, $
After the first character, we can use letters a-z, A-Z, digits 0-9, _, $
Uppercase and lowercase characters are distinct
Identifiers cannot include spaces
Trang 46Identifiers (Cont’d)
It is standard practice to begin variable
names with a lowercase letter
Capitalize the first the first letter of each subsequent word
int itemOdered;
Trang 47Identifiers (Cont’d)
It is standard practice to begin variable
names with a uppercase letter
Capitalize the first letter of each
subsequent word
public class PayRoll
Trang 484 Primitive Data Types
the type of data that the variable can hold.
is important
amount of memory
the way the variable formats and stores
data
Trang 494 Primitive Data Types (Cont’d)
Data Type Size Range
byte 1 byte Integers in the range of -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.4×10 -38 to
±3.4×10 38 , with 7 digits of accuracy double 8 bytes Floating-point numbers in the range of ±1.7×10 -308 to
Trang 504 Primitive Data Types
(Cont’d)
General format of a variable declaration
DataType VariableName;
DataType : name of the data type
VariableName : name of the variable
Trang 514 Primitive Data Types
Trang 53Floating-Point Literals
Java assumes floating-point literals such
as 29.75, 1.76, … to be of double data type.
Trang 54Scientific and E Notation
represented in scientific notation.
47,281.97 4.728197×104
values in scientific notation.
Decimal Notation Scientific Notation E Notation
247.91 2.4791×10 2 2.4791E2
0.00072 7.2×10 -4 7.2E-4
Trang 55The boolean Data Type
create variables that hold one of two possible values:
true false
useful for evaluation conditions that
are either true or false.
Trang 56The boolean Data Type
(Cont’d)
Trang 57The char Data Type
The char data type is used to store
characters.
A variable of the char data type can
hold one character at a time.
Trang 58The char Data Type (Cont’d)
memory
Trang 59The char Data Type (Cont’d)
Trang 60The char Data Type (Cont’d)
Trang 61Variable Assignment and
Initialization
Using = assignment operator
The operand on the left side of the =
operator must be a variable
The value in right side of the = operator is assigned to the variable in left side
int unitSold;
unitSold = 12;
12 = unitSold; //ERROR !
Trang 62Variable Assignment and
Initialization (Cont’d)
We may also assign values to variables as part of the declaration statement
int month = 2, days = 28;
int flightNum = 89, travelTime, departure = 10;
Trang 63Variables Hold Only One Value
at a Time
time.
variable, the new value replaces the
variable’s previous contents.
Trang 645 Arithmetic Operator
Unary
Requires only a single operand
-5 -number (negative operator)
Trang 655 Arithmetic Operator
(Cont’d)
Operator Meaning Type Example
+ Addition Binary total = cost + tax;
- Subtraction Binary cost = total – tax;
* Multiplication Binary tax = cost * rate;
/ Division Binary salePrice = original / 2;
% Modulus Binary remainder = value % 3;
Trang 66Integer Division
When both operands of a division
statement are integers, the statement
will result in integer division
The result of the integer division will be an
integer.
parts is assigned the value 5.0 value 5.666666666667parts is assigned the
Trang 68Operator Precedence (Cont’d)
Trang 69Grouping with Parentheses
performed before others
Trang 70The Math class
Rising a number to a power
result = Math.pow(4.0, 2.0); // 42
accepts a double value as its argument and returns the square root of the value
Trang 716 Combined Assignment
Operators
combine the assignment operator with the arithmetic operators.
x += 5;
x = x + 5; 1 Add 5 to x2 The resut is then
assigned to x equivalent to
Trang 726 Combined Assignment
Operators (Cont’d)
Operator Example Usage Equivalent To
Trang 737 Conversion between
Primitive Data Types
variable, the value’s data type must be compatible with the variable’s data
type.
between data types automatically, but does not perform any conversion that can result in the loss of data;
Trang 74short y = 2;
x = y; // OK
Trang 757 Conversion between
Primitive Data Types (Cont’d)
In assignment statements where values of
lower-ranked data types are stored in variables of
hight-ranked data types, Java automatically
converts the lower-ranked value to the
higher-ranked type (widening conversion)
Primitive data type ranking
double Highest Rank
Trang 76Cast Operators
conversion of a value to a lower-ranked type.
Narrowing conversions can cause a loss
of data, Java does not automatically
perform them.
convert a value, even if it is a narrowing conversion.
Trang 77Cast Operators (Cont’d)
that appear as a data type name
enclosed in a set of parentheses.
int x;
double y = 2.5;
cast operator
Trang 78Cast Operators (Cont’d)
int pie = 10, people = 4;
double piesPerPerson;
piesPerPerson = pie / people;
piesPerPerson = (double)pie / people;
piesPerPerson = pie / (double)people;
piesPerPerson = (double)(pie / people);
2.0
2.5 2.5
2.0
Trang 79Mixed Integer Operations
byte, and short variables:
Values of the byte or short data types are temporarily converted to int value
The result will always be an int
short x = 10, y = 20, z;
x + y results an
Trang 80Other Mixed Mathematical
Expressions
1 If one of an operator’s operands is a double,
the value of the other operand will be converted
to a double The result of the expression will be
a double.
2 If one of an operator’s operands is a float, the
value of the other operand will be converted to a float The result of the expression will be a
float.
3 If one of an operator’s operands is a long, the
value of the other operand will be converted to a long The result of the expression will be a
long.
Trang 818 Creating Named Constants with final
variable declaration to make the
variable a named constant.
value, and that value cannot change during the execution of the program
Trang 828 Creating Named Constants with final (Cont’d)
amount = balance * 0.069;
final double INTEREST_RATE = 0.069;amount = balance * INTEREST_RATE;
The Math.PI Named Constant
is assigned the value 3.1415926535897323845
is an approximation of the mathematical value pi.
Interest rate
Trang 839 The String Class
String literals are enclosed in double
quotation marks.
“Hello World” “Joe Mahoney”
Java does not have a primitive data type
for storing strings in memory.
The String class
Allows you to create objects for holding
strings.
Has various methods that allow you to work with strings.
Trang 849 The String Class (Cont’d)
Objects are created from classes.
Declare a variable of the String class
String name;
A class type variable does not hold the actual data
item It holds the memory address of the data item.
name is a class type variable, holds the memory address of
a String object.
When a class type variable holds the address of an
object, it is said that the variable references the object.
Class type variables are known as reference variables.