Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 48

Topic 2: Elementary Programming

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Java Comments
 Comments can be used to explain Java code, and to make
it more readable. It can also be used to prevent execution
when testing alternative code.
– Single-line Comments
– Multi-line comments

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
2
Single-line Comments
 Single-line comments start with two forward slashes (//).
 Any text between // and the end of the line is ignored by Java (will
not be executed).
 This example uses a single-line comment before a line of code:

// This is a comment
 This example uses a single-line comment at the end
System.out.println("Hello");
of a line of code:

System.out.println("Hello World"); // This is a comment

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
Multi-line comments
 Multi-line comments start with /* and ends with */.
 Any text between /* and */ will be ignored by Java.
 This example uses a multi-line comment (a comment block) to explain
the code:

/* The code below will print the words Hello World to


the screen, and it is amazing */
System.out.println("Hello World");
 Single or multi-line comments?
– It is up to you which you want to use.
– Normally, we use // for short comments, and /* */ for longer.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
Java Variables
 Variables are containers for storing data values.
 In Java, there are different types of variables, for example:
– String - stores text, such as "Hello". String values are surrounded
by double quotes
– int - stores integers (whole numbers), without decimals, such as
123 or -123
– float - stores floating point numbers, with decimals, such as
19.99 or -19.99
– char - stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
– boolean - stores values with two states: true or false

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Primitive Data Types
 A primitive data type specifies the size and type of variable values, and it has no additional
methods.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6
Numerical Data Types
Name Range Storage Size

byte –27 to 27 – 1 (-128 to 127) 8-bit signed

short –215 to 215 – 1 (-32768 to 32767) 16-bit signed

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
Number Literals
A literal is a constant value that appears directly in the
program. For example, 34, 1,000,000, and 5.0 are literals in
the following statements:

int i = 34;
long x = 1000000L;
float f = 5.75f;
double d = 19.99d;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);

Alternatively, you can use ASCII values to display certain characters:


Example
char a = 65, b = 66, c = 67;
System.out.println(a);
System.out.println(b);
System.out.println(c);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);

The String type is so much used and integrated in Java, that some call it "the
special ninth type".

A String in Java is actually a non-primitive data type, because it refers to an


object. The String object has methods that are used to perform certain
operations on strings. Don't worry if you don't understand the term "object"
just yet. We will learn more about strings and objects in a later chapter.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
Java Identifiers
 All Java variables must be identified with unique names.
 These unique names are called identifiers.
– An identifier is a sequence of characters that consist of letters, digits,
underscores (_), and dollar signs ($).
– An identifier must start with a letter, an underscore (_), or a dollar
sign ($). It cannot start with a digit.
– An identifier cannot be a reserved word (like int, boolean ).
– An identifier can be of any length.
– Identifiers are case sensitive ("myVar" and "myvar"
are different variables)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
Naming Conventions
 Choose meaningful and descriptive names.
 Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first
word, and capitalize the first letter of each
subsequent word in the name. For example, the
variables radius and area, and the method
computeArea.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Naming Conventions (Cont..)
 Class names:
– Capitalize the first letter of each word in the name. For
example, the class name ComputeArea.

 Constants:
– Capitalize all letters in constants, and use underscores
to connect words. For example, the constant PI and
MAX_VALUE

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
Declaring (Creating) Variables
Syntax:

type variable;
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
Declaring and Initializing in One
Step
 Syntax:
type variable = value;

int x = 1;
double d = 1.4;
float myFloatNum = 5.99f;
char myLetter = ‘S';
boolean myBool = true;
String myName = “Sara";

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
Declaring and Initializing
in One Step
 if you assign a new value to an existing
variable, it will overwrite the previous value:

int myNum = 15;


myNum = 20; // myNum is now 20

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
Display Variables
String name = “Sara";
System.out.println("Hello " + name);

String firstName = “Sara";


String lastName = “Ali";
String fullName = firstName + lastName;
System.out.println(fullName);
int x = 5;
int y = 6;
System.out.println(x + y);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
Display Variables (Cont.)
 To combine both text and a variable, use
the + character.
 You can also use the + character to add a variable to
another variable.
 For numeric values, the + character works as a
mathematical operator.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
Declare Many Variables

int x = 5, y = 6, z = 50;
System.out.println(x + y + z);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
Example: Computing the Area of a Circle
public class ComputeArea {
/* Main method */
public static void main(String[] args) {
double radius;
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
animation

Trace a Program Execution


allocate memory
public class ComputeArea {
for radius
/** Main method */
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
animation

Trace a Program Execution


public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area; area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign
// Compute area it to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Example
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
Final Variables/Named Constants
 However, you can add the final keyword if you don't
want others (or yourself) to overwrite existing values
(this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

SIZE = 20; // will generate an error:


cannot assign a value to a final variable

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the method nextDouble() to obtain to a double


value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();

import java.util.*;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
Reading Numbers from the
Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();

Method Description

nextByte() reads an integer of the byte type.


nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
Java Operators
 Operators are used to perform operations on
variables and values. Examples:
int x = 100 + 50;

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
Java Operators (Cont..)
 Java divides the operators into the following
groups:
– Arithmetic operators
– Assignment operators
– Comparison operators
– Logical operators
– Bitwise operators

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Arithmetic Operators

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
Integer Division

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is always
1. So you can use this property to determine whether a number
is even or odd. Suppose today is Saturday and you and your
friends are going to meet in 10 days. What day is in 10
days? You can find that day is Tuesday using the following
expression:

Saturday is the 6th day in a week


A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Increment and
Decrement Operators

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
Increment and
Decrement Operators (Cont..)

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Increment and
Decrement Operators (Cont..)
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read. Avoid using these operators in expressions
that modify multiple variables, or the same variable for
multiple times such as this: int k = ++i + i.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
Java Assignment Operators
 Assignment operators are used to assign values to
variables. In the example below, we use the
assignment operator (=) to assign the value 10 to a
variable called x: int x = 10;

 The addition assignment operator (+=) adds a value


to a variable:
int x = 10;
x += 5;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Java Assignment Operators
(Cont..)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
Arithmetic Expressions

is translated to 3  4 x  10( y  5)(a  b  c )  9( 4  9  x )


5 x x y

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
How to Evaluate an Expression
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression. 3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
Numeric Type Conversion
Consider the following statements:

byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:

1. If one of the operands is double, the other is


converted into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
Type Casting
 Type casting is when you assign a value of one primitive data
type to another type.
 In Java, there are two types of casting:
– Widening Casting (automatically) - converting a smaller type to a larger type
size
 byte -> short -> char -> int -> long -> float -> double

– Narrowing Casting (manually) - converting a larger type to a smaller size


type
 double -> float -> long -> int -> char -> short -> byte

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
Type Casting
Implicit casting (done automatically)
double d = 3; (type widening)

Explicit casting (done manually)


int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)

What is wrong? int x = 5 / 2.0;

range increases

byte, short, int, long, float, double

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
Widening Casting
Widening casting is done automatically when passing a
smaller size type to a larger size type:
int myInt = 9;

// Automatic casting: int to double


double myDouble = myInt;

System.out.println(myInt); //Outputs 9 System.out.println(myDouble); //Outputs 9.0

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
47
Narrowing Casting
Narrowing casting must be done manually by placing the
type in parentheses in front of the value:
double myDouble = 9.78d;

// Manual casting: double to int


int myInt = (int) myDouble;

System.out.println(myDouble); //Outputs 9.78 System.out.println(myInt); //Outputs 9

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48

You might also like