[Java] Java371 Lecture 1 & Lecture 2
This document is a class note about Java Programming taughted by Mr.Lu.
2022/10/29
It may take 10000 hours, more or less; it is never too late.
How to Execute Programs
電腦底層使用 2 進位儲存資料,而在現實中的應用包括 8 進位、16 進位等,若是以 16 進位為例,在 8 個位元組會組成兩個 16 進位的數字,總共有 256 種可能,所能表示的最大數(00~FF),像是色彩碼就常常以這樣表示,ex. #00ffee。
這些 16 進位的數值分別代表指令和資料,指令就是機械碼,資料則有很多種(字串、數字、符號)會被轉成 16 進位存到底層,透過 CPU 分辨資料和指令,指令的話 CPU 會執行,資料則是看各程式如何處理。
看不懂的機械碼會載入到記憶體(內存-RAM),因為 RAM 存取速度比硬碟快很多,故先將程式載入到 RAM 才跑得順,接著 CPU 會從 RAM 排程抽取指令來執行,CPU 有 6 個主要組成元素: ALUs, registers, control units, cache, buses, and clock.
程式執行後的結果會先儲存回 RAM,再輸出到硬碟與其他輸出裝置。
CPU 與記憶體(Memory)的運作機制: https://sites.google.com/site/nutncsie10412/ge-ren-jian-jie/ji-yi-ti
PTT 討論串:https://www.ptt.cc/man/ask-why/D4D5/D143/M.1245837202.A.529.html
Programming Languages
程式語言是用來與機器溝通的人工語言,透過語意化和指令來控制機器的行為,而每個語言有其被發明出來的背景。
- Gen 1: machine code.
- Gen 2: assembly code.
- Gen 3: high-level programming languages.
- For example, C, C++, Java, Python.
- Gen 4: SQL.
Algorithm
演算法是指處理問題的良好邏輯,像是一種配方或是食譜用來料理問題。透過演算法與程式,我們放入 input,產出正確的 output。
Ex. Largest Number
- Let A be a nonempty list of any real numbers.
- Now try to propose an algorithm to find the largest number for any list of numbers.
Input: A Algorithm: your work here... Output: the largest number is A.
- For example, assume that A = {1, 7, 9, -2, 4}.
- It is clear that the answer is 9.
// pseudo code
let max = A[1];
for (let i = 0; i < A.length; i++) {
if (A[i] > max) {
max = A[i];
}
}
return max;
About Java
- Java supporting object-oriented programming(OOP) paradigm.
- Java was released back in 1995, maintained by Oracle(ORCL) after the year of 2010.
- Java is widely used in web apps(especially the back-end services), mobile apps and embedded systems.
Java Virtual Machine (JVM)
- JVM is a software program, not a physical machine.
- JVM translates Java bytecodes into machine codes which can be executed by the host platform.(Ex. Linux, Windows and MacOS...)
- JVM verifies all bytecodes before the program is executed, so that no user program can crash the host machine.
Java Virtual Machine specification https://docs.oracle.com/javase/specs/jvms/se17/jvms17.pdf
First Program
public class HelloWorldDemo {
public static void main (String[] args) {
// Print "Hello, Java." on the screen.
System.out.println("Hello, Java.");
}
}
- class: define a new class.
- public: accessible to anyone.
- static: can be called without having any object.
- void: no return value.
Discussions
- A class is an entity of Java programs.
- A Java program can consist of many classes.
- To be executable, a program needs one special methed called the main method as the entry point of the program.
- System.out refers to the standard output device, say the monitor screen.
- The println method is used to output the string you offer.
- Every statement should end with a semicolon (;).
- The only public class should have the same name as the filename.
- For example, the public HelloWorldDemo class should be in the source file whose filename must be HelloWorldDemo.java.
- Note that you cannot have more than one public class in single java file.
2022/10/30 Data types, Variables, and Operators
練習題
Q: Given the circle radius, say 10, determine the area.
public class ComputeAreaDemo {
public static void main (String[] args) {
int r = 10;
double A = r * r * 3.14;
System.out.println(A);
}
}
Naming Rules
- The naming rule excludes the following cases:
- cannot start with a digit.
- cannot be any reserved word.
- cannot include any blank between letters.
- cannot contain operators, like +, -, *, /.
- Note that Java is case-sensitive, for example, the letter A is different from the letter a.
- These rules are also applicable to methods, classes, etc.
Things behind Variable Declaration
- Variable declaration asks to allocate a proper memory space to the variable(box).
- The size of the allocated space depends on its data type.
- We count the space size in bits or bytes.
- A bit presents a binary digit.
- 1 byte is equal to 8 bits.
Data Types
- Every variable needs a type.
- Also, every statement (or expression) has a final type.
- Java is a static-typed language, a variable is available after declaration and cannot changed in runtime.
Q. What is the difference between primitive and reference type?
Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable.
Integers
Name | Bits | Range |
---|---|---|
byte | 8 | <= 255 |
short | 16 | ±3 × 10 的 4 次方 |
int | 32 | ±2 × 10 的 9 次方 |
long | 64 | ±9 × 10 的 18 次方 |
- The range is limited to its finite size of storage.
- If a value is out of the feasible range, an overflow occurs.
- The int type is the most used unless otherwise noted.
- If you want to write down a long-type literal, say 9876543210, you should write 9876543210L, where the suffix L indicates the long type.
Two-Before Rule
- Rule 1: a variable must be declared before any assignment.
- Rule 2: a variable must be initialized before being used.
Two of Program Stages
double x = 1 / 2;
System.out.println(x); // Output: 0.0;
- 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.
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 a double value 1.0.
- Clearly, Java is a weakly-typed language.
- However, there is no automatic conversion from double to int.
- To do so, you must use a cast, which performs an explicit conversion.
small to big size, but cannot big to small size (need a cast)
Text: Characters & Strings
Hex | Dec | Char |
---|---|---|
0x41 | 65 | A |
0x61 | 97 | a |
char x = ’a’;
x += 1;
System.out.println(x); // Output b.
x++;
System.out.println(x); // Output c.
String y = "Java";
y += 999
System.out.println(y); // Output Java999.
Discussion: ++x vs. x++
int x = 0;
int y = ++x;
Console.WriteLine(y); // Output 1.
Console.WriteLine(x); // Output 1.
int w = 0;
int z = w++;
Console.WriteLine(z); // Output 0.
Console.WriteLine(w); // Output 1.
- 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.(新值)
Scanner: Example of Reference Types
- Reading inputs from the users'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.
import java.util.Scanner;
// Create Scanner object to receive data from keyboard.
Scanner input = new Scanner(System.in);
// INPUT
System.out.println("Enter r?");
int r = input.nextInt();
// ALGORITHM
double A = r * r * 3.14;
// OUTPUT
System.out.println(A);
input.close(); // Cleanup: reclaim the resource.
- In Line 1, we include the Scanner class, which belongs to the java.util package, by using the import statement.
- We put these import statements in the beginning of the file.
- Note that we can’t leave these import statements in any class.
- In Line 4, the new operator 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 an int value.
- All runtime objects are created dynamiclly and resided in the heap.
- Before manipulating the Scanner object, its address is assigned to the variable input, which is allocated in the stack.
- Hence input is called a reference to the Scanner object.
- Clearly, the memory contains human data and also references (i.e., memory addresses).
Exercise
Body Mass Index(BMI)
Q. 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 / height * height
Scanner input = new Scanner(System.in);
// INPUT
System.out.println("Enter your name?");
String name = input.nextLine();
System.out.println("Enter your height (cm)?");
double height = input.nextDouble();
System.out.println("Enter your weight (kgw)?");
double weight = input.nextDouble();
// ALGORITHM
double bmi = 10000 * weight / height / height;
// OUTPUT: name (bmi)
System.out.println(name + " (" + bmi + " )");
Two Descriptive Statistics
Write a program to take 3 numbers as user’s input and output the arithmetic average with its standard deviation.
// INPUT
Scanner input = new Scanner(System.in);
System.out.println("a = ?");
double a = input.nextDouble();
System.out.println("b = ?");
double b = input.nextDouble();
System.out.println("c = ?");
double c = input.nextDouble();
input.close();
// ALGORITHM
double mean = (a + b + c) / 3;
double std = Math.sqrt(Math.pow(a - mean, 2) +
Math.pow(b - mean, 2) +
Math.pow(c - mean, 2) / 3);
// OUTPUT
System.out.println("Mean = " + mean);
System.out.println("Std = " + std);