Introduction to Java

advertisement
Introduction to Java
•
•
•
•
•
•
Java Translation
Program Structure
Classes and Objects
Primitive data types
Flow of Control
Loops
Java Translation
The Java compiler translates Java source code into a
special representation called bytecode in the .class file
Java bytecode is not the machine language for any specific
CPU
Another software tool, called an interpreter (in our case the
Java Virtual Machine), executes the bytecode
Java is considered to be architecture-neutral
The Java compiler is not tied to any particular machine
The JVM can be implemented on any machine
Java Program Structure
• In the Java programming language:
– A program is made up of one or more classes
– A class contains zero or more attributes
– A class contains one or more methods
– A method contains program statements
• A Java application starts with a class
containing a method called main
• See Lincoln.java (page 28)
Java Program Structure
//
comments about the class
public class MyProgram
{
class header
class body
Comments can be placed almost anywhere
}
4
Java Program Structure
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main (String[] args)
{
method body
method header
}
}
5
Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or what can be done to it)
• The state of a bank account includes its balance
• The behaviors associated with a bank account include
the ability to get the balance, make deposits, and make
withdrawals
• Note that the behavior of an object might change its
state, e.g. making a deposit will increase the balance
6
Classes
• An object is defined by a class representing a concept
• A class is the blueprint for each instance of an object
• Multiple objects can be created from the same class
• A class has attributes that define the state of each object
• A class has methods that define the behavior of the object
• The class that contains the main method represents the
starting point for a Java program
• The program can and usually does contain more classes
than just the one that contains the main method
Objects and Classes
A Class
(The Concept)
Three objects
(Three Instances
of the Concept)
BankAccount
- balance: float
+ getBalance(): float
+ deposit(float amount): bool
+ withdraw(float amount): bool
Multiple objects
of the same class
John’s Bank Account
Balance: $5,257.51
Bill’s Bank Account
Balance: $1,245,069.89
Mary’s Bank Account
Balance: $16,833.27
Primitive Data
• There are eight primitive data types in Java
• Four of them represent integers:
– byte, short, int, long
• Two of them represent floating point numbers:
– float, double
• One of them represents characters:
– char
• And one of them represents boolean values:
– boolean
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 a sequence of multiple characters
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 represent any two
states such as a light bulb being on or off
boolean isOn = true;
Flow of Control
• Unless specified otherwise, the order of statement
execution through a method is linear:
– one statement after another in sequence
• Some programming statements allow us to:
– decide whether or not to execute a particular statement
– execute a statement over and over, repetitively
• These decisions are based on boolean expressions
(or conditions) that evaluate to true or false
• The order of statement execution is called the flow of
control
Conditional Statements
• A conditional statement lets us choose which
statement will be executed next
• Therefore they are sometimes called selection
statements
• Conditional statements give us the power to make
basic decisions
• The Java conditional statements are the:
– if statement
– if-else statement
– switch statement
The if Statement
• The if statement has the following syntax:
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
if ( condition )
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
14
The if-else Statement
• An else clause can be added to an if statement to
make an if-else statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if
the condition is false, statement2 is executed
• One or the other will be executed, but not both
• See Wages.java (page 211)
15
Block Statements
• Several statements can be grouped into a block
statement delimited by braces
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
Now the increment will only occur
when the if condition is true
• A block statement can be used wherever a
statement is called for in the Java syntax
16
The switch Statement
• The general syntax of a switch statement is:
switch
and
case
are
reserved
words
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
If expression
matches value2,
control jumps
to here
Comparing Characters
• Therefore, if we want to base a decision in
our program on whether a character is a
digit or not, we can use the following code:
if (character >= ‘0’ && character <= ‘9’)
System.out.println (“Yes, it’s a digit!”);
• We can also check for a valid upper case
alphabetic character as follows:
if (character >= ‘A’ && character <= ‘Z’)
System.out.println (“It’s a capital letter!”);
Comparing Strings
• Remember that in Java a string is an object
• We cannot use the == operator to determine if the values
of two strings are identical (character by character)
• The equals method can be called with strings to
determine if two strings contain exactly the same
characters in the same order
• The equals method returns a boolean result
if (name1.equals(name2))
System.out.println ("Same name");
Comparing Strings
• We cannot use the relational operators to compare strings
• The String class contains a method called compareTo
to determine if one string comes before another
• A call to name1.compareTo(name2)
– returns zero if name1 and name2 are equal (contain the same
characters)
– returns a negative value if name1 is less than name2
– returns a positive value if name1 is greater than name2
Strings
• String is basically just a collection of
characters.
• Thus, the string “Martyn” could be thought
of as a 6-element array ('M', 'a', 'r', 't', 'y',
'n').
• The String class allows us to manipulate
these data items.
Strings in java
• String is a class in Java
• Strings are constant (values cannot be
changed after they are created)
• Set of characters "Lisa Simpson" is a
string.
• "A" is a string, 'A' is a character. Note the
difference here. Character literals are
delimited by single quotes and String
literals are delimited by double quotes.
Methods on Strings
• The String class provides methods to
– Return the character at a specific index (charAt)
– Return the index of a specific character (indexOf)
– Compare two strings (compareTo)
– Concatenate two strings (concat)
– Check the length of a string (length)
– Extract a sub-string (substring)
– Replace all instances of a character with another
character (replace)
Repetition Statements
• Repetition statements allow us to execute a
statement or a block of statements multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
– the while loop
– the do loop
– the for loop
• The programmer should choose the right kind of
loop for the situation
The while Statement
Start
while(Boolean_Expression)
Loop_Body
Evaluate
Boolean_Expression
false
End loop
true
Execute
Loop_Body
The do-while Statement
Start
do
Loop_Body
while(Boolean_Expression);
Execute
Loop_Body
true
Evaluate
Boolean_Expression
false
End loop
The for Statement
for( Initialization_Action ; Boolean_Expression ; Update_Action)
Loop_Body
Start
Execute
Initialization_Action
Execute
Update_Action
Evaluate
Boolean_Expression
Execute
Loop_Body
true
false
End loop
Download