Download Lecture 3: More Java Basics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Law of large numbers wikipedia , lookup

Mathematical model wikipedia , lookup

Approximations of π wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
Lecture 3: More Java
Basics
Michael Hsu
CSULA
Recall From Lecture Two

Write a basic program in Java

The process of writing, compiling, and running a Java program

Write a String literal to standard output


System.out.println(“……”);
Naming conventions
Topics to Cover

Variables/constants

Data Type

Type Casting

Operators
animation
Trace a Program Execution
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);
}
}
4
allocate memory
for radius
radius
no value
animation
Trace a Program Execution
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);
}
}
5
memory
radius
no value
area
no value
allocate memory
for area
animation
Trace a Program Execution
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);
}
}
6
assign 20 to radius
radius
area
20
no value
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
memory
radius
area
20
1256.636
// 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);
}
}
7
compute area and assign it
to variable area
animation
Trace a Program Execution
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
double radius;
double area;
memory
radius
area
20
1256.636
// 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);
}
}
8
print a message to the
console
Variables and Constants

One of the basic building blocks of a program

Similar to variables and constants in math

Recall from lecture two:

Computer has memory addresses to store and retrieve data

Variables/constants, in the general sense, allocate memory for specific data
you’re using in a program

Example:

double radius = 0;

Allocates space to store a double, names it radius (think memory address), then
stores the value 0 at the memory address

We call the name of the variable an identifier
Identifiers


An identifier is a sequence of characters that consist of letters, digits,
underscores (_), and dollar signs ($).
Names of variables, methods, classes, etc.


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.

10
The name of a class is an identifier
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

An identifier cannot be true, false, or
null.

An identifier can be of any length.
Concept of Variables
// 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);
11
Declaring Variables
• In Java, you must declare variables before you use them
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
12
// Declare a to be a
// character variable;
Assignment and Comparison
Statements
Note: a SINGLE equal sign is assignment in Java.
To compare variables, use ==
13
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
1 == 1
// Is one equal to one?
Declaring and Initializing
in One Step
 int
x = 1;
 double
 For
d = 1.4;
now, you have to initialize all your variable
before you access them, as they are so called
“local variables” (local to the main method).
14
Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
15
Naming Convention For
Variables/Constants

For variables, use lowerCamelCase

First word starts with lower case, the rest upper case

Choose meaningful, descriptive names, usually nouns.

Capitalize all letters in constants, and use underscores to connect words. For
example, the constant PI and MAX_VALUE

More examples of constant:


HEIGHT_OF_MICHAEL

ABOGADRO_CONSTANT
Again, if you don’t pick reasonable names/follow naming conventions, I will
take off points
Before We Talk About Data Types:

Recall from lecture 2, data is stores as zeroes and ones on the computer



In binary
Bit

Unit of information

It is either 0 or 1 (on or off, true or false)

Logic gates/transistors
Bits make up binary numbers, represented with base 2
Base 10 to Base 2 (Binary) conversion
Source: http://www.wikihow.com/images/4/43/Convert-from-Decimal-to-Binary-Step-14-Version-2.jpg
Bytes

1 Byte = 8 Bit (8 digits in binary)

1 Kilobyte = 1,024 Bytes

1 Megabyte = 1,048,576 Bytes

1 Gigabyte = 1,073,741,824 Bytes

1 Terabyte = 1,099,511,627,776 Bytes

Note: powers of 2
Data Types

Recall from previous slides, when we declare variables/constants, we specify
why type it is

A String literal also has a data type: it is of type String

Different data types take up different amount of space
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
(i.e., -9223372036854775808 to 9223372036854775807)
64-bit signed
float
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit IEEE 754
double
Negative range:
-1.7976931348623157E+308 to -4.9E-324
64-bit IEEE 754
Positive range:
4.9E-324 to 1.7976931348623157E+308
Numerical Data Types Cont.

Be careful on what numeric type you use to store data


Different types take up different amounts of memory
You will most likely not use byte or short for this course

Remember that each numeric type has a set range of possible values

For now, use int for integer values, use double for decimal values
Floating Point Types

Include the types float and double

Uses scientific Notation in binary to store data

IEEE 754

These types store values with limited precision, essentially rounding to the
closest value they can hold

More Info

http://introcs.cs.princeton.edu/java/91float/
23
Floating Point Types Rounding Errors

Floating point arithmetic is not exact, as some numbers require infinite
amount of digits to be represented (like 1/10) in binary.

Example:


FloatingPointComparison.java
Lesson of the day:

Do not rely on floating point types for accurate calculations


What if we’re calculating money? Use BigDecimal
Do not do test for equality between floating point nubmers
More Data Types


boolean

Either true or false

Comparisons evaluate to boolean values

100 > 2 true

2 == 2 true
char

Single character

Set literal value using single quotes:


char exampleChar = ‘B’
You can also use ASCII values:

char exampleChar = 66

Since the variable is of chart datatype, java knows that you are using the ASCII value to refer to the
character ‘B’

As a result, ‘b’ is different from ‘B’ since they have different ASCII values.
Primitive Data Types

Predefined by the language

basic types that build up other types

In later classes, you will use primitives to create your own data types

Only the values are copied when you reassign primitive type variables to each
other


More on this later
Includes all the numeric data types mentioned in previous slides, plus boolean and
char.
Strings

A sequence of zero or more characters

You already used them in the System.out.println statements

Set values using double quotes

The ‘S’ is capitalized

It is NOT a primitive type, but a class

Will be covered later

String helloWorld = “Hello, World”;

“”
null String/empty String
Math Operations


Most of them are just like how you do it in math
int x = 1;
// declared an integer variable x, sets x to be 1

x = x + 1; // adds 1 to x

x = x * 2;

X = 2/3

x = 100.0/9.2; //Floating point division

Integer division: when all variables in the calculation are numeric nonfloating point types, the decimal portion is dropped.

// multiplies x by 2
//integer division
Example: 1/2 == 0, 20/6 == 3, 14/200 == 0
The Modulo operator

%



Performs integer division, and returns the remainder.
x =7%3

Divide 7 by 3, find the remainder, then assign value of the remainder to x

In this case x is 1
Very useful

Calculate divisibility:

If a % b == 0, then a is evenly divisible by b
How to Get Floating Point Results from
Calculations?

One or more of the operands must be of floating point type

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.
* In this case binary means “involving two operands,” not “ in base 2”
Type Casting

Converting between data types
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
char i = (char) 65; (ASCII code to char)
What is wrong?
int x = 5 / 2.0;
range increases
byte, short, int, long, float, double
31
Casting in an Augmented Expression
In Java, an augmented expression of the form x1 op= x2 is implemented as x1 =
(T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement
sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
32
Augmented Assignment Operators
33
Increment and
Decrement Operators
34
Increment and
Decrement Operators, cont.
int i = 10;
int newNum = 10 * i++;
Same effect as
int i = 10;
int newNum = 10 * (++i);
35
int newNum = 10 * i;
i = i + 1;
Same effect as
i = i + 1;
int newNum = 10 * i;
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.
36
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--;
37