Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Lecture 1 introduction to_computersb(2)

242 views

Published on

Lecturrrrre

Published in: Education
  • Login to see the comments

  • Be the first to like this

Lecture 1 introduction to_computersb(2)

  1. 1. Dr Delessy-Gassant COP2800– JAVA PROGRAMMING
  2. 2. INTRODUCTION TO COMPUTERS What is a computer? A computer is an electronic device, operating under the control of instructions (software) stored in its own memory A computer contains many electric, electronic, and mechanical components known as hardware: Input devices Output devices System unit Storage devices Communication devices
  3. 3. THE COMPONENTS OF A COMPUTER
  4. 4. INTRODUCTION TO COMPUTERS The system unit typically includes: Processor The brain Memory Stores data temporarily Drive bays Hard disks, CD / DVD drives Power supply unit Sound cards Video cards
  5. 5. INTRODUCTION TO COMPUTERS The processor, a.k.a. central processing unit (CPU), interprets and carries out the basic instructions that operate a computer. Made of billions of transistors (in 2010) Transistor = electronically controlled switch, made form semi-conductor materials It contains: a control unit: coordinates most of the operations in the computer an arithmetic logic unit (ALU) performs arithmetic, comparison, and other operations Registers Small amount of storage
  6. 6. INTRODUCTION TO COMPUTERS The main memory, a.k.a. RAM: content is volatile (will be erased when the system is shut down), but access time is faster  used as working storage by the CPU
  7. 7. 1-7 COMPUTER SYSTEMS: HARDWARE MAIN MEMORY Commonly known as random-access memory (RAM) RAM contains: currently running programs data used by those programs. RAM is divided into units called bytes. A byte consists of eight bits that may be either on or off.
  8. 8. 1-8 COMPUTER SYSTEMS: HARDWARE MAIN MEMORY A bit is either on or off: 1 = on 0 = off The bits form a pattern that represents a character or a number. Each byte in memory is assigned a unique number known as an address. RAM is volatile, which means that when the computer is turned off, the contents of RAM are erased.
  9. 9. 1-9 COMPUTER SYSTEMS: HARDWARE MAIN MEMORY Main memory can be visualized as a column or row of cells. A section of memory is called a byte. A section of two or four bytes is often called a word. 0x000 0x001 0x002 0x003 0x004 0x005 0x006 0x007 1 0 1 0 1 0 1 0 A byte is made up of 8 bits.
  10. 10. INTRODUCTION TO COMPUTERS • The Von Neumann architecture • Conceptual model that inspired almost every machine today • >The program is stored as general data in memory Output devices commands: read, write Contro l Unit Registers ALU CPU Memory Input devices data, instructions
  11. 11. INTRODUCTION TO COMPUTERS The fetch-execute cycle: Once a computer has been powered on it performs a continuous cycle of the following: 1. Fetch next instruction from memory 2. Decode the instruction commands: devices read, write 3. Possibly fetch data from memory 4. Execute the instruction 5. Store results back to memory Contro l Unit Registers ALU CPU Memory Output Input devices data, instructions
  12. 12. INTRODUCTION TO COMPUTERS The electronic circuits of a computer can recognize and execute a limited set of simple instructions, the machine’s instruction set Instructions carried out by a computer are simple: Arithmetic or logic operations Ex: addition, multiplication, XOR Operations that move data from memory/peripherals to the CPU and the other way around display a movie on a screen, accept input from the keyboard
  13. 13. INTRODUCTION TO COMPUTERS Data representation Computers are digital: data is stored in terms of discrete values The binary system uses two unique digits (0 and 1) Bits and bytes Even instructions are eventually stored in terms of 0’s and 1’s Machine instructions encoded in terms of 0’s and 1’s constitute the machine language Demo: http://www.onlinedisassembler.com/
  14. 14. INTRODUCTION TO COMPUTERS What is a program? A series of instructions given by a programmer to a computer in order to perform a task Tasks carried out by computers are more and more complex. Examples of useful programs? But you don’t want to program using machine language! Too tedious! Cf. OllyDgb Programming languages make it easier for programmers to write programs They define nice (intuitive) ways to talk to a computer
  15. 15. INTRODUCTION TO COMPUTERS Programming languages are classified into 3 levels: Machine language Assembly languages more intuitive to the programmer, but still (low level) i.e., close to machine language Cf. http://www.onlinedisassembler.com/ High-level languages More user-friendly to the programmer Includes abstractions such as loops, switches, … Ex: Java, C/C++, C#, and many more
  16. 16. INTRODUCTION TO COMPUTERS Programming languages are of 2 categories: Compiled: 1. The source code (high-level language instructions) is translated into machine code by a compiler 2. The machine code is saved in an executable file 3. The executable file is run  faster Ex: C/C++ Interpreted: 1. The source code (high-level language instructions) is saved on the disk 2. An interpreter is executed, and the source code is brought to memory. The interpreter translates, on-the-fly, the source code into machine code, thus executing the high level program  slower, but more portable Ex: Java, C#, Python
  17. 17. INTRODUCTION TO COMPUTERS Java is a special case: It uses a mix of compilation and interpretation: 1. The source code is compiled into an intermediary language, the bytecode, which is saved on the disk 2. The bytecode is brought to memory and interpreted at runtime Editor Compiler Interpreter The programmer writes some code in the Java language and saves its .java files to Java the disk instructions are translated in an intermediate format and saved into .class files on The .class files are the brought disk in memory, and each instruction from the bytecode is translated into machine language that is run Your program will not be perfect the first time (errors) Practically, programming is often a cycle
  18. 18. INTRODUCTION TO COMPUTERS Other characteristics of Java: Popular Object-oriented Simple Portable Robust/secure
  19. 19. INTRODUCTION TO COMPUTERS In the labs, we use a powerful tool: Netbeans Editor Compiler Interpreter And more…
  20. 20. INTRODUCTION TO COMPUTERS Example of Java applications Web applications Server side >Blackboard (parts) Client side (Applets embedded in web pages) >Blackboard widgets Enterprise applications Desktop applications With GUI (Graphic User Interface) >Netbeans Console applications Apps for mobile devices on Blackberry, Android, palm, and maybe some day on iPhone? …
  21. 21. INTRODUCTION TO JAVA APPLICATIONS (One of )the simplest Java program:
  22. 22. INTRODUCTION TO JAVA APPLICATIONS First remarks: Java is case-sensitive ‘Class ‘ is not the same as ‘class’ Java does not care about the colors, or the appearance of the source code Colors are added automatically by Netbeans to help the programmer read the text
  23. 23. INTRODUCTION TO JAVA APPLICATIONS Comments Are portions of the source code that will be ignored by the compiler  not translated in bytecode Used for documentation purposes > in this class, you are encouraged to comment your code (part of the grade for an assignment)
  24. 24. INTRODUCTION TO JAVA APPLICATIONS Comments 2 kinds of comments: 1. Comments that runs on one single line Start with ‘//’ and end at the end of the line Typically makes a particular part of your code easier to understand 2. Comments that can run on multiple lines Start with ‘/*’ and end with ‘*/’ Used to make your code easier to use, typically by other programmers Used for administrative purposes, e.g. name of the author, assignment number, …
  25. 25. INTRODUCTION TO JAVA APPLICATIONS Java programs consist in a series of statements This is a simple statement i.e. an instruction written in a high-level language Simple statements This is another composite statement This is a composite statement Typically end in ‘;’ Composite statements contain blocks of other statements  Nested statements This is how programs are recursively constructed! Examples of statements Each type of statement has a precise syntax
  26. 26. INTRODUCTION TO JAVA APPLICATIONS Blocks Blocks consist of successive statements contained between an opening and a closing brace Example of blocks Everything This is another between ‘{‘ and ‘}’ block makes up a block
  27. 27. INTRODUCTION TO JAVA APPLICATIONS Java is an object-oriented language Advanced java programmers manipulate objects Prior to manipulating any object, a class for this kind of object must be defined You can subsequently instantiate as many objects of that class that you want The outermost statement of a java source file is a class definition This statement is a class definition
  28. 28. INTRODUCTION TO JAVA APPLICATIONS Simple class definition Type reserved words ‘public class’ Choose and type a name (a.k.a. identifier) for your class E.g. SimplestClassEver Type an opening brace and a closing brace
  29. 29. INTRODUCTION TO JAVA APPLICATIONS Choosing a valid identifier (=name) An identifier is composed of a sequence of: Unicode letters (include letters from non-english alphabets), digits, underscores (‘_’) dollar signs (‘$’) An identifier cannot begin with a digit An identifier cannot be a reserved word (e.g. ‘class’, ‘public’, ‘static’, …)
  30. 30. INTRODUCTION TO JAVA APPLICATIONS Every application needs a point of entry This statement is the definition of the main method of the application identifies the first instruction to be executed In Java, the point of entry is the main method Methods have a signature to differentiate them from other methods Methods have a body Succession of statements that must be carried out when the method is executed Methods will be discussed soon in more detail… This is the signature of the maiEnv mereytthhoindg inside this block is the body of the main method
  31. 31. INTRODUCTION TO JAVA APPLICATIONS How to write a main method 1. Type the main method signature (always the same) 2. Type the ‘{‘ and ‘}’ 3. Insert your statements within the body of the main method
  32. 32. INTRODUCTION TO JAVA APPLICATIONS Your first practical statement: basic output uses the ‘System’ class from the core library to print a message to the screen The message must be between double quotes! It is provided as an argument to the ‘println’ method of the System output stream. How do you write a basic output statement 1. Type the call to ‘println’ from the output stream of the System object: System.out.println(); 2. Insert you message between the braces, 3. Message must be surrounded by “”
  33. 33. INTRODUCTION TO JAVA APPLICATIONS Your first practical statement: basic output The message cannot include ‘”’ sign (double quote) or the single quote sign What if your message needs to include ” or ‘?  precede it with the escape character ‘’ Ex: In order to print the message: “I will be there,” he said
  34. 34. INTRODUCTION TO JAVA APPLICATIONS Final remarks Code formatting does not matter Indentation does not matter to Java (But it does matter to a human readers) =
  35. 35. INTRODUCTION TO JAVA APPLICATIONS Final remarks Code formatting does not matter White spaces (space, tabulations, blank lines..) can be used interchangeably =
  36. 36. INTRODUCTION TO JAVA APPLICATIONS Summary Comments are omitted by the compiler Simple and composite statements are used to recursively build program source files The outermost statement of a source file is a class definition If your class needs to do something, it needs a point of entry, the main method, and inside this method at least one practical statement (e.g. message printing)
  37. 37. VARIABLES  Concept of variable computers, (and more precisely, programmers) needs to organize the data to be remembered a variable is a named memory location that is used to hold temporary data in a program  facility for storing temporary data
  38. 38. VARIABLES A variable is characterized by: a name The programmer can choose any identifier, using rules (cf. Lect 1) Include alphabetic Unicode characters, digits, underscore, and ‘$’ The first character cannot be a digit, The identifier cannot be a reserved word. a value a bunch of 0s and 1s stored in this memory location can be changed during the execution of the program a type helps java remember how the programmer wants to interpret these 1s and 0s
  39. 39. VARIABLES In Java, there are 8 primitive data types byte raw 0s and 1s  you won't need to interpret the data Use cases: data just needs to be transferred onto the network, or to a file... short, int, long you want to interpret the 0s and 1s as integers, e.g. -2, 0, 4555, -3245, ... Use cases: you want to store the number of sales in your shop today, the number of students in a class,…
  40. 40. VARIABLES In Java, there are 8 primitive types float, double you want to interpret the 0s and 1s as real numbers, for which the accurate value is not important Use cases: you want the computer to remember the surface area of a house, e.g. ~1545.86 sq.ft. Counter example: the amount of money in your customers 'accounts (You want a precise value!) Warning: When using float and double, round-off errors may accumulate! char You want to interpret the 0s and 1s as characters uses: You want to store students' middle initials
  41. 41. VARIABLES In Java, there are 8 primitive types boolean You want the computer to interpret the 0s and 1s as one of the 2 values: 'true' or 'false' Use cases: You want to store whether or not a member of your club has paid his membership this year
  42. 42. VARIABLES Several java types are used for representing integers.. id for real numbers… How do I choose ?? It depends on the range of values that you want to represent… while saving memory space, i.e, reducing the memory footprint of your program For real numbers, precision is also important: ~16 decimal digits for double vs ~7 decimal digits for float
  43. 43. VARIABLES Several java types are used for representing integers.. id for real numbers… How do I choose ?? It depends on the range of values that you want to represent while saving memory space, i.e, reducing the memory footprint of your program Warning: if a large number is stored in a location that is too small, there is an overflow!  no error is reported! An incorrect number is stored! For real number, precision is also important
  44. 44. VARIABLES Ex: number of sales per day in all Walmart stores? Number of sales per day in your local computer shop?
  45. 45. VARIABLES String is not a primitive data type We will see soon that it is are pre-defined class Strings represent sequences of characters But because they are so useful, we are going to use them early
  46. 46. VARIABLES Categories of variables In Java, there are 4 categories of variables Local variables: Defined in a block In the first part of this class, we concentrate on local variables only! Instance variables, (a.k.a. non-static fields) Defined within a class, with a different value for instance of the class Class variables (a.k.a. static fields) Defined within a class Formal parameters Defined within a method
  47. 47. VARIABLES Using variables 1. Choose a name for your variable 2. Declare your variable 3. Initialize your variable
  48. 48. VARIABLES Using variables 1. Choose a name for your variable The identifier chosen must be valid (cf. rules) The identifier should be meaningful ex: numOfSales is more meaningful than ‘n’ or ‘number’
  49. 49. VARIABLES Using variables 2. Declare your variable That is, let java know that you are going to use this variable, by declaring its name and type  Use a declaration statement within a block <Type> <identifier>; e.g.: int numOfSales;
  50. 50. VARIABLES Using variables 3. Initialize your variable  Use an assignment statement. (you assign a value to a variable) <identifier> = <literal>; e.g.: numOfSales = 0;
  51. 51. VARIABLES What is a literal? the source code representation of a fixed value boolean ‘true’ or ‘false’ e.g.: boolean hasPaidMembership; hasPaidMembership = false;
  52. 52. VARIABLES What is a literal? byte, short, int Usual decimal notation, i.e. an optional minus sign, followed by a sequence of digits from 0 to 9 e.g.: int numOfSales ; numOfSales = 4; Or using octal notation (digits from 0-7, use prefix 0) e.g.: int octalNum; octalNum = 011; //9 in decimal Or using hexadecimal notation (digits from 0-9 and A-F, use prefix 0x) e.g.: int MACAddress; MACAddress = 0x10EA; //4330 in decimal
  53. 53. VARIABLES What is a literal? long same as int, but followed by a ‘L’ or a ‘l’ e.g.: in decimal long numOfWalMartSales; numOfWalMartSales = 0L; e.g. in decimal: long ycoordinate; ycoordinate = -3000000000L; e.g. in hexadecimal: long longHexadecimalValue; longHexadecimalValue = -0x13A26E612L; // 5270595090 in decimal
  54. 54. VARIABLES What is a literal? double Using the usual decimal notation: optional minus or plus sign followed by a sequence of digits , and an optional decimal point Optionally followed by a ‘d’ or ‘D’ e.g.: double surfaceArea; surfaceArea = +123.54; Or using the scientific notation: product of a number and a power of 10 , the number is followed by ‘e’ or ‘E’ and the power of ten e.g. declaring and initializing a variable to -6.1×10−9 double doubleValue; doubleValue = -6.1e-9;
  55. 55. VARIABLES What is a literal? float Same as double, but followed by a ‘f’ or a ‘F’ e.g.: float surfaceArea; surfaceArea = +123.54f; e.g. in scientific notation float floatValue; floatValue = -6.1e-9F;
  56. 56. VARIABLES What is a literal? char Any Unicode character, between simple quotes e.g.: char middleInitial; middleInitial = 'F'; If your editor does not allow it, you can insert a character’s unicode code: e.g. ñ char specialChar; specialChar = 'u00F1';
  57. 57. VARIABLES What is a literal? String Any sequence of Unicode characters, between double quotes e.g.: String firstName; firstName = "Nelly"; If your editor does not allow it, you can insert a character’s unicode code: e.g. String fullName; fullName = "Mr Fernando Cau00F1ero ";
  58. 58. VARIABLES You are ready to use local variables! Choose a name for your variable Declare your variable Initialize your variable
  59. 59. VARIABLES Shortcuts Declare and initialize a variable in a single statement <type> <identifier> = <literal>; e.g.: char middleInitial = 'F'; float floatValue = -6.1e-9F; int numOfSales = 3; String sentence = “My name is";
  60. 60. VARIABLES Shortcuts Declare multiple variables of the same type in a single statement <type> <identifier1>, <identifier2>, …; e.g.: char middleInitial, gender; float floatValue, surfaceArea, ratio; int numOfSales, age; String firstName, middleName, lastName;
  61. 61. VARIABLES Shortcuts Declare and initialize multiple variables in a single statement <type> <identifier1> = <literal1>, <identifier2> = <literal2>, <literal3>, …; e.g.: char middleInitial ='F', gender; float floatValue, surfaceArea = 2.3, ratio; int numOfSales = 9, age = 6; String firstName = "Nelly", middleName, lastName;
  62. 62. VARIABLES Scope Where do I declare local variables?  in any block, within a method In what parts of the source code can I access a local variable (i.e., what is the scope of a local variable)?  the rest of the block in which the declaration appears
  63. 63. VARIABLES Variable output The output statement described in the previous lecture also works with variables of primitive data types and with String variables:  omit the double quotes and specify the name of the variable between the braces
  64. 64. VARIABLES Variable output You can mix constant strings and variables by using ‘+’ ‘+’ is used for concatenating a string and the value of your variable, e.g.: Produces:

×