• 沒有找到結果。

Java Programming

N/A
N/A
Protected

Academic year: 2022

Share "Java Programming"

Copied!
41
0
0

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

全文

(1)

Java Programming

Zheng-Liang Lu

Department of Computer Science & Information Engineering National Taiwan University

Java 361 Summer 2022

(2)

Class Information

• Instructor: 盧政良 (Zheng-Liang Lu, Arthur)

• Email: arthurzllu@gmail.com

• The course website is

https://www.csie.ntu.edu.tw/d00922011/java.html.

• All lecture slides are organized in English and will be modified if necessary.

• In-class examples may involve with high school math.

Zheng-Liang Lu Java Programming 1

(3)

Teaching Philosophy

• I try to lower the barriers to entry.

Everything in my class is simple, essential, and general.1

• I could provide extra studying materials as many as possible.

• I answer your questions.

1“Simple is not easy. . . . Easy is a minimum amount of effort to produce a result. . . .Simple is very hard. Simple is the removal of everything except what matters. . . .” by Christopher S. Penn.

Zheng-Liang Lu Java Programming 2

(4)

Learning Tips

• Start with just onelanguage and master it.

• Ask lots of questions; Google first.

• Practice makes permanent (and hopefully, perfect).2

• It may take 10000 hours, more or less3; it is never too late.

• Grasp the fundamentals for long-term benefits; code from the bottom.

• Code by hand; it sharpens proficiency.

2Tryhttps://leetcode.com/.

3Malcolm Gladwell (2008): Outliers.

Zheng-Liang Lu Java Programming 3

(5)

“Knowledge is of no value unless you put it into practice.”

– Anton Chekhov (1860-1904)

“Many roads lead to the path, but basically there are only two: reason and practice.”

– Bodhidharma

Zheng-Liang Lu Java Programming 4

(6)

Grading Policy

• To acquire the class certificate, you need to finish all labs listed in the course page.4

4Seethe list of programming labs.

Zheng-Liang Lu Java Programming 5

(7)

Roll Call

Zheng-Liang Lu Java Programming 6

(8)

1 class Lecture1 {

2

3 "Introduction"

4 5 }

6

7 // Keywords:

8 public, class, static, void

Zheng-Liang Lu Java Programming 7

(9)

Zheng-Liang Lu Java Programming 8

(10)

http://p.migdal.pl/2017/04/30/teaching-deep-learning.html

Zheng-Liang Lu Java Programming 9

(11)

Goal: Problem Solving

• Programming is to provide computational solutions to real-world problems.

• The resulting solution is called a program.

Zheng-Liang Lu Java Programming 10

(12)

Programs

• A program is a collection ofinstructionsto perform a specified task.

• They are almost everywhere, for example,

video games (e.g. Pok´emon Go, Travel Frog, . . . );

operating systems (e.g. Linux, . . . );

autonomous driving5/ auto-piloting (e.g. MRT, airplane, . . . );

search engines (e.g. Google, . . . );

robotics6;

computer malware7;

and more.8

5Seehttps://www.tesla.com/autopilot.

6Seehttps://www.bostondynamics.com/and watch videos from its official YouTube channelhere.

7Seemalwareandcomputer virus.

8SeeInternet of Things (IoT).

Zheng-Liang Lu Java Programming 11

(13)

How to Execute Programs

12

• Once the program is activated, both data and instructions are loaded from the disk into themain memory.

• We now call it a process, which is the smallest unit of resource allocation.9

• Then the instructions in the program are scheduledto be executed by theCPU.10

A CPU consists of 6 main components: arithmetic & logic units (ALUs), registers, control units, cache, buses, and clock.11

• The immediate result is stored back to the main memory and further written into the disk if necessary.

9Seehttps://en.wikipedia.org/wiki/Process (computing).

10Seehttps://en.wikipedia.org/wiki/Scheduling (computing).

11Seehttps://en.wikipedia.org/wiki/Central processing unit.

12SeeInside Your Computerby Bettina Bair andSystems Architectureby BBC.

Zheng-Liang Lu Java Programming 12

(14)

Hardware Organization: Illustration

13

13See Figure 1-4 in Bryant, p. 44.

Zheng-Liang Lu Java Programming 13

(15)

Memory Hierarchy

14

14See Figure 1-9 in Bryant, p. 50.

Zheng-Liang Lu Java Programming 14

(16)

Programming Languages

• A programming language is an artificial language to communicatewith machines.15

• The elements of programming languages are syntaxand semantics, used to control the behavior of machines.

• Top 20 programming languages can be found in TIOBE.

• Every language originates from some reasons.

15Seehttps://en.wikipedia.org/wiki/Programming language.

Zheng-Liang Lu Java Programming 15

(17)

A Short History

16

• Gen 1: machine code.

• Gen 2: assembly code.

• Gen 3: high-level programming languages.

For example, C, C++, Java, C#, Python.

• Gen 4.

For example, SQL.

16Seegenerations of languageandcomputer programming history.

Zheng-Liang Lu Java Programming 16

(18)

Zheng-Liang Lu Java Programming 17

(19)

1st-Generation Languages

• The 1st-generation language is pure machine code, which represents instructions in just ones and zeros. (Why?)

• Each machine has its own instruction set.17

• So machine code is platform-dependent!

• More worse, the machine language is not human-readable.

17For example, the instruction set of thex86family and theARMfamily are incompatible.

Zheng-Liang Lu Java Programming 18

(20)

2nd-Generation Languages

• An assembly language uses mnemonics to represent instructions as opposed to the machine codes.

• Hence, assembly code is easier for human to read and write.

• When the assembly code is executed, it is then converted to the resulting machine code.

• It is worth to mention that the program flow of assembly code is almost close to the execution steps in the machine.18

18To be a hacker, you should learn assembly languages.

Zheng-Liang Lu Java Programming 19

(21)

3rd-Generation Languages

• High-level languages are much closer to human languages by using English-like words, mathematical notations, and punctuation to write programs.

• For example, C19, C++20, Python21, and Java22.

19Dennis Ritchie (1973).

20Bjarne Stroustrup (1983).

21Guido van Rossum (1989).

22James Gosling (1995).

Zheng-Liang Lu Java Programming 20

(22)

What Can A Program Do?

• A programis an implementation of an algorithmexpressed in a specific programming language.

Zheng-Liang Lu Java Programming 21

(23)

First Glance at Algorithms

23

• Simply put, an algorithm is a well-defined procedurethat solves a specific category of problems, like a recipe or a cookbook.

• In general, an algorithm may take adequate information as its input and produce the correct result as itsoutput.

23Also seeWhat’s an Algorithm?by David J. Malan.

Zheng-Liang Lu Java Programming 22

(24)

Example: 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 in A.

• For example, assume that A = {1, 7, 9, −2, 4}.

• It is clear that the answer is 9.

• Can you teach the computer to repeat your idea?

Zheng-Liang Lu Java Programming 23

(25)

Optimal Algorithm (Pseudo Code)

• For convenience, A(i ) denotes the i -th number of A and the symbol ← denotes a copy operator from right to left.

• Then the optimal algorithm could be as follows:

1 max<− A(1) // Initial guess, without loss of generality!

2 for i <− 2 ˜ n

3 if A(i)> max

4 max <− A(i)

5 end

6 end

7 return max

Zheng-Liang Lu Java Programming 24

(26)

Discussions

• In Line 1, why not max ← 0 ?

• You may extend this algorithm for following questions:

smallest number;

location of the largest (also smallest) number;

... (more and more)

• We are eager for efficient algorithms.24

Will “sorting the list and then the largest number could be the last number” be more efficient than the previous one?

24We will show you thecomplexity analysisin the end of the chapter of loops.

Zheng-Liang Lu Java Programming 25

(27)

“Computers are good at following instructions, but not at reading your mind.”

– Donald Knuth (1938-)

“There are two ways of constructing a software design:

One way is to make it sosimplethatthere are obviously no deficiencies, and the other way is to make it socomplicated thatthere are no obvious deficiencies. The first method is far more difficult.”

– Tony Hoare (1934-)

Zheng-Liang Lu Java Programming 26

(28)

Alan Turing

• Provided a formalization of the concepts of algorithmand computation with theTuring machine25, which can be considered a model of a general-purpose computer.

• Proposed the famous question: “Can machines think? ”26

Well-known as the Turing test.

• Turing Award is recognized as the highest distinction in computer science and the“Nobel Prize of computing”.27

25Turing (1936). Trythisgoogle doodle.

26Turing (1950). You could find the paperhere. Also seeTuring Test.

27Seehttps://en.wikipedia.org/wiki/Turing Award#Recipients.

Zheng-Liang Lu Java Programming 27

(29)

• You may watch The Imitation Game(2014).

• Britain’s £50 note will honor computing pioneer Alan Turing.28

28SeeAlan Turing to be the Face of New £50 Noteby Bank of England.

Zheng-Liang Lu Java Programming 28

(30)

About Java

29

• Java is one of general-purpose programming languages, supporting theobject-oriented programming (OOP) paradigm.

• Java was first released by Sun Microsystems back in 1995 and is now maintained byOracle (ORCL) after the year of 2010.

• Java was intended to let application developers write once, run anywhere (WORA).

• Nowadays, Java is widely used in web apps (especially the back-end services), mobile apps (for example, Android apps) and embedded systems.

29SeeJava Version History.

Zheng-Liang Lu Java Programming 29

(31)

Java Virtual Machine (JVM)

32

• JVM is a software program, not a physical machine.

• JVM translates Java bytecodesinto machine codes which can be executed by the host platform.30

• JVM verifies all bytecodes before the program is executed, so that no user program can crash the host machine.31

• You can find further details about JVM from its specification.

30For example, Windows, Linux, and MacOS for desktop/laptop computers;

Android and iOS for mobile devices.

31SeeSecurity Vulnerabilities of Java.

32Seehttp://en.wikipedia.org/wiki/Java virtual machine.

Zheng-Liang Lu Java Programming 30

(32)

Software Installation

• First download and install theJava Development Kit (JDK).33

• Then choose anintegrated development environment (IDE) which may provide comprehensive facilities, say debugger, code completion, and build automation tools.

• In this course, I will use Eclipse34, which is a free and powerful IDE.

You may try other IDEs, for example, NetBeans35, IntelliJ IDEA36 or Visual Studio Code37 with proper packages.

33Seehttps://www.oracle.com/java/technologies/downloads/.

34Seehttps://www.eclipse.org/downloads/.

35Seehttps://netbeans.apache.org/.

36Seehttps://www.jetbrains.com/idea/.

37Seehttps://code.visualstudio.com/.

Zheng-Liang Lu Java Programming 31

(33)

Workflow

38

38See Figure 2-19 in Sharan, p. 59.

Zheng-Liang Lu Java Programming 32

(34)

First Program: Hello, World

39

1 public class HelloWorldDemo {

2

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

4

5 // Print "Hello, Java." on the screen.

6 System.out.println("Hello, Java.");

7

8 }

9 10 }

• class: define a new class.

• public: accessible to anyone.

• static: can be called without having any object.

• void: no return value.

39Seehttps://en.wikipedia.org/wiki/”Hello, World!” program.

Zheng-Liang Lu Java Programming 33

(35)

Discussions (1/3)

• A class is an entity of Java programs.

• A Java program can consist of many classes.40

• To be executable, a program needs one special method41 called themain method as the entry pointof the program.

• System.out refers to the standard output device, say the monitor screen.

• The println method is used to output thestring you offer.

• Every statement should end with a semicolon (;).

40We will discuss more later in the OOP chapter.

41Also called functions and subroutines in other programming languages.

Zheng-Liang Lu Java Programming 34

(36)

Discussions (2/3)

• For now, one program has only onepublic class.

• The only public classshould have the same name as the filename.

For example, thepublicHelloWorldDemo 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.

• The keyword public is one ofaccess modifiers, allowing you to control thevisibility of classes and also its members.42

42We will visit more access controls later.

Zheng-Liang Lu Java Programming 35

(37)

Discussions (3/3): Table of Special Characters

Symbol Description

{ } Denote a scope to enclose statements; enumerate a set of objects.

( ) Mostly used with expressions and methods.

[ ] Mostly used with arrays.

” ” Enclose a string.

; Mark the end of a statement.

// Precede a comment line.

/* ... */ Used as block comments.

Zheng-Liang Lu Java Programming 36

(38)

Recall How To Run A Java Program

43

43See Figure 1.14 in YDL, p.20.

Zheng-Liang Lu Java Programming 37

(39)

Digression: Bugs

44

• A bug is an error, flaw, failure, or fault in a computer program or system, producing an incorrect or unexpected result, or misbehaving in unintended ways.

Compile-time error: most of them are syntax errors.

Runtime error: occurs when Java program runs, e.g. 1/0.

Logic error: introduced by implementing the functional requirement incorrectly.

• Note that logic (semantic) errors are the obscurest because they are hard to be found.

44SeeComputer Bugs.

Zheng-Liang Lu Java Programming 38

(40)

“If debugging is the process of removing software bugs, then programming must be the process of putting them in.”

– Edsger W. Dijkstra (1930–2002)

“Why do we fall sir? So that we can learn to pick ourselves up.”

– Alfred Pennyworth, Batman Begins (2005)

Zheng-Liang Lu Java Programming 39

(41)

Programming Style

• A good programming style makes programs easy to read and helps programmers prevent from errors.

For example,Google Java Style GuideandCode Style of Java from IntelliJ IDEA.

• In particular, we use indentationto enhance the structural relationships by visual.

For Eclipse users, select the code snippet and press ctrl + I to make correct indentation.

• Be consistent through the whole program, even in the project!

Zheng-Liang Lu Java Programming 40

參考文獻

相關文件

OOP: organized DATA + organized code (ACTION) using classes as the basic module. action are closely coupled

• 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

Dynamic programming is a method that in general solves optimization prob- lems that involve making a sequence of decisions by determining, for each decision, subproblems that can

• Instead, static nested classes do not have access to other instance members of the enclosing class. • We use nested classes when it

• manipulating object status (partially done: instance variable assignments).. • deleting objects —[TODO 3]

• Instead, static nested classes do not have access to other instance members of the enclosing class. • We use nested classes when it

• Non-static nested classes, aka inner classes, have access to other members of the enclosing class, even if they are declared private. • Instead, static nested classes do not

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type.. If there isn’t such a