• 沒有找到結果。

Java Programming

N/A
N/A
Protected

Academic year: 2022

Share "Java Programming"

Copied!
52
0
0

加載中.... (立即查看全文)

全文

(1)

Java Programming

Zheng-Liang Lu

Department of Computer Science & Information Engineering National Taiwan University

Java 361 Summer 2022

(2)

1 class Lecture2 {

2

3 "Data types, Variables, and Operators"

4 5 }

6

7 // Keywords:

8 byte, short, int, long, char, float, double, boolean, true, false,

9 import, new

Zheng-Liang Lu Java Programming 41

(3)

Example

Given the circle radius, say 10, determine the area.

• Input: how to store the value of the circle radius?

• Algorithm: how to compute the resulting area?

• Output: how to show the result?

Zheng-Liang Lu Java Programming 42

(4)

1 public class ComputeAreaDemo {

2

3 public static void main(String[] args) {

4

5 // INPUT

6 int r = 10;

7

8 // ALGORITHM

9 double A = r * r * 3.14;

10

11 // OUTPUT

12 System.out.println(A);

13

14 }

15 }

• In Line 6, we declare the variable r an integer (int) with its initial value 10.

• In Line 9, we store the circle area in the variable A which is decimal (double).

• The keywords int anddoubleare two ofprimitive types.

Zheng-Liang Lu Java Programming 43

(5)

Simple Analog: Variable ≈ Box

Zheng-Liang Lu Java Programming 44

(6)

Variable Declaration

• First, we name the variable, say price.

• We then determine a proper type for price, for example,

1 ... // ignore the common part; the same applies hereinafter

2

3 int price; // price is a variable declared an integer type

4 5 ...

• The rule of variable declaration looks like data-type variable-name;

For example, String[] args in the main method.

• This rule is similar to C, C++, and C#.

Zheng-Liang Lu Java Programming 45

(7)

Naming Rules

• The naming rule excludes the following cases:

cannot start with a digit;

cannot be any reserved word(see the next page);

cannot include any blank between letters;

cannot contain operators, like +, −, ∗, /.

• Note that Java iscase-sensitive, for example, the letter A is different from the letter a.

• These rules are also applicable to methods, classes, etc.

• These rules, again, are similar to C, C++, and C#.

Zheng-Liang Lu Java Programming 46

(8)

Reserved Words

1

• Coverage: 44 / 50 = 88%.

1Based on JDK8. You can check the language changeshere.

Zheng-Liang Lu Java Programming 47

(9)

Things behind Variable Declaration

• Variable declaration asks to allocatea proper memory space to the variable (box).

• The size of the allocated space depends on its data type.

• We count the space size inbitsor bytes.

A bit presents a binary digit.

1 byte is equal to 8 bits.

• For example, an int value occupies 32 bits (or 4 bytes) in the memory.

Zheng-Liang Lu Java Programming 48

(10)

Variable Name as Alias of Memory Address

• Literals that start with 0x are hexadecimal (hex) integers.2

• Hex numbers are widely used to represent, say addresses and colors.3

2Seehttps://en.wikipedia.org/wiki/Hexadecimal.

3Tryhttps://htmlcolorcodes.com/.

Zheng-Liang Lu Java Programming 49

(11)

Data Types

• Every variable needs a type.

• Also, every statement (or expression) has a final type.

• The notion of data types is vital to programming languages.

I would say that, the role of data typesacts like the physics law in the universe.

• Java is a static-typedlanguage, similar to C, C++, and C#.

A variable is available after declaration and cannot changed in runtime.

• We now proceed to introduce the two categories of data types: primitivetypes, and referencetypes.

Zheng-Liang Lu Java Programming 50

(12)

Type System: Overview

Type System

References Primitives

Numbers void boolean

Integers byte

short int

long char

Floats float double

String · · ·

Zheng-Liang Lu Java Programming 51

(13)

Digression: Binary System

5

• We have been familiar with the decimal system. (Why?)

• Computers know only the binary system because of its nature:

only two states, onandoff.4

• However, both systems are equivalent except that they differ in representations.

• For example,

99910= 9 ×102+ 9 ×101+ 9 ×100.

• Similarly,

1112 = 1 ×22+ 1 ×21+ 1 ×20 = 710.

• In most cases, we don’t need to deal with binary codes directly because we are using high-level languages.

4How about the quantum computers? Spin up and down. SeeQubit.

5SeeHow Exactly Does Binary Code Work?by Jos´e Am´erico NLF Freitas.

Zheng-Liang Lu Java Programming 52

(14)

Integers

Name Bits Range Approx. Range

byte 8 0 to 255 <= 255

short 16 −32768 to 32767 ±3 × 104

int 32 −2147483648 to 2147483647 ±2 × 109

long 64 −9223372036854775808 to 9223372036854775807 ±9 × 1018

• The range is limited to its finite size of storage.

• If a value is out of the feasible range, an overflow occurs.

• The inttype is the most used unless otherwise noted.

• If you want to write down along-type literal, say 9876543210, you should write 9876543210L, where the suffixLindicates thelong type.

Zheng-Liang Lu Java Programming 53

(15)

Floating-Point Numbers

Name Bits Range

float 32 1.4e −045 to 3.4e +038

double 64 4.9e −324 to 1.8e +308

• The notation e (or E ) represents the scientific notation, based 10.

For example, 1e2 = 100 and −1.8e −3 = −0.0018.

• We use floating-point numbers when evaluating expressions that require fractional precision, say sqrt() and log().

• In this sense, integers seem redundant because floating-point numbers could represent integers and also decimals.

• However, the floating-point system can only approximate the real-number arithmetic! (Why?)

Zheng-Liang Lu Java Programming 54

(16)

Machine Epsilon

7

1 ...

2

3 System.out.println(0.5 − 0.1 − 0.1 − 0.1 − 0.1 − 0.1);

4 // Output? Why?

5 6 ...

• We relieve the machine epsilon by proper algorithm design.

• In critical applications, we even avoid to use the floating-point numbers but integers.6

6Also readhttps://news.cnyes.com/news/id/3680649.

7SeeMachine Epsilonandhttps://0.30000000000000004.com/.

Zheng-Liang Lu Java Programming 55

(17)

Another Example

1 ...

2 System.out.println(3.14 + 1e20 − 1e20); // Output?

3 System.out.println(3.14 + (1e20 − 1e20)); // Output?

4 ...

• Floating-point arithmetic (FP)8 is arithmetic using formulaic representation of real numbers as an approximation to support a trade-off between range and precision.9

8Seehttps://en.wikipedia.org/wiki/Floating-point arithmetic.

9You may also read this article

What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Zheng-Liang Lu Java Programming 56

(18)

IEEE Floating-Point Representation

10

x = (−1)s× M × 2E

• The sign bit s determines whether the number is negative (s = 1) or positive (s = 0).

• The mantissa M is a fractional binary number that ranges either between 1 and 2 − ε, or between 0 and 1 − ε.

• The exponent E weights the value by a (possibly negative) power of 2.

10William Kahan (1985): IEEE754; Also seeDouble-Precision FP Format.

Zheng-Liang Lu Java Programming 57

(19)

Illustration

• That is why we call a doublevalue.

• Double values have at least 16 significant digits in decimal!

Zheng-Liang Lu Java Programming 58

(20)

Assignments

• The equal sign (=) is used as theassignment operator.

• An assignment statement designates a value to the variable.

1 int x, y; // Variable declaration.

2 x = 0; // Assign 0 to x.

3 y = x + 1; // y = 1 (trivial?)

4 x = x + 1; // Is this weird?

• Direction: from the right-hand side to the left-hand side.11

Copy a value from the right-hand side (value or expression) to the space indicated by the variable in the left-hand side.

• You cannot write codes like 1 = x because 1 cannot be resolved to a memory space.

11The variable x can be a l-value and r-value, but 1 and other numbers can be only r-value but not l-value. SeeValue.

Zheng-Liang Lu Java Programming 59

(21)

Two-Before Rule

1 int x;

2 ...

3 x = 0;

4 ...

5 x = x + 1;

• Rule 1: a variable must bedeclaredbefore any assignment.

• Rule 2: a variable must beinitializedwith a value before being used.

Zheng-Liang Lu Java Programming 60

(22)

Arithmetic Operators

Operator Operation Example Result

+ Addition 12 + 34 46

− Subtraction 56 − 78 −22

∗ Multiplication 90 * 12 1080

/ Division 3.0 / 2.0 1.5

% Remainder 20 % 3 2

• What if 3 / 2?

• The result depends on the types of its operands!

Zheng-Liang Lu Java Programming 61

(23)

Concept Check

1 ...

2 double x = 1 / 2;

3 System.out.println(x); // Output? Why?

4 ...

• What is the output?

Zheng-Liang Lu Java Programming 62

(24)

Two of Program Stages

• Compile time(or compilation period):

memory allocation for x ,

constant literals (in this case 1, 2),

linking the println method, etc.

• Run time (or execution period):

execution of arithmetic operation

output the result, etc.

Zheng-Liang Lu Java Programming 63

(25)

Compatibility and Type Conversion

• If a type is compatible to another, then the compiler will perform the implicit conversion.

For example, the integer 1 is compatible to adoublevalue 1.0.

• Clearly, Java is aweakly-typed language.12

• However, there is no automatic conversion fromdoubleto int.

(Why?)

• To do so, you must use acast, which performs an explicit conversion.

• Similarly, along value is not compatible toint.

12SeeStatically vs. Dynamically Typed Languages.

Zheng-Liang Lu Java Programming 64

(26)

Casting

1 ...

2 int x = 1;

3 double y = x; // Compatible; implicitly converted.

4 x = y; // Not allowed unless casting.

5 x = (int) y; // Succeeded!!

6 ...

• Note that the Java compiler does onlytype checking but no real execution before compilation.

• In other words, the actual values of x and y are unknown until the program is executed.

Zheng-Liang Lu Java Programming 65

(27)

Compatibility and Type Conversion (Concluded)

• Small-size types → large-size types.

• Small-size types 8 large-size types (need a cast).

• Simple types → complicated types.

• Simple types 8 complicated types (need a cast).

Zheng-Liang Lu Java Programming 66

(28)

Text: Characters & Strings

• Each character is encoded in a sequence of 0’s and 1’s.

For example, ASCII. (See the next page.)

• The chartype denotes characters, which are represented in Unicode, a 16-bit unsigned value.13

• However, we often use String to present texts, as shown before.

• As an analogy, a molecule (string) consists of atoms (characters).14

13Unicode defines a fully international character set that can represent all of the characters found in all human languages.

14A String object comprises characters equipped with plentiful tools.

Zheng-Liang Lu Java Programming 67

(29)

ASCII (7-bit version)

Zheng-Liang Lu Java Programming 68

(30)

Example

1 ...

2 char c = ’a’; // A char value should be single−quoted.

3 System.out.println(c + 1); // Output 98!! (why?)

4 System.out.println((char)(c + 1)); // Output b.

5

6 String s = "Java"; // A string should be double−quoted.

7 System.out.println(s + 999); // Output Java999.

8 ...

• We may apply arithmetic operators to characters, say Line 4 for some purposes.15

• In Line 7, the result of applying the + operator to string is totally different from Line 3 & 4. (Why?)

15For example,https://en.wikipedia.org/wiki/Cryptography.

Zheng-Liang Lu Java Programming 69

(31)

Boolean Values

17

• Programs are expected to do decision makingby itself, say self-driving cars.16

• Java provides theboolean-type flow controls (branching and iteration).

• The booleantype allows only two values: trueand false.

• Note thatboolean values cannotbe cast to non-booleantype, and vice versa. (Why?)

16Seehttps://www.google.com/selfdrivingcar/.

17George Boole (1815–1864) is the namesake of the branch of algebra known as Boolean algebra. Seehttps://en.wikipedia.org/wiki/George Boole.

Zheng-Liang Lu Java Programming 70

(32)

Relational Operators

Operator Name

< less than

<= less than or equal to

> greater than

>= greater than or equal to

== equal to

!= not equal to

• Relational operators take two operands and return a boolean value.

• Note that the mathematical equality operator is ==, not = (assignment).

Zheng-Liang Lu Java Programming 71

(33)

Example

1 ...

2 int x = 2;

3 System.out.println(x > 1); // Output true.

4 System.out.println(x < 1); // Output false.

5 System.out.println(x == 1); // Output false.

6 System.out.println(x != 1); // Output true.

7 System.out.println(1 < x < 3); // Sorry?

8 ...

• In Line 7, 1 < x < 3 is syntactically wrong.

• You need to split a complex statement into several basic statements and joint them by properlogical operators.

• For example, 1 < x < 3 should be 1 < x && x < 3, where && represents the AND operator.

Zheng-Liang Lu Java Programming 72

(34)

Conditional Logical Operators

18

Operator Name

! NOT

&& AND

|| OR

∧ EXCLUSIVE-OR

• We often use XOR to denote the exclusive-or operator.

18Thebit-wiseoperators are ignored in my course because most of Java programmers do not use those directly. SeeBitwise and Bit Shift Operatorsif necessary.

Zheng-Liang Lu Java Programming 73

(35)

Truth Table

• Let X and Y be two boolean variables.

• Then the truth table for logical operators is shown below:

X Y !X X&&Y X k Y X ∧Y

T T F T T F

T F F F T T

F T T F T T

F F T F F F

• Note that basic instructions of computers, such as arithmetic operators, are implemented by Boolean logic.19

For example, 1-bit adder can be implemented by using the XOR operator. (Try!)

19Can you image that the combination of these very basic elements (0, 1, AND, OR, NOT) with jumps producesAlphaGowhich beat human beings in 2016.

Zheng-Liang Lu Java Programming 74

(36)

“Logic is the anatomy of thought.”

– John Locke (1632–1704)

“This sentence is false.”

– anonymous

“I know that I know nothing.”

– Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than any other person because he does not imagine that he knows what he does not know.)

Zheng-Liang Lu Java Programming 75

(37)

Arithmetic Compound Assignment Operators

• For simplicity, let x and k be any number.

Operator Description x ++ Increment by one

x + = k Cumulative increment by k x − = k Cumulative subtraction by k x ∗ = k Cumulative multiplication by k x / = k Cumulative division by k x % = k Cumulative modulus by k x −− Decrement by one

Zheng-Liang Lu Java Programming 76

(38)

Example: Integers

1 ...

2 int x = 1;

3 System.out.println(x); // Output 1.

4

5 x = x + 1;

6 System.out.println(x); // Output 2.

7

8 x += 2;

9 System.out.println(x); // Output 4.

10

11 x++; // Equivalent to x += 1 and x = x + 1.

12 System.out.println(x); // Output 5.

13 ...

Zheng-Liang Lu Java Programming 77

(39)

Example: Characters and Strings

• Some of the aforesaid operators are also applicable to char values and String objects.

• For example,

1 ...

2 char x = ’a’;

3 x += 1;

4 System.out.println(x); // Output b.

5 x++;

6 System.out.println(x); // Output c.

7

8 String y = "Java";

9 y += 999

10 System.out.println(y); // Output Java999.

11 ...

Zheng-Liang Lu Java Programming 78

(40)

Discussion: ++x vs. x++

1 ...

2 int x = 0;

3 int y = ++x;

4 Console.WriteLine(y); // Output 1.

5 Console.WriteLine(x); // Output 1.

6

7 int w = 0;

8 int z = w++;

9 Console.WriteLine(z); // Output 0.

10 Console.WriteLine(w); // Output 1.

11 ...

• x++ first returns the old value of x and then increments itself.

• Instead, ++x first increments itself and then returns the new value of x .

• We will use these notations very often.

Zheng-Liang Lu Java Programming 79

(41)

Operator Precedence

20

20See Table3-10 in YDL, p. 116.

Zheng-Liang Lu Java Programming 80

(42)

Tip: Using Parentheses

• The program always evaluates the expression inside of parentheses first.

• If necessary, using parentheses in expressions could change the natural order of precedence among the operators.

Zheng-Liang Lu Java Programming 81

(43)

Scanner: Example of Reference Types

• To reuseyour program, it is inconvenient to modify and recompile the source code for every radius.

• Reading inputs from the user’s keyboard in the console is the easiest way to interact with programs.

• Java provides the Scanner object with easy-to-use input methods.

• Note that System.in refers to the standard input device, by default, the keyboard.

Zheng-Liang Lu Java Programming 82

(44)

Example

1 import java.util.Scanner;

2 ...

3 // Create Scanner object to receive data from keyboard.

4 Scanner input = new Scanner(System.in);

5

6 // INPUT

7 System.out.println("Enter r?");

8 int r = input.nextInt(); //

9

10 // ALGORITHM

11 double A = r * r * 3.14;

12

13 // OUTPUT

14 System.out.println(A);

15 input.close(); // Cleanup: reclaim the resource.

16 ...

Zheng-Liang Lu Java Programming 83

(45)

Discussions (1/2)

• In Line 1, we include the Scanner class, which belongs to the java.util package, by using theimport statement.

We put theseimportstatements in the beginning of the file.

Note that we can’t leave theseimportstatements in anyclass.

• In Line 4, thenewoperator followed by Scanner is to create a Scanner object.

• This object works as an agent between the keyboard and your program.

• In Line 9, the nextInt method of Scanner is used to convert the input to anint value.

Zheng-Liang Lu Java Programming 84

(46)

Discussions (2/2): General Concepts

• All runtime objects arecreated dynamically and resided in the heap. (See the figure in the next page.)

• Before manipulating the Scanner object, its addressis assigned to the variable input, which is allocated in thestack.

• Hence input is called areference to the Scanner object.21

• Clearly, the memory contains human data and also references (i.e., memory addresses).

21If you have programming experiences in C/C++, then this reference is similar to the concept ofpointers.

Zheng-Liang Lu Java Programming 85

(47)

Illustration: Simplified Memory Model

Zheng-Liang Lu Java Programming 86

(48)

Methods Provided by Scanner

22

22See Table 2-1 in YDL, p. 38.

Zheng-Liang Lu Java Programming 87

(49)

Exercise: Body Mass Index (BMI)

Write a program to take user name, height (in cm), weight (in kgw) as input, and then output the user name attached with his/her BMI, which is

BMI = weight height2.

• Be careful about unit conversion!

Zheng-Liang Lu Java Programming 88

(50)

1 ...

2 Scanner input = new Scanner(System.in);

3

4 // INPUT

5 System.out.println("Enter your name?");

6 String name = input.nextLine();

7

8 System.out.println("Enter your height (cm)?");

9 double height = input.nextDouble();

10

11 System.out.println("Enter your weight (kgw)?");

12 double weight = input.nextDouble();

13

14 // ALGORITHM

15 double bmi = 10000 * weight / height / height;

16

17 // OUTPUT: name (bmi)

18 System.out.println(name + " (" + bmi + ")");

19 ...

• Make sure that you understand Line 18.

Zheng-Liang Lu Java Programming 89

(51)

Exercise: Two Descriptive Statistics

Write a program to take 3 numbers as user’s input and output the arithmetic average with its standard deviation.

• Let a, b, c be the doublevariables.

• Then its standard deviation is

rP(xi − x)2

3 ,

where xi = {a, b, c} and x = (a + b + c) / 3.

• You may use two of Math methods:23 Math.pow(doublex , doubley) for xy and Math.sqrt(doublex) for√

x .

23Seehttps://docs.oracle.com/javase/tutorial/java/data/beyondmath.html

Zheng-Liang Lu Java Programming 90

(52)

1 ...

2 // INPUT

3 Scanner input = new Scanner(System.in);

4 System.out.println("a = ?");

5 double a = input.nextDouble();

6 System.out.println("b = ?");

7 double b = input.nextDouble();

8 System.out.println("c = ?");

9 double c = input.nextDouble();

10 input.close();

11

12 // ALGORITHM

13 double mean = (a + b + c) / 3;

14 double std = Math.sqrt((Math.pow(a − mean, 2) +

15 Math.pow(b − mean, 2) +

16 Math.pow(c − mean, 2)) / 3);

17

18 // OUTPUT

19 System.out.println("Mean = " + mean);

20 System.out.println("Std = " + std);

21 ...

Zheng-Liang Lu Java Programming 91

參考文獻

相關文件

The origami patterns from previous works were intended to be assembled by hand and have folds that are 

This is a reflection of the fact that the method enforces the equation element- by-element and of the use of the numerical trace.. In our simple setting, this

Then we can draw a right triangle with angle θ as in Figure 3 and deduce from the Pythagorean Theorem that the third side has length.. This enables us to read from the

The sample point can be chosen to be any point in the subrectangle R ij , but if we choose it to be the upper right-hand corner of R ij [namely (x i , y j ), see Figure 3],

• The Java programming language is based on the virtual machine concept. • A program written in the Java language is translated by a Java compiler into Java

A constant state u − is formed on the left side of the initial wave train followed by a right facing (with respect to the velocity u − ) dispersive shock having smaller

Bootstrapping is a general approach to statistical in- ference based on building a sampling distribution for a statistic by resampling from the data at hand.. • The

Now, nearly all of the current flows through wire S since it has a much lower resistance than the light bulb. The light bulb does not glow because the current flowing through it