Intro.to.Java

Download Report

Transcript Intro.to.Java

INTRODUCTION TO JAVA
CENG 104 FUNDAMENTALS OF COMPUTER
PROGRAMMING II
Melek OKTAY
[email protected]
Referenced Book

The metarils of this course are taken from two
different books


“Java Software Solutions: Foundations of Program
Design, 6th Edition”
“Java How to Program, 6/e-7/e Deitel”
JAVA TRANSLATION
Java
compiler
Java
bytecode
Bytecode
interpreter
Bytecode
compiler
© 2007 Pearson Addison-Wesley. All
rights reserved
Java source
code
Machine
code
1-3
“WRITE ONCE, RUN EVERYWHERE”
FOCUS OF THE COURSE

Object-Oriented Software Development
problem solving

program design, implementation, and testing

object-oriented concepts
classes
 objects
 encapsulation
 inheritance
 polymorphism


graphical user interfaces  not included (out of
scope)
© 2007 Pearson Addison-Wesley. All
rights reserved

1-5
JAVA



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
© 2007 Pearson Addison-Wesley. All
rights reserved

A programming language specifies the words and
symbols that we can use to write a program
1-6
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
© 2007 Pearson Addison-Wesley. All
rights reserved

See Lincoln.java (page 27)
1-7
JAVA PROGRAM STRUCTURE
//
comments about the class
public class MyProgram
{
class body
Comments can be placed almost anywhere
© 2007 Pearson Addison-Wesley. All
rights reserved
class header
}
1-8
JAVA PROGRAM STRUCTURE
//
comments about the class
public class MyProgram
{
comments about the method
public static void main (String[] args)
{
method body
}
method header
© 2007 Pearson Addison-Wesley. All
rights reserved
//
}
1-9
COMMENTS

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:
© 2007 Pearson Addison-Wesley. All
rights reserved

Comments in a program are called inline
documentation
// 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
*/
*/
1-10
IDENTIFIERS




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
© 2007 Pearson Addison-Wesley. All
rights reserved

Identifiers are the words a programmer uses in a
program
1-11
IDENTIFIERS



Sometimes we are using another programmer's
code, so we use the identifiers that he or she
chose (such as println)
Often we use special identifiers called reserved
words that already have a predefined meaning in
the language
© 2007 Pearson Addison-Wesley. All
rights reserved

Sometimes we choose identifiers ourselves when
writing a program (such as Lincoln)
A reserved word cannot be used in any other way
1-12
RESERVED WORDS

The Java reserved words:
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
© 2007 Pearson Addison-Wesley. All
rights reserved
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
1-13
WHITE SPACE


Spaces, blank lines, and tabs are called white space
© 2007 Pearson Addison-Wesley. All
rights reserved
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 33)

See Lincoln3.java (page 34)
1-14
2.3 MODIFYING OUR FIRST JAVA
PROGRAM (CONT.)

Modifying programs
Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
 Using different code

9
10
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
Line 9 displays “Welcome to ” with cursor remaining
on printed line
 Line 10 displays “Java Programming! ” on same line
with cursor on next line

16
1
// Fig. 2.3: Welcome2.java
2
// Printing a line of text with multiple statements.
17
OUTLINE
3
4
public class Welcome2
5
{

Welcome2.java
1. Comments
2. Blank line
6
// main method begins execution of Java application
7
public static void main( String args[] )
8
{
3.1 Method
main
9
System.out.print( "Welcome to " );
10
System.out.println( "Java Programming!" );
System.out.print keeps the
Method
cursor on the same line, so4.
System.out.prin
t
System.out.println
continues
4.1 Method
on the same line.
System.out.prin
tln
11
12
3. Begin class
Welcome2
} // end method main
13
14 } // end class Welcome2
Welcome to Java Programming!
5. end main,
Welcome2
Program
Output
2.3 MODIFYING OUR FIRST JAVA
PROGRAM (CONT.)

Escape characters
Backslash ( \ )
 Indicates special characters be output


Newline characters (\n)
Interpreted as “special characters” by methods
System.out.print and System.out.println
 Indicates cursor should be at the beginning of the
next line
 Welcome3.java (Fig. 2.4)

9

System.out.println( "Welcome\nto\nJava\nProgramming!" );
Line breaks at \n
18
1
// Fig. 2.4: Welcome3.java
2
// Printing multiple lines of text with a single statement.
19
OUTLINE
3
4
public class Welcome3
5
{

6
// main method begins execution of Java application
7
public static void main( String args[] )
8
{
9
Welcome3.java
1. main
2.
System.out.println
(uses \n for new
line)
System.out.println( "Welcome\nto\nJava\nProgramming!" );
10
11
} // end method main
12

Program Output
13 } // end class Welcome3
Welcome
to
Java
Programming!
Notice how a new line is output for each
\n escape sequence.
2.4 DISPLAYING TEXT WITH PRINTF

System.out.printf
New feature of J2SE 5.0
 Displays formatted data


9
10
System.out.printf( "%s\n%s\n",
"Welcome to", "Java Programming!" );
Format string
Fixed text
 Format specifier – placeholder for a value


Format specifier %s – placeholder for a string
20
1
// Fig. 2.6: Welcome4.java
2
// Printing multiple lines in a dialog box.
21
OUTLINE
3
4
public class Welcome4
5
{

6
// main method begins execution of Java application
7
public static void main( String args[] )
8
{
9
10
System.out.printf( "%s\n%s\n",
"Welcome to", "Java Programming!" );
Welcome4.j
ava
main
 printf

System.out.printf
displays formatted data.
11
12
} // end method main
13
14 } // end class Welcome4
Welcome to
Java Programming!

Program
output
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS

Upcoming program
Use Scanner to read two integers from user
 Use printf to display sum of the two values
 Use packages

22
1
// Fig. 2.7: Addition.java
2
// Addition program that displays the sum of two numbers.
3
import java.util.Scanner; // program uses class Scanner
4
5
public class Addition
6
{
7
// main method begins execution of Java application
8
public static void main( String args[] )
9
{
23
OUTLINE
import declaration imports class
Scanner from package
java.util.
 Addition.
java
10
// create Scanner to obtain input from command window
11
Scanner input = new Scanner( System.in );
12
13
int number1; // first number to add
14
int number2; // second number to add
15
int sum; // sum of number1 and number2
16
17
System.out.print( "Enter first integer: " ); // prompt
18
number1 = input.nextInt(); // read first number from user
19

(1 of 2)
Declare and initialize
import
variable input, 
which
is a
declaration
Scanner.
 Scanner
Declare variables
number1, number2and
nextInt
sum.
Read an integer from the
user and assign it to
number1.
20
System.out.print( "Enter second integer: " ); // prompt
21
number2 = input.nextInt(); // read second number from user
22
23
sum = number1 + number2; // add numbers
24
25
System.out.printf( "Sum is %d\n", sum ); //
26
27
} // end method main
28
29 } // end class Addition
Enter first integer: 45
Enter second integer: 72
Sum is 117
24
OUTLINE
Read an integer from the
user and assign it to
number2.the sum of the
Calculate
 Additio
display sum
variables number1 and
n.java
number2, assign result to
 (2 of 2)
sum.
Display the sum using

formatted output.
Two integers entered by the
user.

4. Addition
5. printf
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
3

import java.util.Scanner;
// program uses class Scanner
import declarations
Used by compiler to identify and locate classes used in Java
programs
 Tells compiler to load class Scanner from java.util
package


5
6
Begins public class Addition


public class Addition
{
Recall that file name must be Addition.java
Lines 8-9: begins main
25
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
10
11


// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
Variable Declaration Statement
Variables
Location in memory that stores a value
 Declare with name and type before use
 Input is of type Scanner
 Enables a program to read data for use
 Variable name: any valid identifier



Declarations end with semicolons ;
Initialize variable in its declaration
Equal sign
 Standard input object
 System.in

26
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
int number1; // first number to add
int number2; // second number to add
int sum; // second number to add
13
14
15

Declare variable number1, number2 and sum of type
int
int holds integer values (whole numbers): i.e., 0, -4, 97
 Types float and double can hold decimal numbers
 Type char can hold a single character: i.e., x, $, \n, 7
 int, float, double and char are primitive types


// first number to add
Can int
addnumber1,
comments
to describe purpose of variables
number2, // second number to add
sum; // second number to add


Can declare multiple variables of the same type in one
declaration
Use comma-separated list
27
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
17


Message called a prompt - directs user to perform an
action
Package java.lang
18

System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
Result of call to nextInt given to number1 using
assignment operator =
Assignment statement
 = binary operator - takes two operands
 Expression on right evaluated and assigned to variable
on left
 Read as: number1 gets the value of input.nextInt()

28
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
20

Similar to previous statement

21

Prompts the user to input the second integer
number2 = input.nextInt(); // read second number from user
Similar to previous statement

23

System.out.print( "Enter second integer: " ); // prompt
Assign variable number2 to second integer input
sum = number1 + number2; // add numbers
Assignment statement
Calculates sum of number1 and number2 (right hand side)
 Uses assignment operator = to assign result to variable sum
 Read as: sum gets the value of number1 + number2
 number1 and number2 are operands

29
2.5 ANOTHER JAVA APPLICATION:
ADDING INTEGERS (CONT.)
System.out.printf( "Sum is %d\n: " , sum ); // display sum
25
Use System.out.printf to display results
 Format specifier %d


Placeholder for an int value
System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );


Calculations can also be performed inside printf
Parentheses around the expression number1 +
number2 are not required
30
2.6 MEMORY CONCEPTS

Variables

Every variable has a name, a type, a size and a value

Name corresponds to location in memory
When new value is placed into a variable, replaces (and
destroys) previous value
 Reading variables from memory does not change them

31
| MEMORY LOCATION SHOWING THE NAME AND
VALUE OF VARIABLE NUMBER1.
32
FIG. 2.8
| MEMORY LOCATIONS AFTER STORING
VALUES FOR NUMBER1 AND NUMBER2.
FIG. 2.9
33
| MEMORY LOCATIONS AFTER CALCULATING AND
STORING THE SUM OF NUMBER1 AND NUMBER2.
34
FIG. 2.10
2.7 ARITHMETIC

Arithmetic calculations used in most programs

Usage
* for multiplication
 / for division
 % for remainder
 +, 

Integer division truncates remainder
7 / 5 evaluates to 1

Remainder operator % returns the remainder
7 % 5 evaluates to 2
35
Java
operation
Arithmetic Algebraic
operator
expression
Java
expression
Addition
+
f+7
f + 7
Subtraction
–
p–c
p - c
Bm
b * m
Multiplication *
Division
FIG. 2.11
/
x / y or
or x ÷ y
| ARITHMETIC OPERATORS.
x / y
36
2.7 ARITHMETIC (CONT.)

Operator precedence

Some arithmetic operators act before others (i.e.,
multiplication before addition)


Use parenthesis when needed
Example: Find the average of three variables a, b
and c
Do not use: a + b + c / 3
 Use: ( a + b + c ) / 3

37
Operator(s) Operation(s) Order of evaluation
(precedence)
FIG. 2.12
*
Multiplication
/
Division
%
Remainder
+
Addition
-
Subtraction
Evaluated first. If there are
several operators of this type,
they are evaluated from left to
right.
Evaluated next. If there are
several operators of this type,
they are evaluated from left to
right.
38
| PRECEDENCE OF ARITHMETIC OPERATORS
.
2.8 DECISION MAKING: EQUALITY AND
RELATIONAL OPERATORS

Condition


Expression can be either true or false
if statement
Simple version in this section, more detail later
 If a condition is true, then the body of the if
statement executed
 Control always resumes after the if statement
 Conditions in if statements can be formed using
equality or relational operators (next slide)

39
Standard algebraic Java equality Sample
equality or relational or relational Java
operator
operator
condition
Equality operators


Relational operators



≤
FIG. 2.14
Meaning of
Java condition
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>
<
>=
<=
x
x
x
x
x is greater than y
x is less than y
x is greater than or equal to y
x is less than or equal to y
> y
< y
>= y
<= y
| EQUALITY AND RELATIONAL OPERATORS.
40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 2.15: Comparison.java
// Compare integers using if statements, relational operators
// and equality operators.
import java.util.Scanner; // program uses class Scanner
public class Comparison
{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );


int number1; // first number to compare
int number2; // second number to compare

System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
if ( number1 == number2 )
System.out.printf( "%d == %d\n",
41
OUTLINE
Test for equality,
using
number1,display
number2 result
);
printf.
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
Compares two numbers
using relational operator
<.
if ( number1 < number2 )
System.out.printf( "%d < %d\n", number1, number2 );
Compar
ison.jav
a
(1 of 2)
1. Class
Comparison
1.1 main
1.2 Declarations
1.3 Input data
(nextInt)
1.4 Compare two
inputs using if
statements
31
32
33
34
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );
35
if ( number1 <= number2 )
36
System.out.printf( "%d <= %d\n",
37
38
39

if ( number1 >= number2 )
System.out.printf( "%d >= %d\n", number1, number2 );
40
41
Compares two numbers
operator
number1, using
number2relational
);
>, <= and >=.
42
OUTLINE
Compariso
n.java

(2 of 2)

Program output
} // end method main
42
43 } // end class Comparison
Enter first integer: 777
Enter second integer: 777
777 == 777
777 <= 777
777 >= 777
Enter first integer: 1000
Enter second integer: 2000
1000 != 2000
1000 < 2000
1000 <= 2000
Enter first integer: 2000
Enter second integer: 1000
2000 != 1000
2000 > 1000
2000 >= 1000
2.8 DECISION MAKING: EQUALITY AND
RELATIONAL OPERATORS (CONT.)





Line 6: begins class Comparison declaration
Line 12: declares Scanner variable input and assigns
it a Scanner that inputs data from the standard input
Lines 14-15: declare int variables
Lines 17-18: prompt the user to enter the first integer
and input the value
Lines 20-21: prompt the user to enter the second
integer and input the value
43
2.8 DECISION MAKING: EQUALITY AND
RELATIONAL OPERATORS (CONT.)
23
24

if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if statement to test for equality using (==)
If variables equal (condition true)
 Line 24 executes
 If variables not equal, statement skipped
 No semicolon at the end of if statement
 Empty statement
 No task is performed


Lines 26-27, 29-30, 32-33, 35-36 and 38-39

Compare number1 and number2 with the operators !=, <,
>, <= and >=, respectively
44
Operators
*
/
+
-
<
<=
==
!=
=
%
>
>=
Associativity
Type
left to right
multiplicative
left to right
additive
left to right
relational
left to right
equality
right to left
assignment
| PRECEDENCE AND ASSOCIATIVITY OF
OPERATIONS DISCUSSED.
FIG. 2.16
45