Introduction to Computer Programming (CS109) Lecture Notes PDF

Document Details

HandsomeCentaur7126

Uploaded by HandsomeCentaur7126

Southern University of Science and Technology

Yuxin Ma

Tags

computer programming java programming computer science lecture notes

Summary

This document provides lecture notes for the Introduction to Computer Programming (CS109) course at Southern University of Science and Technology. It covers topics such as course objectives, grading policy, textbooks, and syllabus. The notes are presented in a structured format, typically used for computer science courses at the university level.

Full Transcript

Introduction to Computer Programming (CS109) Yuxin Ma Department of Computer Science and Engineering Southern University of Science and Technology Instructor Dr. Yuxin Ma 马昱欣 (Associate Professor in the Department of CSE) Office: Room 512, South...

Introduction to Computer Programming (CS109) Yuxin Ma Department of Computer Science and Engineering Southern University of Science and Technology Instructor Dr. Yuxin Ma 马昱欣 (Associate Professor in the Department of CSE) Office: Room 512, South Tower, Engineering Building Email: [email protected] Office hour: Monday 2-4pm @ my office i.e., right before Monday’s classroom session If you would like to come, please send me an email for appointment first Course Objectives To learn how to solve problems by writing computer programs To learn how to design a computer program To learn how to program in Java To learn object-oriented programming To prepare you for further courses and career Grading Policy Lecture attendance and quizzes (5%) Lab attendance (5%) 4 different lab sessions (by Yun Shen 沈昀 and Yuxin Ma 马昱欣) Assignments (30%) 6 Assignments, 2~3 weeks each Project (20%) Early November Final exam (40%) Grading Policy Late Submission We do not accept late submissions. All assigments, quizzes, and projects, etc. will receive a score of zero if you miss the deadline. Groups for Projects Groups across different lab sessions are not allowed Please try to find your teammate in the same lab session Grades The teachers and TAs guarantee that your assignments and projects will be evaluated carefully and unbiasedly We do not accept argueing with teachers over a certain grade once the decision has been made Lecture Notes, Sakai and QQ Group There is a Blackboard site for this course https://bb.sustech.edu.cn If you are not in the site after selecting this course, please let me know Slides and lab sheets will be on the Blackboard site Assignment questions and answers are also there QQ Group ID: 892639275 Teaching assistants will be there to help you Some Other Stuff How to get updated Check your university email (mail.sustech.edu.cn) regularly Blackboard site notices will be sent to your university email box Remember to check them everyday Computing technologies advance very fast. Search online to learn more by yourself. The lecture notes can guide your self study. Search engines (Google, Bing, Baidu, etc.), StackOverflow, GitHub. Lab Session The lab sessions start from today 4 Groups, on Monday, Tuesday or Wednesday Attendance is required. Please remember to attend your lab class. You are highly recommended to bring your own laptop. Introduction to Computer Programming (CS109) Lecture 1: Introduction to Java Programming Yuxin Ma Department of Computer Science and Engineering Southern University of Science and Technology Syllabus Introduction to Java Applications Procedural Programming: Control Statement Arrays and ArrayLists Methods Strings, Wrapper Classes, File I/O Syllabus Object-oriented Programming: Classes, Objects Inheritance Polymorphism GUI programming Java Collections, Generic Methods and Classes Exception Handling and Recursion Textbooks Actually, any Java textbook should work. The books listed here are just some (useless) suggestions. You can find the one that suits you the best. Main textbook: P. Deitel, H. Deitel, Java: How to Program (11/e), Prentice-Hall. Reference books: Y. Daniel Liang. Introduction to Java Programming, 10e, Pearson, Prentice Hall, 2015. Allen B. Downey and Chris Mayfield. Think Java, How to Think Like a Computer Scientist, O'Reilly, 2016. Computer System Hardware (physical parts, e.g., keyboard, mouse, hard disk, memory, processing units) Software (computer programs, libraries, non-executable data, e.g., documentation) Hardware is directed by software to execute commands or instructions. A combination of hardware and software forms a usable computer system. The von Neumann Architecture A design model for a stored-program digital computer John von Neumann (1903-1957) Hungarian-American mathematician, physicist The von Neumann Architecture A design model for a stored-program digital computer (Pray before the final exam) What is a Computer Program? Human work model Work WorkerProduct Instructions Computer work model WorkComputer Product Program A computer program is a set of machine-readable instructions that tells a computer how to preform a specific task. What is a (Programming) Language? Programs are written in programming languages There are many programming languages Low-level, understandable by a computer High-level, needs a translator! A sequence of instructions An algorithm A program (in human language) (in computer language) What is a (Programming) Language? https://www.tiobe.com/tiobe-index/ Programs are written in programming languages There are many programming languages Low-level, understandable by a computer High-level, needs a translator! A sequence of instructions An algorithm A program (in human language) (in computer language) Tip: What is the relationship between Java and JavaScript? We learn Java, why? A computer programming language An object-oriented computer programming language – today’s key methodology One of the most widely used computer programming language – billions of devices Preferred for Internet-based applications and devices over a network https://www.tiobe.com/tiobe-index/ We learn Java, why? A computer programming language An object-oriented computer programming language – today’s key methodology One of the most widely used computer programming language – billions of devices Preferred for Internet-based applications and devices over a network (the first time when I was teaching CS109/CS102A -) https://www.tiobe.com/tiobe-index/ We learn Java, why? A computer programming language An object-oriented computer programming language – today’s key methodology One of the most widely used computer programming language – billions of devices Preferred for Internet-based applications and devices over a network Question for Today’s Class How do we write the first program? Prerequisites: JDK and IDE installed Regarding basic input/output: How can we output (print) something in the program? How can we input something? How can we do math in programs? Our First Program in Java Our First Program in Java Comments // indicates that the line is a comment. Used to document programs and improve their readability Compiler ignores comments. Traditional comment, can be spread over several lines This type of comment begins with Traditional vs. End-of-Line Comments Traditional comments do not nest, the first */ after the first /* will terminate the comment. End-of-line comments can contain anything. Our First Program in Java: Printing a Line of Text (Cont.) Class declaration Every Java program consists of at least one class that you define class keyword introduces a class declaration and is immediately followed by the class name Keywords are reserved for use by Java and are always spelled with all lowercase letters. Our First Program in Java: Printing a Line of Text (Cont.) Class names By convention, begin with a capital letter and capitalize the first letter of each word they include Java is case sensitive—uppercase and lowercase letters are distinct (not in comments) Our First Program in Java: Printing a Line of Text (Cont.) The braces A left brace, {, begins the body of every class declaration A corresponding right brace, }, must end each class declaration Code between braces should be indented (good practice) Our First Program in Java: Printing a Line of Text (Cont.) The braces A left brace, {, begins the body of every class declaration A corresponding right brace, }, must end each class declaration Code between braces should be indented (good practice) Another way of aligning braces Our First Program in Java: Printing a Line of Text (Cont.) The braces A left brace, {, begins the body of every class declaration A corresponding right brace, }, must end each class declaration Code between braces should be indented (good practice) Another way of aligning braces Our First Program in Java: Printing a Line of Text (Cont.) The braces A left brace, {, begins the body of every class declaration A corresponding right brace, }, must end each class declaration Code between braces should be indented (good practice) Our First Program in Java: Printing a Line of Text (Cont.) Declaring the main method Starting point of Java applications Parentheses after the identifier main indicate that it’s a program building block called a method Java class declarations normally contain one or more methods Keyword void indicates that this method will not return any information Our First Program in Java: Printing a Line of Text (Cont.) Body of the method declaration Enclosed in left and right braces Statement Instructs the computer to perform an action Print the string of characters contained between the double quotation marks Our First Program in Java: Printing a Line of Text (Cont.) Body of the method declaration Enclosed in left and right braces Statement Instructs the computer to perform an action Print the string of characters contained between the double quotation marks Our First Program in Java: Printing a Line of Text (Cont.) Body of the method declaration Enclosed in left and right braces Statement Instructs the computer to perform an action Print the string of characters contained between the double quotation marks Our First Program in Java: Printing a Line of Text (Cont.) System.out object Standard output object Allows Java applications to display strings in the command window from which the Java application executes System.out.println method Displays (or prints) a line of text in the command window. The string in the parentheses is the argument to the method. Positions the output cursor at the beginning of the next line in the command window Our First Program in Java: Printing a Line of Text (Cont.) Compiling and executing your first Java application To compile the program, type: javac Welcome1.java If the program contains no syntax errors, preceding command creates a Welcome1.class file (known as the class file) containing the platform-independent Java bytecodes that represent the application > javac Welcome1.java > java Welcome1 Welcome to Java Programming! > Our First Program in Java: Printing a Line of Text (Cont.) To execute the program, type: java Welcome1 Launches the JVM, which loads the.class file for class Welcome1 Note that the.class file-name extension is omitted from the preceding command; otherwise, the JVM will not execute the program. > javac Welcome1.java > java Welcome1 Welcome to Java Programming! > Modify Our First Java Program Modify Our First Java Program Class Welcome2 uses two statements to produce the same output as class Welcome1 System.out’s method print displays a string Unlike println, print does not position the output cursor at the beginning of the next line in the > javac Welcome2.java command window > java Welcome2 Welcome to Java Programming! > Modify Our First Java Program Newline character ‘\n’ tells the print methods when to position the output cursor at the beginning of the next line in the command window Newline characters are white-space characters White-space characters do not correspond to a visible mark, but represent horizontal or vertical space in typography The backslash (\) is called an escape character, and forms an escape sequence together with its next character Invokes an alternative interpretation on subsequent character Common Escape Sequences Escape Sequence Description \n Newline. Position the cursor at the beginning of the next line. \t Horizontal tab. Move the cursor to the next tab stop. Carriage return. Position the cursor at the beginning of the current line (do not advance to the \r next line). Any characters output after the carriage return overwrite the characters previously output on that line. \\ Use to print a backslash character. Used to print a double-quote character. \" System.out.println("\"in quotes\""); displays "in quotes" Displaying Text with printf Displaying Text with printf The method printf displays “formatted” data. It takes a format string as an argument. Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. Format specifier %s is a placeholder for a string. Format specifier %n is a placeholder for a newline. Displaying Text with printf The method printf displays “formatted” data. It takes a format string as an argument. Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. Format specifier %s is a placeholder for a string. Format specifier %n is a placeholder for a newline. Displaying Text with printf The method printf displays “formatted” data. It takes a format string as an argument. Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. Format specifier %s is a placeholder for a string. Format specifier %n is a placeholder for a newline. > javac Welcome4.java > java Welcome4 Welcome to Java Programming! > General vs. Specific Sometimes we want to write a function to serve the majority, with a very general purpose. Consider buying a standard hamburger set in McDonald’s. “One Size Can’t Fit All” We always have a lot of specific purposes. What if I want more ketchup in my hamburger, more ice and less sugar in my drink? print() vs. printf() Primitive Data Types: Integers Type Size Range byte 8 bits -128 to +127 short 16 bits -32,768 to +32,767 int 32 bits (about) -2 billion to +2 billion long 64 bits (about) -10E18 to +10E18 Primitive Data Types: Floating Point Numbers Type Size Range float 32 bits -3.4E+38 to +3.4E+38 double 64 bits -1.7E+308 to 1.7E+308 Another Application: Adding Integers Another Application: Adding Integers > javac Addition.java > java Addition Enter the first integer: 45 Enter the second integer: 72 Sum is 117 > Another Application: Adding Integers import declaration: Helps the compiler locate a class that is used in this program. Related classes are grouped into packages java.util package provides commonly-used classes. These classes are collectively called Java class library, or Java Application Programming Interface (Java API). Another Application: Adding Integers Variable declaration statement Variable represents a location in the computer’s memory where a value can be stored for use later in a program Must be declared with a name and a type before use A variable’s name enables the program to access the value of the variable in memory A variable’s type specifies what kind of information is stored at that location in memory Another Application: Adding Integers Variable declaration statement type name Variable represents a location in the computer’s memory where a value can be stored for use later in a program Must be declared with a name and a type before use A variable’s name enables the program to access the value of the variable in memory A variable’s type specifies what kind of information is stored at that location in memory Another Application: Adding Integers The Scanner class enables a program to read data for use in a program The data can come from many sources, such as the user at the keyboard or a file on disk The equals sign (=) in a declaration indicates that the variable should be initialized (i.e., prepared for use in the program) with the result of the expression to the right of the equals sign Another Application: Adding Integers The Scanner class enables a program to read data for use in a program The data can come from many sources, such as the user at the keyboard or a file on disk The equals sign (=) in a declaration indicates that the variable should be initialized (i.e., prepared for use in the program) with the result of the expression to the right of the equals sign Another Application: Adding Integers The new keyword creates an object (we will talk more on objects later) Standard input object, System.in, enables applications to read bytes of information typed by the user. Scanner object translates these bytes into types that can be used in a program. Another Application: Adding Integers Several variables of the same type may be declared in one declaration with the variable names separated by commas. Another Application: Adding Integers Several variables of the same type may be declared in one declaration with the variable names separated by commas. Alternative ways to declaring the variables: Another Application: Adding Integers Prompt is an output statement that directs the user to take a specific action System is a class and part of package java.lang The class System does not need to be imported at the beginning of the program because the classes in the java.lang package are imported by default. Another Application: Adding Integers Scanner method nextInt obtains an integer from the user at the keyboard. Program waits for the user to type the number and press the Enter key to submit the number. The result of the call to method nextInt is placed in variable number1 by using the assignment operator, =. number1 gets the value of input.nextInt() Another Application: Adding Integers Arithmetic operations sum gets the value of number1 + number2 Portions of statements that contain calculations are called expressions. Another Application: Adding Integers Integer formatted output Format specifier %d is a placeholder for an int value The letter d stands for “decimal integer” Memory Concepts Variables Every variable has a name, a type, a size (in bytes) and a value When a new value is placed into a variable, the new value replaces the previous value (if any) And the previous value is lost Arithmetic Operations Operator Description Algebra Expression Java Expression + Additive operator (also used for String concatenation) 𝑓+7 f + 7 - Subtraction operator 𝑝−𝑐 p - c * Multiplication operator 𝑏𝑚 b * m 𝑥 / Division operator 𝑥/𝑦 or 𝑦 or 𝑥 ÷ 𝑦 x / y % Remainder operator 𝑟 𝑚𝑜𝑑 𝑠 r % s These are binary operators because they operate on two operands Integer division yields an integer quotient. The fractional part is simply discarded 3 / 2 = 1 % yields the remainder after division 10 % 3 = 1 Arithmetic Operations Arithmetic expressions must be written in straight-line form to facilitate entering programs into the computer 𝑎 Expression “a divided by b” must be written as a / b (rather than ), so 𝑏 that all constants, variables and operators appear in a straight line Parentheses are used to group terms in expressions in the same manner as in algebraic expressions: a * (b + c) In case of nested parentheses, the expression in the innermost set of parentheses is evaluated first: ((a + b) * c) Operator Precedence *, / and % operations are applied first (the three operators have the same level of precedence) If an expression contains several such operations (*, /, %), they are applied from left to right + and - operations are applied next. If an expression contains several such operations (+, -), the operators are applied from left to right Integer Divisions What is the result? Java drops the fractional part for integer divisions. What to do if you really want to calculate 9 / 2 - 1.5? Primitive Types vs. Reference Types Java types are divided into two categories Primitive types Reference types Primitive types are the basic types of data. byte, short, int, long, float, double, boolean, char A primitive-type variable can store one value of its declared type Primitive Types vs. Reference Types All non-primitive types are reference types, including instantiable classes and arrays (an array is a container object that holds a fixed number of values of a single type) Scanner, String, String[], int[]. Programs use reference-type variables to store the locations of objects in memory Such a variable is said to refer to an object in the program Objects that are referenced may each contain many instance variables of primitive and reference types Primitive Types vs. Reference Types Reference-type variables, if not explicitly initialized, are initialized by default to the value null (reference to nothing). To call methods of an object, you need to use the reference to the object: myGradeBook.displayMessage(); Primitive-type variables (e.g., int variables) do not refer to objects, so such variables cannot be used to call methods. Some Important Prerequisite Asking Questions You are encouraged to ask questions at any time Try to make good use of all the resources around you Question regarding the assignments and the project The lecturer and the TAs won’t help you write or debug codes and pass the Online Judge system tests with no effort from your side Instead, we will provide you guidance about how to solve it Practice makes perfect No need to be afraid of trying new techniques/ideas/codes Plagiarism Plagiarism is strictly prohibited in this course Zero tolerance upon copying in assignments and projects Do not copy any codes from others Including but not limited to: friends, classmates, websites, public code repositories (Github, Gitee, etc.) Be sure NOT to copy any codes from examples used for teaching (especially from your classmates or senior students) There are differences between plasiarism and use as references Plagiarism On the other hand, please learn to protect yourself Do not lend your code and OJ account to others When helping your classmates, try not to show your own code directly Be cautious when someone saves your code without permission Lock screen with passwords Plagiarism On the other hand, please learn to protect yourself Do not lend your code and OJ account to others When helping your classmates, try not to show your own code directly Be cautious when someone saves your code without permission Lock screen with passwords Once plagiarism is identified in the Online Judge (OJ) system, all students involved will be punished no matter you are copying or copied by others (unless you can prove someone has stolen your code). There will be serious consequences once being caught, so please write all the assignments and projects on your own. Plagiarism Please read the regulations on academic misconduct on the Sakai site Upload the signed Undergraduate Students Declaration Form to Sakai with the following file name format: name_ID.[docx|pdf]

Use Quizgecko on...
Browser
Browser