0% found this document useful (0 votes)
13 views

Lecture 2 ElementaryProgramming

Uploaded by

Slum Dog
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lecture 2 ElementaryProgramming

Uploaded by

Slum Dog
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Elementary Programming

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 1
rights reserved.
Motivations
In the preceding chapter, you learned how to
create, compile, and run a Java program. Starting
from this chapter, you will learn how to solve
practical problems programmatically. Through
these problems, you will learn Java primitive data
types and related subjects, such as variables,
constants, data types, operators, expressions, and
input and output.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 2
rights reserved.
Data Types in Java

• In java we have two categories of data type:


• 1) Primitive data types
• 2) Non-primitive data types- Arrays and
Strings

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 3
rights reserved.
Primitive data types
In Java, we have eight primitive data types: boolean,
char, byte, short, int, long, float and double. Java
developers included these data types to maintain the
portability of java as the size of these primitive data
types do not change from one operating system to
another.
• byte, short, int and long data types are used for
storing whole numbers.
• float and double are used for fractional numbers.
• char is used for storing characters(letters).
• boolean data type is used for variables that holds
either true or false.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 4
rights reserved.
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

Note
IEEE 754 is a standard approved by the Institute of Electrical and Electronics Engineers for representing floating-point numbers on
computers. The standard has been widely adopted. Java uses the 32-bit IEEE 754 for the float type and the 64-bit IEEE 754 for the
double type. The IEEE 754 standard also defines special floating-point values, which are listed in Appendix E.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 5
rights reserved.
Boolean
• Boolean: holds either true of false.
class JavaExample
{ public static void main(String[] args)
{ boolean b = false;
System.out.println(b);
}
}

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 6
rights reserved.
char
• holds characters.
size: 1 bytes
class JavaExample {
public static void main(String[] args)
{ char ch = 'Z';
System.out.println(ch);
}
}

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 7
rights reserved.
Identifiers
• is a sequence of characters that consist of:
– letters
– digits
– underscores (_)
– dollar signs ($).
• must start with a letter an underscore (_), or a dollar
sign ($). It cannot start with a digit.
• cannot be a reserved words
• cannot be true, false, or null.
• can be of any length.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 8
rights reserved.
Declaring Variables
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 9
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 10
rights reserved.
Declaring and Initializing
in One Step
• int x = 1;
• double d = 1.4;

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 11
rights reserved.
Named Constants
final –datatype- -CONSTANTNAME- = -someValue-;

Examples:
final double PI = 3.14159;
final int SIZE = 3;

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 12
rights reserved.
Naming Conventions
• Choose meaningful and descriptive names.
• Variables and method names:
– Use lowercase.
– Examples:
• radius
• area
• the method computeArea.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 13
rights reserved.
Naming Conventions, cont.

• Constants:
– Capitalize all letters with underscores
– For example:
• PI
• MAX_VALUE

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 14
rights reserved.
NOTE
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy.
For example:
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1

Integers are stored precisely so calculations with


integers yield a precise integer result.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 15
rights reserved.
Exponent Operations
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 16
rights reserved.
Numeric 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 = 1000000;
double d = 5.0;

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 17
rights reserved.
Integer Literals
An integer literal can be assigned to an integer variable as long as it
can fit into the variable.
The statement:
byte b = 1000
would cause a compilation error, because 1000 cannot be stored in a
variable of the byte type.
An integer literal is of type int
has value between -231 (-2147483648) to 231–1 (2147483647)
To denote an integer literal of the long type
append it with the letter L or l.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 18
rights reserved.
Floating-Point Literals
Floating-point literals have a decimal point.
Are treated as a double type value.
For example, 5.0 a double value, not a float value.
You can make a number a float by appending the
letter f or F, and make a number a double by
appending the letter d or D.
These are float: 100.2f or 100.2F
These are double: 100.2d or 100.2D
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 19
rights reserved.
Scientific Notation
Floating-point literals can also be specified in
scientific notation, for example,
123.456 = 1.23456e+2 & 1.23456e2
0.0123456 = 1.23456e-2.
E (or e) represents an exponent and it can be
either in lowercase or uppercase.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 20
rights reserved.
Introducing Programming with an
Example
Computing the Area of a Circle
This program computes the area of the circle.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 21
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 22
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 23
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 24
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 25
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 26
rights reserved.
I made 2 versions
ComputeArea.java
ComputeAreaInWindow.java

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 27
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 28
rights reserved.
import javax.swing.JOptionPane;

public class ComputeAreaInWindow {


/** 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 in a window


JOptionPane.showMessageDialog(null,"radius " + radius + " is " + area,"Circle Area with
",JOptionPane.INFORMATION_MESSAGE);

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 29
rights reserved.
Now let’s enter some data from the console

1.import java.util.scanner;
Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the methods:


nextByte(), nextShort(), nextInt(), nextLong(),
nextFloat(), nextDouble(), or nextBoolean(),
next(),nextLine()

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 30
rights reserved.
Two examples

ComputeAreaWithConsoleInput.java
ComputeAverage.java

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 31
rights reserved.
import java.util.Scanner; // Scanner is in the java.util package

public class ComputeAreaWithConsoleInput {


public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

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

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 32
rights reserved.
import java.util.Scanner; // Scanner is in the java.util package

public class ComputeAverage {


public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display result
System.out.println("The average of " + number1 + " " + number2
+ " " + number3 + " is " + average);
}
}

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 33
rights reserved.
Types of Operator in Java

• 1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement
Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 34
rights reserved.
Basic Arithmetic Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 35
rights reserved.
Integer Division

+, -, *, /, and %

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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 36
rights reserved.
Remainder Operator
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 37
rights reserved.
Problem: Displaying Time
Write a program that obtains hours and
minutes from seconds.
import java.util.Scanner;

public class DisplayTime {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: ");
int seconds = input.nextInt();

int minutes = seconds / 60; // Find minutes in seconds


int remainingSeconds = seconds % 60; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes +
" minutes and " + remainingSeconds + " seconds");
}
}
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 38
rights reserved.
Arithmetic Expressions
3+ 4 x 10( y−5 )( a +b +c ) 4 9+ x
− + 9( + )
5 x x y

is translated to

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

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 39
rights reserved.
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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 40
rights reserved.
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:

celsius = (5.0 / 9) * (fahrenheit – 32)

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 41
rights reserved.
import java.util.Scanner;

public class FahrenheitToCelsius {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter a degree in Fahrenheit: ");


double fahrenheit = input.nextDouble();

// Convert Fahrenheit to Celsius


double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius");
}
}

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 42
rights reserved.
Shortcut Assignment Operators
(Pick one style and stick with it)
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 43
rights reserved.
More shortcuts
Increment and Decrement Operators
(Pick one style and stick with it)

Operator Name Description


++var preincrement The expression (++var) increments var by 1 and evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 44
rights reserved.
More shortcuts
Increment and Decrement Operators.

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, Ninth Edition, (c) 2013 Pearson Education, Inc. All 45
rights reserved.
More shortcuts
Increment and Decrement Operators
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.

The main idea here is to AVOID them!

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 46
rights reserved.
Assignment Expressions and Assignment
Statements
Prior to Java 2, all the expressions can be used as
statements. Since Java 2, only the following types of
expressions can be statements:
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 47
rights reserved.
Logical Operators
Logical operators in java are: &&, ||, !
Let’s say we have two boolean variables b1 and b2.
•b1&&b2 will return true if both b1 and b2 are true else it would return
false.
•b1||b2 will return false if both b1 and b2 are false else it would return
true.
•!b1 would return the opposite of b1, that means it would be true if b1 is
false and it would return false if b1 is true.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 48
rights reserved.
Comparison(Relational) operators

We have six relational operators in Java: ==, !=, >, <, >=,
<=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of
operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right
side.
<= returns true if left side is less than or equal to right side.

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 49
rights reserved.
Bitwise Operators
• There are six bitwise Operators: &, |, ^, ~, <<, >>
• num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
• 0 000 0 0 1 0
• num1 & num2: 2
• num1 | num2: 31
• num1 ^ num2: 29
• ~num1: -12
• num1 << 2: 44
• num1 >> 2: 2

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All 50
rights reserved.

You might also like