Lecture 1 CS1211 Computer Programming PDF

Document Details

Uploaded by Deleted User

Umm Al-Qura University

2023

Dr. Malak AlGabri, Dr. Areej Althobiti, Dr. Azhar Alhindi, Dr. Maryam Alsolami

Tags

java programming computer programming programming languages computer science

Summary

This document is a lecture on Computer Programming (CS1211) for the 2nd Trimester of 2023/24. It provides an introduction to programs and programming languages, including an outline, programs, programming languages, and different levels of programming languages.

Full Transcript

CS1211: Computer Programming 2nd Trimester : 2023/24 Lecture 1 Introduction to Programs and programming Languages Source: Dr. Malak AlGabri and Dr. Areej Althobiti slides Modification:...

CS1211: Computer Programming 2nd Trimester : 2023/24 Lecture 1 Introduction to Programs and programming Languages Source: Dr. Malak AlGabri and Dr. Areej Althobiti slides Modification: Dr. Azhar Alhindi and Dr. Maryam Alsolami 1 1 Outline ✓Programs and Programming Languages. ✓Java Programming Language. ✓Programming Basics. 2 2 1 Programs and Programming Languages 3 3 Programs A program is a set of instructions for a computer to follow that directs the computer to do the tasks you want it to do and produce the results you want. A program is like a recipe. It contains a list of variables (called ingredients) and a list of statements (called directions) that tell the computer what to do with the variables. Following the instructions is called running or executing the program We use programs almost daily (email, word processors, video games, bank ATMs, etc.). Programmers tell a computer what to do through programs. Without programs, a computer is an empty machine. Computers do not understand human languages, so we need to use computer languages to communicate with them. Programs are written using programming languages. 4 4 2 Running a Program Normally, a computer receives two kinds of input: The program The data needed by the program. The output is the result(s) produced by following the instructions in the program. 5 5 Programming Languages Programming languages are a set of instructions written in a way that a computer could understand Why do we need programming languages? All computer components: Central Processing Unit(CPU), memory, and Input/Output (I/O) understands a machine code called a binary. Binary is a long string of 0’s and 1’s that human cannot understand! So how can we make the computer to perform a certain task? Programming languages helps us in doing so by providing an intermediate solution between the human and the machine Each language has a unique set of keywords (words that it understands) and a special syntax for organizing program instructions. 6 6 3 Syntax and Semantics of programming languages Syntax and Semantics provide a language's definition. The grammar rules for a programming language are called the syntax of the language (detected by the compiler). Different languages have different syntax. e.g., while statement in java while (boolean_expression) statement The interpretation or the meaning of the statements is called the semantic of the language. e.g., Array index out of range: int[] v = new int; v = 100; // 10 is not a legal index for an array of 10 elements e.g., Use of a non-initialized variable: int i; i++; // the variable i is not initialized More details: https://newtutorial2012.blogspot.com/2012/07/differentced-between-synataxsemantic.html https://www.inf.unibz.it/~calvanese/teaching/ip/lecture-notes/uni10/node2.html 7 7 Programming Languages (cont.) Programming languages could be Assembly High-level categorized into: Low-level languages (machine language): they are close to the machine language e.g. assembly language High-level languages: they are closer to the programmers' language (more friendly!) e.g. Java 8 8 4 Levels of Programming Languages High-level languages are relatively easy Natural Language to use (i.e., more flexibility, easier to be Implemented, maintained) Very High-Level Language Unfortunately, computer hardware does (e.g., Java, C++, C#) not understand high-level languages! Therefore, a high-level language High Level Language program must be translated into a (e.g., Fortran, Cobol) low-level language. Assembly Language (Intel:8086, Sun Sparc) Speed Machine Language (e.g., 01001110000) 9 9 Choosing A Language Depends on your tasks: Satellite communication (speed) → Assembly Education→ Basic, Pascal Business → Cobol Web development→ JavaScript, JSP,.NET Scientific calculation→ Fortran, Matlab Embedded and Operating Systems→ C Enterprise applications → Java 10 10 5 Translating/Converting High-level to Low- level A source program must be translated into a machine code. An application program called a translator which transforms code from High Level Language to Low Level Language, making it machine understandable code. Compilers and interpreters are simply language translators in computer programming. The program is run by loading machine code into main memory. The processor directly executes these machine language instructions 11 11 Compilers A compiler is a program that takes a high-level language program and translates the entire program into machine code all at one time All instructions are compiled before any are executed by the CPU The Java compiler (javac) translates Java source code (Hello.java) into a special representation called bytecode (object program) When a Java program is translated into bytecodes, the bytecodes are exactly the same no matter what computer system is used Compilation process occurs only once and the resulting object program could be run as often as needed without re-compiling the source program 12 12 6 Interpreters An interpreter reads through a source program written in a high level language and performs the instructions that the source program asks for one by one. Once a given instruction has been translated and executed, the next one then will follow, and son on The Java Virtual Machine (JVM) uses an interpreter, to translate bytecode into machine language and executes it 13 13 Java Programming Language 14 14 7 Java History Java is a high-level object-oriented programming language developed by James Gosling at Sun Microsystems in the early 1990s. He was unhappy using c++ programming language so he developed java. Java Old name was “Oak” 1995 “Oak” was renamed as Java as a core components of Sun microsystems java platform Java is a consolidation language, designed to absorb the strengths of earlier languages and ignore their weakness 15 15 Java Features Simple Platform-Independent (portable) Object-Oriented Robust and Secure Compiled and interpreted Distributed Multithreaded Architecture-Neutral High-performance 16 16 8 Java Features (Cont.) Simple Java syntax is based on C++ (greatly simplified and improved). Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. Platform-Independent (portable) Write once run anywhere Java is completely portable; the same Java code will run identically on different platforms, regardless of hardware compatibility or operating systems. Object oriented OOP is a popular programming approach that is replacing traditional procedural programming which offers great flexibility, modularity, clarity, and reusability All coding and data reside within objects and classes 17 17 Java Features (Cont.) Robust and secure Exception handling built-in strong type checking automatic garbage collection so all memory corruptions or unauthorized memory accesses are impossible strong memory management (no-pointers). Programs run inside the virtual machine sandbox Compiled and interpreted Code is complied to bytecode that are interpreted by a JVM Distributed Creating applications on networks. Multiple programmers can work together on a single project from multiple remote locations and share data and programs. 18 18 9 Java Features (Cont.) Multithreaded It allows to handle multiple tasks simultaneously (run multiple threads ) Architecture-Neutral no implementation dependent features e.g. size of primitive types is fixed. High-performance The new JVM uses the technology known as just-in-time (JIT) compilation. With JIT complier the interpreted code gives almost the native code speed. 19 19 Java Applications According to sun, 3 billions devices run java. There are mainly four types of applications: Stand alone applications Also known as desktop applications There are traditional software i.e., we need to install to every machine Examples: Acrobat reader, Media player, Antivirus, etc. Web applications These applications that runs on the server side and creates a dynamic pages. Technologies such as JSP, Servlet, spring, etc. are used for creating web applications in java. Example: google.com, uqu.edu.sa (student information system (SIS)) Enterprise applications An application that is distributed in nature, such as Banking applications. It has advantages of high-level security, load balancing, and clustering. Mobile applications An application which is created for mobile devices Currently, Android and java Me are used for creating mobile applications. Other applications such as robotics, games, etc. 20 https://www.slideshare.net/MadishettyPrathibha/introduction-java-237623974?from_search=16 20 10 Java Development Environment Java programs normally go through five phases Program is created in an Phase 1 Editor Disk editor and stored on disk in a file ending with.java. Phase 2 Compiler Disk Compiler creates bytecodes and stores them on disk in a Primary file ending with.class. Memory Phase 3 Class Loader Class loader reads.class files containing bytecodes from disk and puts those Disk.. bytecodes in memory..... Primary Memory Bytecode Phase 4 Verifier Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s.. security restrictions..... Primary Memory Phase 5 Interpreter Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing.. data values as the program.... executes. 21 21 Step1: Creating and Editing Programs This step involves using an editor to type a Java program (source code), then save it on a secondary storage device, such as hard drive. Well-known editors: Notepad on Windows and TestEdit on OS X Integrated development environments (IDEs) provide tools that support the software development process, such as editors, debuggers for locating logic errors (errors that cause programs to execute incorrectly) and more. Popular Java IDEs: Eclipse (www.eclipse.org ) NetBeans (www.netbeans.org) IntelliJ IDEA (www.jetbrains.com) VSCode (code.visualstudio.com) -- Not just Java! All Java source code files are ending with the.java extension. 22 22 11 Step2: Compiling a Java Program into Byte- codes The Java compiler does not translate a Java program into machine language for a particular computer. Instead, it translates a Java program into byte-code. Byte-code is the machine language for a hypothetical computer (or interpreter) called the Java Virtual Machine. The byte-code file has a.class file extension byte-code represents the tasks to execute in the execution phase 23 23 Step2: Compiling a Java Program into Byte- codes Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the Java platform Bytecodes are platform independent They do not depend on a particular hardware platform Bytecodes are portable The same bytecodes can execute on any platform containing a JVM that understands the version of Java in which the bytecodes were compiled Bytecode can be sent over the Internet and used anywhere in the world. This makes Java suitable for Internet applications. 24 24 12 Step3: Loading a Program into Memory The Java Virtual Machine (JVM) places the program in memory to execute it—this process is known as loading The JVM’s class loader (also called the linker ) takes the.class files containing the program’s byte-codes and transfers them to main memory. A class loader automatically connects the classes together. 25 25 Step 4: Bytecode Verification As the classes are loaded, the bytecode verifier checks their bytecodes to ensures that they’re valid and don’t violate Java’s security restrictions Java enforces strong security to make sure that Java programs arriving over the network do not damage your files or your system (as computer viruses and worms might) 26 26 13 Step5: Interpreting and Execution The Java Virtual Machine (JVM) translates each byte-code instruction and executes the resulting machine-language instructions before translating the next byte-code instruction. Most Java programs today are executed using a Just-In-Time or JIT compiler. JIT compilers interact with the Java Virtual Machine (JVM) at run time and compile suitable bytecode sequences into native machine code that can be sent directly to a computer's processor (CPU). 27 27 Recap! Java code is usually compiled into platform independent bytecode (class files). The JVM is able to load the class files and execute the java bytecode via the java interpreter. Even though this bytecode is usually interpreted, it might also be compiled into native machine code using the JVM’s Just-In-Time (JIT). Unlike the normal compiler, the JIT compiler compiles the code (bytecode) only when required. So, JVM provides a platform-independent way of executing Java bytecode. It is a keystone of the write-once run any ware value of java programs. https://www.slideshare.net/wso2.org/java-performance-and-profiling 28 28 14 Core Concepts in Java source 29 29 Java Runtime Environment (JRE) It Includes: The Java Virtual Machine (JVM) with a Jit compiler Java class libraries It is used to: read bytecode run the same bytecode on any machine with a JVM (run any java program) 30 30 15 Java Development Kit (JDK) It includes: JRE Java Compiler Other tools (include Java libraries, Java source compilers, Java debuggers, bundling and deployment tools) It is used to simply compile bytecode (.java ->.class) 31 31 Recap: Compiling and Running a Java Program (Overall Picture) IDE JDK JRE 32 32 16 Programming Basics 33 33 What Is Programming? Programming is a process of problem solving. We could think of programming as the process of breaking down a large, complex task into smaller and smaller subtasks. The process continues until the subtasks are simple enough to be performed with the electronic circuits provided by the hardware. 34 34 17 Problem Solving Problem solving is the process of identifying a problem, developing an algorithm, and eventually implementing a computer program Analyzing Developing Coding Testing Problem Algorithm An algorithm is a set of finite, sequential, and unambiguous steps usually described in natural language to solve a given problem. Two most common methods to represent algorithms are: Flowcharts is a graphical representation of an algorithm Pseudocode is a description of the instructions that human could understand and so the computer could execute later on 35 35 Problem Solving (cont.) Step1: Analyze the problem Understand the overall problem Define problem requirements Does program require user interaction? If yes, What is the Input? What is the expected Output? Design steps (algorithm) to solve the problem https://www.youtube.com/watch?v=KYhy6Q914C0 36 36 18 Problem Solving (cont.) Step2: Implement the algorithm Implement the algorithm in code (coding) Verify that the algorithm works (testing) Step3: Maintenance Use and modify the program if the problem domain changes. (any changes required) If the problem is complex, divide it into sub problems. Analyze each sub-problem as above - The person who writes a program is called the programmer. - The person who interacts with the program is called the user. 37 37 Programming Paradigms In programming, we have two paradigms: Procedural/Functional paradigm, in which programs consist of a collection of procedures and functions that operate on data. Example: Fortran, Pascal, and C The object-oriented paradigm, in which programs are viewed instead as a collection of “objects” for which the data and the operations acting on that data are encapsulated into integrated units. Example: Smalltalk, C++, and Java. 38 38 19 What Is Programming? (cont.) Few basic instructions that could be found in every programming language: input: Get data from the keyboard, a file, a sensor, or some other device. output: Display data on the screen, or send data to a file or other device. math: Perform basic mathematical operations like addition and division. decision: Check for certain conditions and execute the appropriate code. repetition: Perform an action repeatedly, usually with some variation. 39 39 41 Reserved Keywords Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. Reserved words are always spelled with all lowercase letters. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. We must use reserved words only for their intended purpose. For example, we can't use the word class for any other purpose than defining a class 40 20 42 Reserved Keywords The Java reserved words: abstract else interface switch assert enum long synchronized boolean extends native this break false new throw byte final null throws case finally package transient catch float private true char for protected try class goto public void const if return volatile continue implements short while default import static do instanceof strictfp double int super 41 Compiling and Running a Java Program or Class A Java program consists of one or more classes, which must be compiled before running the program. Each class should be in a separate file. 42 42 21 Compiling and Running a Java Program or Class The name of the file should be the same as the name of the class. The class to run will contain the statement (only ONE class must include the main method) public static void main(String[] args) All this will become clearer when we begin to write Java classes! 43 43 Testing and Debugging The best way to write a correct program is to carefully design the necessary objects and the algorithms for the objects’ methods. Then you carefully translate everything into a programming language such as Java. So, to eliminate errors is to avoid them in the first place :) Test your program with appropriate test cases (some where the answer is known), discover and fix any errors, then retest. 44 44 22 Programming Errors A mistake in a program is called a bug. The process of eliminating errors is called debugging. Three kinds of errors: Syntax errors Runtime errors Logic errors 45 45 Syntax Errors The syntax of a programming language is the set of grammatical rules for the correct way to write a program. Thus, syntax errors are the grammatical mistakes in a program The compiler catches syntax errors and prints an error message. Example: missing semicolon. 46 46 23 Runtime Errors Errors that are detected when your program is running, but not during compilation When the computer detects an error, it terminates the program and prints an error message. The error message might not be easy to understand, but at least you will know that something is wrong! Example: attempting to divide by 0. 47 47 Logic Errors Errors that are not detected during compilation or while running, but which cause the program to produce incorrect results. Logic errors will not give you any error messages. For this reason, logic errors are the hardest kind of error to locate. Example: an attempt to calculate a Fahrenheit temperature from a Celsius temperature by multiplying by 9/5 and adding 23 instead of 32 48 48 24 Basic Java Program Structure There are 5 components that we usually include in a Java program, which are: [ Documentation Statement(s) ] [ Package Statement ] [ Import Statement(s) ] public class className { public static void main(String[] args) { [ Body of Main Function ] } } 49 49 Documentation Statement(s) It includes "comments" lines that we use to describe the whole idea behind the program and its methods The compiler ignores these comments during the time of execution. It helps other programmers to easily understand your code! There are three types of comments that Java supports:- Single line Comment Multi-line Comment Javadoc Comment 50 50 25 Single-line Comments A single-line comment can begin with //. Everything after these symbols and to the end of the line is treated as a comment and is ignored by the compiler. Example double radius; //in centimeters 51 51 Multi-lines Comments A multi-lines comment can begin with Everything between these symbols is treated as a comment and is ignored by the compiler. Example 52 52 26 Package Statement Package statements are used to declare classes in a collection called package They are optional! Only have one package statement is allowed to be in a program Package statements have to be at the beginning of the code before any class or interface declaration! Note, this statement declares that all Syntax: the classes and interfaces defined in package name; this source file are a part of the people package Example: package people; A package is a library or container of a group of related classes (think of it as a folder in a file directory) that could be user-defined or have been defined by java already (built-in). 53 53 Import Statement(s) Import statements are used to refer to set of classes that are located in other packages Always write the import statements after the package statement and before the class declaration. Syntax: import packageName.className; Example: import java.util.Date; //imports the date class 54 54 27 Class Definition(s) A class is a collection of variables and methods that operate on the attributes or fields. Syntax: Notes: the public keyword means this class is accessible by any other //attributes classes //methods The curly brackets are used to make sure that the statements belong to one class 55 55 31 Class Declaration and Name Class declaration (header) 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 Java class declaration normally contain one or more methods. One of these classes must have the main method Class name By convention, begin with a capital letter and capitalize Camel Case is a style used to capitalizing the initial letter of each word and omitting spaces (e.g., SampleClassName). A class name is an identifier—a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces Java is case sensitive—uppercase and lowercase letters are distinct 56 28 Main Method The main method is the place where the program execution actually starts. Meaning the computer follows the order specified by the Java statements. main method is an essential part of any program in Java main method is declared inside the class definition Syntax: main method — where the JVM starts running the program 57 57 Main Method (cont.) Where: public means that this method can be used outside of this class static means that there is no need to create an object to access this a method void means that this method does not return any value String[] args is an array named as args where each element is a string. We use it to pass the input to the program when we run the Java code through a console Why is the main method declared static?! Declaring main as static allows the JVM to invoke main without creating an instance of the class 58 58 29 46 Blocks A pair of curly braces in a program forms a block that groups components of a program Examples: o Class block, method block, statement block,... public class Hello { public static void main (String[] args) Class { block System.out.println("Hello World!"); Method } block } A left brace, {, begins the body of every class declaration A corresponding right brace, }, must end each class declaration It is a syntax error if braces do not occur in the matching pairs 59 58 Block Styles You may use next-line or end-of-line style for braces You should stick with one style in the whole code Next- public class Test line { style public static void main(String[] args) { System.out.println("Block Styles"); } } End-of-line style public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } 60 30 58 Example Which code do you think it is more readable? Code Sample 1: public class Test1 { public static void main ( String[] args ) { System.out.println("On a withered branch"); System.out.println("A crow has just alighted:"); System.out.println("Nightfall in autumn."); } } Code Sample 2: public class Test1 { public static void main ( String[] args ) { System.out.println( "On a withered branch"); System. out.println("A crow has just alighted:"); System.out.println("Nightfall in autumn."); }} 61 45 Java Statements Is a command for the computer to do something. MOST statement in Java should be followed by a semicolon ( ;) Methods are built out of statements. The statements in a method are placed between braces {and }as in this example public class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } } There are several types of statements in Java. For example, declaration, assignment, control, and loop statements. 62 31 34 Java Statements (cont.) System.out.println("Hello World!"); statement Class Object Method Instructs the computer to display a string of characters contained between the double quotation marks on the screen White-space characters in strings are not ignored by the compiler The string in the parentheses the argument to the method Positions the output cursor at the beginning of the next line on the screen (command window) Strings cannot span multiple lines of code System.out.println("Hello World!"); 63 Recap! Proper Indentation and Spacing: Use blank lines to separate segments of the code. Use space characters and code indentations to enhance program readability Write each statement in a separate line , allowing end of line comment. For example: System.out.println("Hello World!"); // print a string Appropriate Comments: Starts your program with a comment that states the purpose of the program, the author, time and date of the last program modifications Write a comment before each class, documenting the purpose of the class Write a comment before each method, documenting the purpose of the method Write an end of line (single line) comment, documenting the purpose of the statement 64 64 32 Recap! In every Java source file, you might see the following 5 components: //comments package name; import className; public class className{ //attributes //methods public static void main (String[]args){ //statements } } 65 65 A First Java Application 66 66 33 A First Java Application Sample screen output 67 67 36 Tracing The Program Enter main method //This program prints Hello World! public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } } 68 34 37 Tracing The Program (Cont.) Execute Statement //This program prints Hello World! public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } } 69 38 Tracing The Program (Cont.) //This program prints Hello World! public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } } print a message to the console 70 35 Questions? 71 71 36

Use Quizgecko on...
Browser
Browser