King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 - Introduction to computing Lecture 1 : Introduction Components of a Personal Computer Questions : - what are the input devices ? - what are the output devices ? Motherboard A motherboard, provides the electrical connections by which the other components of the system communicate and hosts the central processing unit as well as other subsystems and devices . Motherboard example : Acer E360 CPU (Central Processing Unit) The Central Processing Unit (CPU) or processor is the portion of a computer system that carries out the instructions of a computer program and is the primary element carrying out the computer's functions. Example: (3 + 2) = 5 In an addition operation, the arithmetic logic unit (ALU) will be connected to a set of inputs and a set of outputs. The inputs provide the numbers to be added, and the outputs will contain the final sum . 3 5 2 Memory Memory refers to computer components, devices, and recording media that hold digital data used for computing for some interval of time. There are mainly three types of memory : CPU memory Registers Cache Main memory (RAM): Data has to be in main memory so that CPU can access it Volatile: lost when program exits; computer shuts off Hard Disk, CD, etc. Persistent This is where you keep the data for long-term storage Main Memory … Address 1002 1003 1004 1005 Cell Memory is divided into Many memory locations (cells) Each memory cell has a numeric address, which uniquely identifies it Each cell contains a data value, e.g. 22 Main Memory … Main Memory … The word “Hello.” stored in 6 memory cells Memory units : Bits and Bytes Bit -- most basic unit of memory 1 or 0, on or off 1 Byte = 8 bits In a computer, data values are stored as a sequence of bits 1004 2 1004 00000010 1005 7 1005 00000111 Program / CPU / Memory Interaction Example: Input read a number from keyboard Add 1 to it Output it on screen Keyboard 1 RAM 1 1 CPU 2 RAM 2 2 Monitor What is programming? What is a program? A (software) program is a list of instructions intended to a computer The list must be ordered correctly A program has inputs and outputs Each instruction tells the computer to do something (an action, a calculation, a comparison) Program Execution A program tells the CPU how to manipulate and/or move information Programming is about processing information Take some input, manipulate it in some way, and produce a particular output Program Inputs Manipulation Outputs Example 1 : Recipe for Scrambled Eggs Ingredients (Inputs) : two eggs, tablespoon of oil, salt Instructions (program): Add oil to pan Heat pan on stove Crack eggs into pan Add salt Mix until light and flakey Output: scrambled eggs Example 2 : Currency Exchange Task : convert an amount of money in some currency (e.g. US Dollars) to another one (e.g. Saudi Riyals). Input: • Amount Source Currency Desired Currency Instructions Look up in table current exchange rate for the selected currencies Calculate result as amount * exchange rate Output: result Programming language A programming language is the language used to write programs A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements A programming language has a syntax and semantics There are several types of languages (functional, Object-Oriented, etc.) In this course we focus on Java programming language. Java • Java is a programming language originally developed by James Gosling at Sun Microsystems • It was first released in 1995. • The language derives much of its syntax from C and C++. • But has a simpler object model and fewer lowlevel facilities than C and C++. Why Java ? Currently, Java is the most popular language in the world ! Why Java ? 1. Simple • Get started quickly 2. Concise • Write less code 3. Object-oriented • Better quality code 4. Portable • Architecture neutral (write once run anywhere) 5. Secure • More appropriate for Internet Portability of Java Classical model : Java model : Portability of Java Write once, run anywhere :Because applications written in the Java programming language are compiled into machineindependent bytecodes, they run consistently on any Java platform . A Java Program A Java Program A Java program consists of one or more classes A Java class consists of one or more methods A Java method consists of one or more statements Java classes Java Methods A Java Program A Java program resides in one or more files. The file name of a Java program has extension .java. One of the classes of a Java program is called the driver class. The name of the driver class must be the same as the name of its Java file. (Java is case sensitive. So EX1 is different from ex1.) The diver class must contain a method called main. The execution of Java program starts from the main method of the driver class. Example of a Java Program Example of a Java Program Class name Main method Class body Instruction Example of a Java Program Also notice: Curly braces { } Example of a Java Program Also notice: Curly braces { } Parentheses ( ) Example of a Java Program Also notice: Curly braces { } Square brackets [ ] Parentheses ( ) Example of a Java Program Also notice: A pair of braces { } define a block Compiling and running a program Type in your program Save the program Store all your files in one directory for now Give the program the same name as the class Compile the program this produces a .class file Translates the program into something the computer can understand and execute (Java bytecode) Run the program Observe the result and adjust the program if necessary Edit Public class Adven /* This program is an Arit */ Public class /* Text Editor public static void main /* Program statements g System.out.print(“Wel } } Adventure.java Compile - With Errors Public class Adven /* This program is an Arit */ public static void main /* Program statements g System.print(“Welcome } Compiler } Adventure.java Errors and Warnings ------------------Error : The method print( String) is undefined for Type System Compile - Success Public class Adven /* This program is an Arit */ public static void main /* Program statements g System.out.print(“Wel } Compiler } Adventure.java 001011010001011101 1011010001011101110 101000101110111010110100010 111011101011010001011101110 101101000101110111010110100 010111011100010111011101011 010001011101110010111011101 011010001011101110010111011 101011010001011101110010111 011101011010001011101110010 111011101011010001011101110 0101110 Adventure.class Run Program Fred 1 Adventure Welcome to the Arithm The date is Monday Sep What is your name?Fred Well Fred, after a day The cube appears to be You find a Green door, The door closes behind There is a feel of mat End King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 1 : Expressions and Assignment Outline July 17, 2016 Declaration Statements Primitive Data Types Identifiers Assignment Statements Arithmetic Operators and Expressions Precedence Rules Round-Off Errors in Floating-Point Numbers Integer and Floating-Point Division The % Operator Type Casting Increment and Decrement Operators ICS102: Expressions & Assignment 38 Variable variable In mathematics: x + y = 17 variable variable July 17, 2016 In Computer Science: a variable is an identifier (usually a letter, word, or phrase) that is linked to a value stored in the computer's memory x = 5; ICS102: Expressions & Assignment 39 Variable Declaration Every variable in a Java program must be declared before it is used int numberOfBeans; numberOfBeans = 10; A variable declaration tells the compiler what kind of data (type) will be stored in the variable Basic types in Java are called primitive types - Primitive Data Types July 17, 2016 ICS102: Expressions & Assignment 41 Names of variables (Identifiers) int variable = 3; The name of a variable must not start with a digit, and all the characters must be letters, digits, or the underscore symbol Java is a case-sensitive language: Rate, rate, and RATE are the names of three different variables It is not allowed to use reserved words as variable names: public July 17, 2016 class void ICS102: Expressions & Assignment static 42 Assignment Statements In Java, the assignment statement is used to change the value of a variable An assignment statement consists of a variable on the left side of the operator, and an expression on the right side of the operator Variable = Expression; Example temperature = 98.6; count = numberOfBeans; July 17, 2016 ICS102: Expressions & Assignment 44 Assignment Statements With Primitive Types When an assignment statement is executed, the expression is first evaluated, and then the variable on the left-hand side of the equal sign is set equal to the value of the expression distance = rate * time; Note that a variable can occur on both sides of the assignment operator count = count + 2; The assignment operator is automatically executed from rightto-left, so assignment statements can be chained number2 = number1 = 3; July 17, 2016 ICS102: Expressions & Assignment 45 Initialize Variables … int initialCount = 50; int finalCount; What is the value of initialCount? What is the value of finalCount? A variable that has been declared but that has not yet been given a value by some means is said to be uninitialized In certain cases an uninitialized variable is given a default value July 17, 2016 It is best not to rely on this and always initialize your variables ICS102: Expressions & Assignment 46 Shorthand Assignment Statements … e.g. variable += 3; Shorthand assignment notation combines the assignment operator (=) and an arithmetic operator The general form is Variable Op = Expression July 17, 2016 Example: Equivalent To: count += 2; count = count + 2; sum -= discount; sum = sum – discount; bonus *= 2; bonus = bonus * 2; time /= rushFactor; time = time / rushFactor; change %= 100; change = change % 100; amount *= count1 + count2; amount = amount * (count1 + count2); ICS102: Expressions & Assignment 47 Arithmetic Operators and Expressions These are : + (addition), - (subtraction), * (multiplication), / (division), and % (modulo, remainder) If an arithmetic operator is combined with int operands, then the resulting type is int If an arithmetic operator is combined with one or two double operands, then the resulting type is double If different types are combined in an expression, then the resulting type is the right-most type on the following list that is found within the expression byteshortintlongfloatdouble Char July 17, 2016 ICS102: Expressions & Assignment 48 Assignment Compatibility Is this legal ? int x = 2.99; And this ? double variable = 2; July 17, 2016 ICS102: Expressions & Assignment 49 Assignment Compatibility More generally, a value of any type in the following list can be assigned to a variable of any type that appears to the right of it byteshortintlongfloatdouble Note that as your move down the list from left to right, the range of allowed values for the types becomes larger int x = 5.8; error double y = 6; ok short i = 14.3; error float s = 9.2; ok For these, you need type cast. next slide July 17, 2016 ICS102: Expressions & Assignment 50 Type Casting A type cast takes a value of one type and produces a value of another type with an "equivalent" value int x = (int) 2.9; When type casting from a floating-point to an integer type, the number is truncated, not rounded: (int) 2.9 evaluates to 2, not 3 July 17, 2016 ICS102: Expressions & Assignment 51 Integer and Floating-Point Division When one or both operands are a floating-point type, division results in a floating-point type 15.0/2 evaluates to 7.5 When both operands are integer types, division results in an integer type Any fractional part is discarded The number is not rounded 15/2 evaluates to 7 July 17, 2016 Be careful to make at least one of the operands a floating-point type if the fractional portion is needed ICS102: Expressions & Assignment 52 y 17, 2016 Precedence Rules If some or all of the parentheses in an expression are omitted, Java will follow precedence rules to determine, in effect, where to place them. High precedence First: The unray operators: +, -, ++, --, and ! Second: The binary arithmetic operators: *, /. And % Third: The binary arithmetic operators: + and Low precedence e.g. int x = y = -2 + 5 * 7 – 7 / 2 % 5; y 17, 2016 Precedence Rules If some or all of the parentheses in an expression are omitted, Java will follow precedence rules to determine, in effect, where to place them. High precedence First: The unray operators: +, -, ++, --, and ! Second: The binary arithmetic operators: *, /. And % Third: The binary arithmetic operators: + and Low precedence e.g. int x = y = -2 + 5 * 7 – 7 / 2 % 5; This will be evaluated as.. int x = (y = ((-2 + (5 * 7)) – ((7 / 2) % 5))); 35 3 3 33 30 ICS102: Expressions & Assignment 54 The % (modulo) Operator The % operator is used with operands of type int to recover the information lost after performing integer division 15/2 evaluates to the quotient 7 15%2 evaluates to the remainder 1 The % operator can be used to count by 2's, 3's, or any other number July 17, 2016 To count by twos, perform the operation number % 2, and when the result is 0, number is even ICS102: Expressions & Assignment 55 Increment and Decrement Operators The increment operator (++) adds one to the value of a variable The decrement operator (--) subtracts one from the value of a variable July 17, 2016 If n is equal to 2, then n++ or ++n will change the value of n to 3 If n is equal to 4, then n-- or --n will change the value of n to 3 ICS102: Expressions & Assignment 56 Increment and Decrement Operators When either operator precedes its variable, and is part of an expression, then the expression is evaluated using the changed value of the variable When either operator follows its variable, and is part of an expression, then the expression is evaluated using the original value of the variable, and only then is the variable value changed July 17, 2016 If n is equal to 2, then 2*(++n) evaluates to 6 If n is equal to 2, then 2*(n++) evaluates to 4 ICS102: Expressions & Assignment 57 The end Important to do at home : - read section 1.2 of the textbook King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 3 : Math What is a library? Most programming languages come with a library. A library is a collection of classes for common system services such as : math operations, input/output routines, etc. The Java library is called : API (Application Programming Interface). Java API is organized into packages. Today we will see a class of this library : Math. The Math Class The Math class provides a number of standard mathematical methods The Math class has two predefined constants, E (e, the base of the natural logarithm system) and PI (, 3.1415 . . .) area = Math.PI * radius * radius; Some Methods in the Class Math … Some Methods in the Class Math … Some Methods in the Class Math … Some Methods in the Class Math … Some Methods in the Class Math The end Exercises King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 4 : String Class Outline The String Class Explicit String Objects String variables are References String Methods Escape Sequences July 17, 2016 ICS102: The class String 70 The String Class There is no primitive type for strings in Java The class (type) String is a predefined class in Java that is used to store and process strings A String object is a sequence of characters that is treated as a single value. When any “ ” (quote) appears, a String object is created automatically. System.out.println("Hello, how are you?"); A variable of type String can be given the value of a String object String sentence = "Java is Fun!"; 71 July 17, 2016 ICS102: The class String Explicit String Objects A declaration and object creation are needed for instances of the String class. For example, String name1; name1 = new String("Salam"); We normally use shorthand notation (only for Strings): These two statements are equivalent. String name1; name1 = "Salam"; July 17, 2016 ICS102: The class String 72 String variables are References… Code A String word1, word2; word1 = new String("Java"); word2 = word1; State of Memory word1 L word2 L After A is executed Both word1 and word2 are allocated memory (to store references), but the objects themselves are not yet created, so they both contain null. String variables are References… Code String B One String object is created and assigned to word1, so word1 contains the address of this object. word1, word2; word1 = new String("Java"); word2 = word1; word1 String Java State of Memory word2 L After B July 17, 2016 is executed ICS102: The class String 74 String variables are References. Code String Content of word1, which is an address, is assigned to word2, making word2 refer to the same object. word1, word2; word1 = new String("Java"); C word2 = word1; word1 String Java State of Memory word2 After C July 17, 2016 is executed ICS102: The class String 75 String Methods String Concatenation String Length String Starting Position Other Useful String Operators July 17, 2016 ICS102: The class String 76 String Concatenation Concatenation: Using the + operator on two (or more) strings in order to connect them to form one longer string String greeting = "Hello "; String course = "ICS102"; System.out.println(greeting + course); Hello ICS102 A new String object is created operands are not affected. When a string is combined with almost any other type of item, the result is a string int x = 6, y = 10; String s = ".Hi."; System.out.println(s System.out.println(x System.out.println(s System.out.println(s July 17, 2016 + + + + x); y + s); (x + y)); x + y); ICS102: The class String .Hi.6 16.Hi. .Hi.16 .Hi.610 77 String Length We determine the number of characters in a String with the length method. String name = "Espresso!"; String str2 = ""; String str3; name.length(); 9 str2.length(); 0 str3.length(); Error! Error because no object is created for str3, so it is a null. String Starting Position Individual characters in a String can be accessed with the charAt method. Position of a character or String can be found with indexOf method. String text = "Java is fun."; text This variable refers to the whole string. text.indexOf("is") The method returns the position of the string “is”. text.charAt(8) The method returns the character at position # 8. Other Useful String Operators Method equals Meaning Checks if two strings are equal. (Use equalsIgnoreCase for case insensitive) str1.equals( str2 ) compareTo Compares the two strings. str1.compareTo( str2 ) substring Extracts the a substring from a string. str1.substring( 1, 4 ) str1.substring( 5 ) trim toUpperCase Removes the leading and trailing spaces. str1.trim( ) Converts a string to all caps string. (Use toLowerCase for all small) str1.toUpperCase( ) Escape Sequences … A backslash (\) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character July 17, 2016 The character following the backslash does not have its usual meaning Although it is formed using two symbols, it is regarded as a single character ICS102: The class String 81 Escape Sequences July 17, 2016 ICS102: The class String 82 The end Important to do at home : - read section 1.3 (pages 65-77) Exercises For each of these expressions determine its result String text = "Java Programming"; text.substring(0, text.length( ) text.substring(8, text.substring(0, text.substring(5, 4) 12) 1) + text.substring(7, 9) 6) + text.substring(text.length() – 3, text.length()) Exercises Write a program that initializes a String object to “Hello the World”, prints its length, then erases the word “the” from that String. King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 5 : Screen Output and Console Input System.out.println To write of the screen: System.out.println(“Hello World"); Package name Class name Method name The item to be printed on the screen It is possible to print more than one item: A plus sign is used to connect more than one item System.out.println("The answer is " + 42); Every invocation of println generates a new line after it finishes System.out.println(“Hello World”); System.out.println(“Hello World”); Hello World Hello World println Versus print To stay on the same line, use print System.out.print(“Hello World ”); System.out.print(“Hello World ”); Hello World Hello World The print method is like println, except that it does not generate a new line With println, the next output goes on a new line With print, the next output goes on the same line Console Input What if we want to let the user choose the values he wants to use ? We can prompt the user by console (keyboard) input Console Input Import instruction Create Scanner object Read a first integer and assign it to variable a Read a second integer and assign it to variable b Console Input Details .. Java includes a class for doing simple keyboard input named the Scanner class In order to use the Scanner class, a program must include the following line near the start of the file: import java.util.Scanner This statement tells Java to Make the Scanner class available to the program Find the Scanner class in a library of classes (i.e., Java package) named java.util Details .. The following line creates an object of the class Scanner and names the object keyboard : Scanner keyboard = new Scanner(System.in); Although a name like keyboard is often used, a Scanner object can be given any name For example, in the following code the Scanner object is named scannerObject Scanner scannerObject = new Scanner(System.in); Once a Scanner object has been created, a program can then use that object to perform keyboard input using methods of the Scanner class Details .. The method nextInt reads one int value typed in at the keyboard and assigns it to a variable: int numberOfPods = keyboard.nextInt(); The method nextDouble reads one double value typed in at the keyboard and assigns it to a variable: double d1 = keyboard.nextDouble(); Multiple inputs must be separated by whitespace and read by multiple invocations of the appropriate method Whitespace is any string of characters, such as blank spaces, tabs, and line breaks that print out as white space on paper Details .. The method next reads one string of non-whitespace characters delimited by whitespace characters such as blanks or the beginning or end of a line Given the code String word1 = keyboard.next(); String word2 = keyboard.next(); and the input line jelly beans The value of word1 would be jelly, and the value of word2 would be beans Details .. The method nextLine reads an entire line of keyboard input The code, String line = keyboard.nextLine(); reads in an entire line and places the string that is read into the variable line The end of an input line is indicated by the escape sequence '\n‘ This is the character input when the Enter key is pressed On the screen it is indicated by the ending of one line and the beginning of the next line When nextLine reads a line of text, it reads the '\n' character, so the next reading of input begins on the next line However, the '\n' does not become part of the string value returned (e.g., the string named by the variable line above does not end with the '\n' character) Dealing with the Line Terminator, '\n‘ … The method nextLine of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off This can cause problems when combining it with different methods for reading from the keyboard such as nextInt Given the code, Scanner keyboard = new Scanner(System.in); int n = keyboard.nextInt(); String s1 = keyboard.nextLine(); String s2 = keyboard.nextLine(); and the input, 2 Heads are better than 1 head. what are the values of n, s1, and s2? Dealing with the Line Terminator, '\n' Given the code and input on the previous slide n will be equal to 2, s1 will be equal to "", and s2 will be equal to "heads are better than“ If the following results were desired instead n equal to 2, s1 equal to "heads are better than", and s2 equal to "1 head“ then an extra invocation of nextLine would be needed to get rid of the end of line character ('\n') Dealing with the Line Terminator, '\n' Given the code Scanner keyboard = new Scanner(System.in); int n = keyboard.nextInt(); keyboard.nextLine(); String s1 = keyboard.nextLine(); String s2 = keyboard.nextLine(); and the input, 2 Heads are better than 1 head. We get the desired result: n equal to 2, s1 equal to "heads are better than", and s2 equal to "1 head“ Programming Tip … Prompt for Input A program should always prompt the user when he or she needs to input some data: System.out.println( "Enter the number of pods followed by"); System.out.println("the number of peas in a pod:"); The end Important to do at home : - read chapter 2 (pages 90-118) Methods in the Class Scanner … Methods in the Class Scanner …. Methods in the Class Scanner King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 6 : File Input Output Outline Text Files Stream Reading from a Text File using Scanner Writing to a File IOException Pitfalls Text Files Files that are designed to be read by human beings, and that can be read or written with an editor are called text files Text files can also be called ASCII files because the data they contain uses an ASCII encoding scheme An advantage of text files is that they are usually the same on all computers, so that they can move from one computer to another ASCII Encoding Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream is called an input stream If the data flows out of a program, then the stream is called an output stream file program Streams Input streams can flow from the keyboard or from a file System.in is an input stream that connects to the keyboard Scanner keyboard = new Scanner(System.in); Output streams can flow to a screen or to a file System.out is an output stream that connects to the screen System.out.println("Output stream"); Reading From a Text File Using Scanner The class Scanner can be used for reading from the keyboard as well as reading from a text file Simply replace the argument System.in (to the Scanner constructor) with a suitable stream that is connected to the text file Scanner StreamObject = new Scanner(new FileInputStream(FileName)); Methods of the Scanner class for reading input behave the same whether reading from the keyboard or reading from a text file For example, the nextInt and nextLine methods Reading Input from a Text File Using Scanner Reading Input from a Text File Using Scanner Reading Input from a Text File Using Scanner Reading Input from a Text File Using Scanner Writing to a Text File The class PrintWriter is a stream class that can be used to write to a text file An object of the class PrintWriter has the methods print and println These are similar to the System.out methods of the same names, but are used for text file output, not screen output Writing to a Text File All the file I/O classes that follow are in the package java.io, so a program that uses PrintWriter will start with a set of import statements: import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; The class PrintWriter has no constructor that takes a file name as its argument It uses another class, FileOutputStream, to convert a file name to an object that can be used as the argument to its (the PrintWriter) constructor Writing to a Text File A stream of the class PrintWriter is created and connected to a text file for writing as follows: PrintWriter outputStreamName; outputStreamName = new PrintWriter(new FileOutputStream(FileName)); The class FileOutputStream takes a string representing the file name as its argument The class PrintWriter takes the anonymous FileOutputStream object as its argument Writing to a Text File This produces an object of the class PrintWriter that is connected to the file FileName The process of connecting a stream to a file is called opening If the file already exists, then doing this causes the old contents to be lost If the file does not exist, then a new, empty file named FileName is created the file After doing this, the methods print and println can be used to write to the file Writing to a Text File Path Names When a file name is not in the same directory, the path name must be given First way: Scanner in = new Scanner(new FileInputStream(“c:/user/data.txt")); Second way: Scanner in = new Scanner(new FileInputStream(“c:\\user\\data.txt")); The end Important to do at home : - read chapter 10 from 602 to 615 King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 7 : Selection Structures Outline Block statement Branching Statements July 17, 2016 Simple if statement if-else statement if-else-elseif statement switch statement Nested if statements ICS102: The course 124 Introduction to selection structures Write a program that accepts an integer value from the user and then: prints “positive” if the integer is larger or equal to zero Prints “negative” if the integer is less than zero Block Statement A block statement consists of one or more Java statements enclosed in braces. Example of a block statement: { } statement 1; statement 2; … statement n; Blocks can be nested. A block statement can be used anywhere that a single statement can be used. July 17, 2016 ICS102: The course 126 Branching Statement July 17, 2016 A branching statement consists of one or more block statements The execution of a block statement in a branching statement is controlled by a boolean expression which we call a condition. There are mainly the following four types of branching statement. Simple if If-else If-elseif-else switch ICS102: The course 127 Simple if Statement … Simple if statement has the following structure: if ( <boolean_expression> ) { <then_block> } The boolean_expression must be enclosed in parentheses If the boolean_expression is true, then the then_block is executed. Otherwise it will NOT execute. Boolean Expression if ( testScore >= 95 ) { System.out.println("You are a good student"); Then Block } July 17, 2016 ICS102: The course 128 -- Simple if Statement … Control Flow of if: true testScore >= 95? false July 17, 2016 System.out.println ("You are a good student"); ICS102: The course Chapter 6 - 129 … -- Simple if Statement } Example: Design and write a Java program prints the absolute value of a number. import java.util.Scanner; class absolute { public static void main(String [] args) { Scanner kb = new Scanner(System.in); System.out.print(“Enter a number: “); double x = kb.nextDouble(); double y = x; if( y < 0) { y = -y; } System.out.print(“The absolute value of “ + x + “ is “ + y); } July 17, 2016 ICS102: The course 130 -- if-else Statement … An if-else statement chooses between two alternative statements based on the value of a Boolean expression If the boolean_expression is true, then the then_block is executed, otherwise the else_block is executed. if (<boolean_expression>) { <then_block> } else { <else_block> } Boolean Expression if (testScore < 50) { Then Block System.out.println("You did not pass"); } else { Else Block July 17, 2016 System.out.println("You did pass"); } ICS102: The course 131 -- if-else Statement … false true testScore < 50 ? System.out.println ("You did pass"); July 17, 2016 System.out.println ("You did not pass"); ICS102: The course Chapter 6 - 132 Compound Statements You have to use braces if the <then> or <else> block has multiple statements. if only one statement is there braces are optional but it is advisable to always use them to enhance readability if (testScore < 70) { System.out.println("You did not pass"); System.out.println("Try harder next time"); Then Block } else { System.out.println("You did pass"); System.out.println("Keep up the good work"); Else Block } July 17, 2016 ICS102: The course Chapter 6 - 133 … -- if-else Statement Design and write a Java program which prints the difference of two numbers. Scanner kb = new Scanner(System.in); System.out.println(“Enter the value of the first number: “); double first = kb.nextDouble(); System.out.println(“Enter the value of the second number: “); double second = kb.nextDouble(); if ( first > second) { double diff = first – second; System.out.println(diff); } else { double diff = second – first; System.out.println(diff); } July 17, 2016 ICS102: The course 134 -- if-elseif-else Statement … The multiway if-else statement is simply a normal if-else statement that nests another ifelse statement at every else branch July 17, 2016 It is indented differently from other nested statements All of the Boolean_Expressions are aligned with one another, and their corresponding actions are also aligned with one another The Boolean_Expressions are evaluated in order until one that evaluates to true is found The final else is optional ICS102: The course 135 if - else- if if (score >= 85) { System.out.println(”Grade is A"); } else if (score >= 75) { System.out.println(”Grade is B"); Test Score 85 score 75 score 85 65 score 75 } else if (score >= 65) { System.out.println(”Grade is C"); } else if (score >= 50) { 50 score 65 score 50 System.out.println(”Grade is D"); Grade A B C D N } else { System.out.println(”Grade is N"); } July 17, 2016 ICS102: The course Chapter 6 - 137 - The switch Statement … The switch statement is the only other kind of Java statement that implements multiway branching When a switch statement is evaluated, one of a number of different branches is executed The choice of which branch to execute is determined by a controlling expression enclosed in parentheses after the keyword switch July 17, 2016 The controlling expression must evaluate to a char, int, short, or byte ICS102: The course 138 Syntax for the switch Statement switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> } switch ( Arithmetic Expression fanSpeed ) { case 1: Case Label System.out.println("That's low"); break; case 2: System.out.println("That's medium"); break; Case Body case 3: System.out.println("That's high"); break; July 17, 2016 } ICS102: The course Chapter 6 - 139 switch With break Statements switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; } N == 1? false N == 2? x = 10; break; true x = 20; false N == 3? false July 17, 2016 true ICS102: The course break; true x = 30; break; Chapter 6 - 140 The switch Statement with default switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> default: <default body> } switch ( binaryDigit ) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; default: System.out.println("That's not a binary digit"); break; } July 17, 2016 ICS102: The course Chapter 6 - 141 switch With No break Statements N == 1? switch ( N ) { case 1: x = 10; false case 2: x = 20; N == 2? case 3: x = 30; } true x = 10; true x = 20; false N == 3? true x = 30; false July 17, 2016 ICS102: The course Chapter 6 - 142 … -- The switch Statement double y = 30; double z = 20; Scanner kb = new Scanner(System.in); System.out.println("1. add "); System.out.println("2. Subtract "); System.out.println("3. Multiply "); System.out.println("Enter a value: between 1 and 3 "); int x = kb.nextInt(); switch (x) { case 1: System.out.println(z + y); break; case 2: System.out.println(z - y); break; case 3: System.out.println(z * y); break; default: System.out.println("Wrong Choice."); break; } July 17, 2016 ICS102: The course 143 - Nested if Statements … One of the block statements of a branching statement can be another if statement. The inner if statement is executed when the enclosing block statement is executed If statements can be nested to many levels If(<boolean_expresion_1>) { Statement_1; <block_statement_2>; Statement_3; } if(<boolean_expression_2>) { Statement_2A; Statement_2B: } Statement_2A and 2B are only executed if boolean_expresions 1 and 2 are true. July 17, 2016 ICS102: The course 144 - Nested if Statements … if (testScore >= 50) { if (studentAge < 10) { System.out.println("You did a great job"); } else { Nested if System.out.println("You did pass"); } } else { //test score < 50 System.out.println("You did not pass"); } July 17, 2016 ICS102: The course Chapter 6 - 145 - Nested if Statements … false System.out.println ("You did not pass"); true testScore >= 50 ? false System.out.println ("You did pass"); July 17, 2016 ICS102: The course studentAge < 10 ? inner if true System.out.println ("You did a great job"); Chapter 6 - 146 Nested simple-if if (x < y) { if (x < z) System.out.println("Hello"); } else { System.out.println("Good bye"); } means if (x < y) { if (x < z) { System.out.println("Hello"); } } else { System.out.println("Good bye"); } July 17, 2016 ICS102: The course Chapter 6 - 147 Nested if-else if (x < y) if (x < z) System.out.println("Hello"); else System.out.println("Good bye"); really means if (x < y) { if (x < z) { System.out.println("Hello"); } else { System.out.println("Good bye"); } } July 17, 2016 ICS102: The course Chapter 6 - 148 The end Important to do at home : - read section 3.1 (pages 128-140) Exercises Write a Java program that reads an integer using Scanner then tests if it is odd or even. The format of the input and output should be as follows: Please enter a number: 10 10 is even. Write a program that reads three integers and prints them in increasing order. Example: Please enter three integers: 9, 5, 21 The integers in increasing order are: 5 9 21 Exercises Write a program that reads an integer between 0 and 10 and then prints the word corresponding to the number. Example: Please enter a number between 0 and 10: 7 You entered: seven King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 8 : Boolean Expressions Outline Introduction Java Comparison Operators Evaluating Boolean Expressions Pitfall: Using == with Strings Lexicographic and Alphabetical Order Building Boolean Expressions Truth Tables Short-Circuit and Complete Evaluation Precedence and Associativity Rules Evaluating Expressions Rules for Evaluating Expressions July 17, 2016 ICS102: The course 153 - Introduction A Boolean expression is an expression that is either true or false The simplest Boolean expressions compare the value of two expressions time < limit yourScore == myScore July 17, 2016 Note that Java uses two equal signs (==) to perform equality testing: A single equal sign (=) is used only for assignment ICS102: The course 154 - Java Comparison Operators July 17, 2016 ICS102: The course 155 - Evaluating Boolean Expressions Even though Boolean expressions are used to control branch and loop statements, Boolean expressions can exist independently as well A Boolean variable can be given the value of a Boolean expression by using an assignment statement A Boolean expression can be evaluated in the same way that an arithmetic expression is evaluated The only difference is that arithmetic expressions produce a number as a result, while Boolean expressions produce either true or false as their result boolean madeIt = (time < limit) && (limit < max); July 17, 2016 ICS102: The course 156 - Pitfall: Using == with Strings The equality comparison operator (==) can correctly test two values of a primitive type However, when applied to two objects such as objects of the String class, == tests to see if they are stored in the same memory location, not whether or not they have the same value In order to test two strings to see if they have equal values, use the method equals, or equalsIgnoreCase string1.equals(string2) string1.equalsIgnoreCase(string2) July 17, 2016 ICS102: The course 157 - Lexicographic and Alphabetical Order Lexicographic ordering is the same as ASCII ordering, and includes letters, numbers, and other characters All uppercase letters are in alphabetic order, and all lowercase letters are in alphabetic order, but all uppercase letters come before lowercase letters If s1 and s2 are two variables of type String that have been given String values, then s1.compareTo(s2) returns: A negative number if s1 is before s2 in lexicographic ordering zero if the two strings are equal. A positive number if s2 comes before s1 When performing an alphabetic comparison of strings (rather than a lexicographic comparison) that consist of a mix of lowercase and uppercase letters, use the compareToIgnoreCase method instead July 17, 2016 ICS102: The course 158 - Building Boolean Expressions When two Boolean expressions are combined using the "and" (&&) operator, the entire expression is true provided both expressions are true When two Boolean expressions are combined using the "or" (||) operator, the entire expression is true as long as one of the expressions is true The expression is false only if both expressions are false Any Boolean expression can be negated using the ! Operator Otherwise the expression is false Place the expression in parentheses and place the ! operator in front of it Unlike mathematical notation, strings of inequalities must be joined by && July 17, 2016 Use (min < result) && (result < max) rather than result < max ICS102: The course min < 159 - Truth Tables July 17, 2016 ICS102: The course 160 - Short-Circuit and Complete Evaluation Consider x > y || x > z The expression is evaluated left to right. If x > y is true, then there’s no need to evaluate x > z because the whole expression will be true whether x > z is true or not. This also happens when we use first expression is false. && operator and the To stop the evaluation once the result of the whole expression is known is called short-circuit evaluation or lazy evaluation July 17, 2016 ICS102: The course 161 - Short-Circuit and Complete Evaluation What would happen if the short-circuit evaluation is not done for the following expression? kids != 0 && toys/kids >= 2 There are times when using short-circuit evaluation can prevent a runtime error Sometimes it is preferable to always evaluate both expressions, i.e., request complete evaluation July 17, 2016 In this case, use the & and | operators instead of && and || ICS102: The course 162 - Precedence and Associativity Rules … Boolean and arithmetic expressions need not be fully parenthesized If some or all of the parentheses are omitted, Java will follow precedence and associativity rules (summarized in the following table) to determine the order of operations July 17, 2016 If one operator occurs higher in the table than another, it has higher precedence, and is grouped with its operands before the operator of lower precedence If two operators have the same precedence, then associativity rules determine which is grouped first ICS102: The course 163 Precedence and Associativity Rules Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious July 17, 2016 ICS102: The course 164 The end Important to do at home : - read chapter 3 from 141 to 153 165 King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 9 : While and DoWhile loops Outline Introduction while Loop do-while Loop July 17, 2016 ICS102: while & do-while 167 - Introduction Loops in Java are similar to those in other high-level languages Java has three types of loop statements: The while The do-while The for The code that is repeated in a loop is called the body of the loop Each repetition of the loop body is called an iteration of the loop July 17, 2016 ICS102: while & do-while 168 - while loop A while statement is used to repeat a portion of code (i.e., the loop body) based on the evaluation of a Boolean expression The Boolean expression is checked before the loop body is executed July 17, 2016 When false, the loop body is not executed at all Before the execution of each following iteration of the loop body, the Boolean expression is checked again If true, the loop body is executed again If false, the loop statement ends The loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ }) ICS102: while & do-while 169 -- while Loop Syntax while ( <boolean expression> ) <statement> //only one statement OR while ( <boolean expression> ) { <statement> //many Boolean Expression } while ( sum Statement (loop body) number <= 100 = sum + number; number = number + 1; ) { These statements are executed as long as number is less than or equal to 100. } July 17, 2016 ICS102: while & do-while 170 -- while Loop Control flow int sum = 0, number = 1 number <= 100 ? false true sum = sum + number; number = number + 1; July 17, 2016 ICS102: while & do-while 171 -do-while Loop A do-while statement is used to execute a portion of code (i.e., the loop body), and then repeat it based on the evaluation of a Boolean expression The loop body is executed at least once The Boolean expression is checked after each iteration of the loop body July 17, 2016 The Boolean expression is checked after the loop body is executed If true, the loop body is executed again If false, the loop statement ends Don't forget to put a semicolon after the Boolean expression Like the while statement, the loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ({ }) ICS102: while & do-while 172 -- do-while Loop Syntax do { <statement> } while (<boolean expression>); do { sum += number; Statement (loop body) number++; These statements are executed as long as sum is less than or equal to 1,000,000. } while (sum <= 1000000) ; Boolean Expression July 17, 2016 ICS102: while & do-while 173 -- do-while Loop Control Flow int sum = 0, number = 1 sum += number; number++; sum <= 1000000 ? true false July 17, 2016 ICS102: while & do-while 174 Examples July 17, 2016 ICS102: while & do-while 175 Questions 1. 2. 3. July 17, 2016 Write a Java program which computes the sum of all the odd numbers between 0 and 100. Write a Java program which reads 20 numbers using a scanner and computes their average. Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the number of even numbers. Assume the input integers are all positive. Use a negative number as a sentinel. ICS102: while & do-while 176 Solution using while loop July 17, 2016 ICS102: while & do-while 177 Q1 Solution Write a Java program which computes the sum of all the odd numbers between 0 and 100. int n =1; int sum = 0; while (n < 100) { sum += n; n = n + 2; } System.out.println(“The sum is “ + sum); July 17, 2016 ICS102: while & do-while 178 Q2 Solution Write a Java program which reads 20 numbers using a scanner and computes their average. Scanner kb = new Scanner(System.in); int cnt = 0; double x; double sum = 0; While (cnt < 20) { x = kb.nextDouble(); sum += x; cnt++; } System.out.println(“The Average is “ + sum/cnt); July 17, 2016 ICS102: while & do-while 179 Q3 Solution Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel. Scanner kb = new Scanner(System.in); int even_cnt = 0; int odd_cnt = 0; double x = kb.nextInt(); while (x > 0) { if ( mod(x,2) == 0) even_cnt++; else odd_cnt++; x = kb.nextInt(); } System.out.println(“Even numbers are = “ + even_count); System.out.println(“Odd numbers are = “ + odd_count); July 17, 2016 ICS102: while & do-while 180 Solution using do-while loop July 17, 2016 ICS102: while & do-while 181 Q1 Solution Write a Java program which computes the sum of all the odd numbers between 0 and 100. int n = 1; int sum = 0; do { sum += n; n = n + 2; } While ( n < 100) System.out.println(“The sum is “ + sum); July 17, 2016 ICS102: while & do-while 182 Q2 Solution Write a Java program which reads 20 numbers using a scanner and computes their average. Scanner kb = new Scanner(System.in); int cnt = 0; double x; double sum = 0; do { System.out.println(“Enter a number”); x = kb.nextDouble(); sum += x; cnt++; } while (cnt < 20); System.out.println(“The Average is “ + sum/cnt); July 17, 2016 ICS102: while & do-while 183 Q3 Solution Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel. Scanner kb = new Scanner(System.in); int even_cnt = 0; int odd_cnt = 0; double x = kb.nextInt(); if (x > 0) { do { if ( mod(x,2) == 0) even_cnt++; else odd_cnt++; x = kb.nextInt(); } while ( x > 0) } System.out.println(“Even numbers are = “ + even_count); System.out.println(“Odd numbers are = “ + odd_count); July 17, 2016 ICS102: while & do-while 184 Additional Slides July 17, 2016 ICS102: while & do-while 185 while Loop Pitfall - 1 1 int product = 0; while ( product < 500000 ) { product = product * 5; } Infinite Loops 2 Both loops will not terminate because the boolean expressions will never become false. int count = 1; while ( count != 10 ) { count = count + 2; } July 17, 2016 ICS102: while & do-while Chapter 7 - 186 while Loop Pitfall - 2 1 double count = 0.0; while ( count != 1.0 ) { count = count + 1.0/3.0; } Using Real Numbers 2 double count = 0.0; Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory. while ( count <= 1.0 ) { count = count + 1.0/3.0; } July 17, 2016 ICS102: while & do-while Chapter 7 - 187 while Loop Pitfall - 3 1 Goal: Execute the loop body 10 times. count = 1; 2 count = while (count < 10) { while (count <= 10) { . . . . . . count++; count++; } 3 1; } count = 0; 4 while (count <= 10) { count = 0; while (count < 10) { . . . . . . count++; count++; } } 1 and 3 exhibit off-by-one error. July 17, 2016 ICS102: while & do-while Chapter 7 - 188 Checklist for Repetition Control 1. Watch out for the off-by-one error (OBOE). 2. Make sure the loop body contains a statement that will eventually cause the loop to terminate. 3. Make sure the loop repeats exactly the correct number of times. July 17, 2016 ICS102: while & do-while Chapter 7 - 189 The end Important to do at home : - read section 3.3 (pages 160-166) King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 10 : The for-loop and nested loops Outline The for Statement Syntax Semantics of the for Statement Nested Loops continue, break, and exit Statements - The for Statement Syntax for (Initializing; Boolean_Expression; Update) Block Note that the three control expressions are separated by two, not three, semicolons Note that there is no semicolon after the closing parenthesis at the beginning of the loop - The for Statement The for statement is most commonly used to step through an integer variable in equal increments It begins with the keyword for, followed by three expressions in parentheses that describe what to do with one or more controlling variables The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration The second expression determines when the loop should end, based on the evaluation of a Boolean expression before each iteration The third expression tells how the control variable or variables are updated after each iteration of the loop body Example - Nested Loops Loops can be nested, just like other Java structures When nested, the inner loop iterates from beginning to end for each single iteration of the outer loop for (Initializing; Boolean_Expression; Update) Block 1 Block 1 can contain other loop statements as follows Block 1 for (Initializing; Boolean_Expression; Update) Block 2 - Nested Loops Loops can be nested, just like other Java structures When nested, the inner loop iterates from beginning to end for each single iteration of the outer loop int rowNum, columnNum; for (rowNum = 1; rowNum <=3; rowNum++) { for (columnNum = 1; columnNum <=2; columnNum++) System.out.print(" row " + rowNum + " column " + columnNum); System.out.println(); } Continue, break, and exit Statements Class test { public static void main( String [] args) { for (int i = 0; i < 10; i++) { statement 1; statement 2; if( cond) continue; statement 3; statement 4; } statement 5; statement 6; } } Continue, break, and exit Statements Class test { public static void main( String [] args) { for (int I = 0; I < 10; i++) { statement 1; statement 2; if( cond) break; statement 3; statement 4; } statement 5; statement 6; } } Continue, break, and exit Statements Class test { public static void main( String [] args) { for (int I = 0; I < 10; i++) { statement 1; statement 2; if( cond) System.exit(0); statement 3; statement 4; } statement 5; statement 6; } } For-loop examples Questions 1. 2. 3. July 17, 2016 Write a Java program which computes the sum of all the odd numbers between 0 and 100. Write a Java program which reads 20 numbers using a scanner and computes their average. Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the number of even numbers. Assume the input integers are all positive. Use a negative number as a sentinel. ICS102: while & do-while 202 Q1 Solution Write a Java program which computes the sum of all the odd numbers between 0 and 100. int sum = 0; for( int n = 1; n <= 100; n = n + 2) { sum += n; } System.out.println(“The sum is “ + sum); July 17, 2016 ICS102: while & do-while 203 Q2 Solution Write a Java program which reads 20 numbers using a scanner and computes their average. Scanner kb = new Scanner(System.in); double x; double sum = 0; While (int cnt = 0; cnt < 20; cnt++) { System.out.println(“Enter a number”); x = kb.nextDouble(); sum += x; } System.out.println(“The Average is “ + sum/cnt); July 17, 2016 ICS102: while & do-while 204 Q3 Solution Write a Java program which reads unknown number of integers using a scanner and counts the number of odd numbers and the count of even numbers. Assume the input integers are all positive. Use any negative number as a sentinel. Scanner kb = new Scanner(System.in); int even_cnt = 0; int odd_cnt = 0; int n; For(;;) { n = kb.nextInt(); if (n < 0) break; else if ( mod(n,2) == 0) even_cnt++; else odd_cnt++; } System.out.println(“Even = “ + even_count + “ odd = “ odd_cnt); July 17, 2016 ICS102: while & do-while 205 Nested-loop examples Questions 1. Write a java program which gives the following output 1 22 333 4444 55555 2. Write a java program which prints all the prime numbers less than 1000. Q1 Solution Write a java program which gives the following output 1 22 333 4444 55555 for(int k = 1; k <= 5; k++) { For ( int j = 1; j <=k; j++) System.out.print(k); System.out.println(); } Q2 solution Write a java program which prints all the prime numbers less than 1000. int n, j; for(int k = 2; k < 100; k++) { n = 0; j = 2; while(n == 0 && j < k/2) { if (mod(k,j) == 0) n++; j++; } if( n ==0) System.out.println(k); } The end Important to do at home : - read section 3.3 (pages 166-177) King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 11 : Arrays Arrays An array is an ordered list of values Entire array has A single name scores Each value has A numeric index [0] 79 [1] [2] [3] 62 98 57 An array of size N is indexed from zero to N-1 This array holds 4 values that are indexed from 0 to 3 Processing Array Elements Access individual elements of an array using: the name of the array a number (index or subscript) that tells which of the element of the array What value is stored in scores[2]? scores [0] 79 [1] [2] [3] 62 98 57 Arrays For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 87; scores[first] = scores[first] + 2; Avg = (scores[0] + scores[1])/2; System.out.println (“Max = " + scores[3]); Arrays The values held in an array are called array elements Array elements are of the same type The element type can be a primitive type or an object reference. Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. In Java, the array itself is an object Therefore the name of the array is a object reference variable, and the array itself must be instantiated Declaring an Array Defining an array Type [] name Where: •This declares the handle only •Initialized to null •Stores an address when arrays are created Type specifies the kind of values the array stores the brackets [ ] indicate this is an array name is the handle to access the array Declaring an Array The scores array could be declared as follows: double [] scores = new double [4]; The above statement will: allocate block of memory to hold 4 doubles initialize block with zeros create a handle or a pointer or a reference called scores store address of the block in scores scores Handle [0] [1] [2] 0.0 0.0 0.0 Block [3] 0.0 Syntax Forms ElementType [] arrayName; ElementType [] arrayName = new ElementType [size]; ElementType [] arrayName = array-literal; Where: ElementType is any type arrayName is the handle for the array array-literal is a list of literals enclosed in curly braces { } Declaring Arrays Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; Bounds Checking Once an array is created, it has a fixed size An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1) The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking Bounds Checking For example, if the array scores can hold 100 values, it can be indexed using only the numbers 0 to 99 If scores has the value 100, then the following reference will cause an exception to be thrown: System.out.println (scores[count]); Often for loop is used to process array. It’s common to introduce off-by-one errors when using arrays problem for (int index=0; index <= 100; index++) scores[index] = index*50 + epsilon; Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index Initializer Lists An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: int[] scores = {98, 76, 54, 83, 87, 65, 99, 66}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; Initializer Lists: Example 1 Used when exact size and initial values of an array are known in advance int [] scores = {98, 76, 54, 83} Visualize the results of the above command scores [0] [1] [2] [3] 98 76 54 83 Initializer Lists: Example 2 Consider the following 4 student names String [] STUDENTS = { “Aref", “Ali“, “Emad”, "Sami"}; Note results: STUDENTS [0] Aref [1] Ali [2] Emad [3] Sami Array elements are handles for String values Initializer Lists Note that when an initializer list is used: the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can only be used only in the array declaration The Assignment Operation Java provides a few operations to use with arrays, including assignment Consider: int [] alist = { 1, 12, 15, 7}; int [] blist; blist = alist; Recall that alist and blist are handles alist contains an address of where the numbers are blist now contains that same address blist does not have a copy of alist Array Cloning To actually create another array with its own values, Java provides the .clone() method int [] alist = {1, 12, 15, 7}; int [] blist; blist = alist.clone(); Now there are two separate lists of numbers, one with handle alist, the other with handle blist Array Cloning with Reference Types Recall previous declaration: STUDENTS [0] Aref [1] Ali [2] Emad [3] Sami Consider: Sometimes called a "shallow copy" operation String[] s_list = STUDENTS.clone(): This will create another list of handles, also pointing to the names Array Cloning with Reference Types We can write our own "deep copy" String [] original = {“Aref”,“Ali”, “Emad”, “Sami”}; String [] result = new String(original.length); for (i = 0; i < original.length; i++) result[i] = original[i].clone(); Array Equality Java has an equals() method for classes if (a1.equals(a2)) … If a1 and a2 are arrays, the equals() method just looks at the addresses the handles point to They could be pointing to different addresses but the contents of the array still be equal It is the contents that we really wish to compare Array Equality We must write our own method to compare the arrays they both must have the same length then use a for( ) loop to compare element by element for equality Boolean areEqual = true; As soon as one pair of elements is found if (list1.length != list2.length) equal, the arrays are not equal areEqual =not false; else { for (int i = 0; i < list1.length; i++) if (list1[i] != list2[i]) areEqual = false; } if(areEqual) System.out.println(“They are equal”); else System.out.println(“They are NOT equal”); Array exercises Write an application that inputs 10 numbers, each between 10 and 100. As each number is read, display it only if it is not a duplicate of a number already read. Given an array of integers, write a java code that allows to check if the array is “palindromic”. A palindromic array is a symmetric one: For example the arrays 1 6 4 6 1 and 258852 are both palindromic, but the array 3753 is not. Array exercises Write a program that reads a sequence of 10 integers into an array and then computes the alternating sum of all elements in the array. For example if the array is : 1 4 9 16 9 7 4 9 11 then it computes : 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = -2 The end Important to do at home : - read section 6.1 (pages 372-379) King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 12 : 2-D Arrays Two-Dimensional Arrays Two-dimensional (2-D) Arrays. 2-D Array Declaration. Initializer Lists. Differing Numbers of Elements in each Row. Implementation of a 2-D Array Printing a 2-D Array. 2-D Arrays: Why? Often data come in a 2-D form. For example: The layout of a printed page is 2-D Computer screen is 2-D The spread sheet (table) is 2-D For these situations we need a 2-D array. A 2-D array can be thought of as a collection of "slots" laid out in a 2-D grid. each slot can hold a value two indexes are needed to specify a slot. Example: Table of Student Grades Imagine a class of 7 students that have a quiz grades for 5 weeks. These grades can be stored in a table form. A particular cell of the table is identified by student number and week number. For example: The grade for student 0 in week 1 is 42 Student The grade for student 3 in week 4 is 93 The grade for student 6 in week 2 is 78 Week 0 1 2 3 4 0 99 42 74 83 100 1 90 91 72 88 95 2 88 61 74 89 96 3 61 89 82 98 93 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 78 56 99 2-D Arrays in Java In Java, a table may be implemented as a 2-D array. As with 1-D arrays, every slot in a 2-D array is of the same type which can be a primitive type or an object reference type. Each slot of the array is specified with a row and column number. Suppose that gradeTable is a 2-D array then the syntax to specify a particular slot should be gradeTable[row][col] For example Student Week 0 1 2 3 4 gradeTable[0][1] is 42 0 99 42 74 83 100 1 90 91 72 88 95 gradeTable[3][4] is 93 2 88 61 74 89 96 3 61 89 82 98 93 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 78 56 99 gradeTable[6][2] is 78 2-D Arrays in Java The subscripted variables of a 2-D array can be used in assignment statements and arithmetic expressions just like any variable: gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1. gradeTable[ 3 ][ 4 ]++; //increments the value at row 3 column 4. int value = (gradeTable[ 6 ][ 2 ] + 2)/2;//puts 40 into value Student Write a Java statement that puts a zero into row 5 column 3. gradeTable[ 5 ][ 3 ] = 0 Week 0 1 2 3 4 0 99 33 74 83 100 1 90 91 72 88 95 2 88 61 74 89 96 3 61 89 82 98 94 4 93 73 75 78 99 5 50 65 92 87 94 6 43 98 78 56 99 2-D Array Declaration In Java, a 2-D array is an object. To declare a reference variable myArray to a 2-D array of int: int[][] myArray; To create an array object of 3 rows and 5 columns, and put the reference in myArray, we write int[][] myArray = new int[3][5]; All the elements of myArray are initialized to zero. We can create the above array by using the initializer list: int[][] myArray = {{0,0,0,0,0}, {0,0,0,0,0}, {0,0,0,0,0}}; Different Numbers of Elements per Row In Java, each row of a 2-D array may have a different number of elements. In the following example, the array A has 3 elements in its first row, 2 in its second row, and 5 in its last row. int[][] A = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }}; Length of a 2-D Array The length of a 2-D array is the number of rows it has. So the row index (number) is from 0 to length-1. As each row in a 2-D array is like a 1-D array, we can refer to an entire row by specifying just the row index, e.g., A[0] means row # 0 The length of a row is the number of columns in the row. As each row of a 2-D array can have a different number of columns, so each row has its own length. int[][] A = { { 1, 9, 4 }, System.out.println("Length System.out.println("Length System.out.println("Length System.out.println("Length { 0, 2}, { 0, 1, 2, 3, 4 } }; of array is: " + A.length ); of row[0] is: " + A[0].length ); of row[1] is: " + A[1].length ); of row[2] is: " + A[2].length ); Implementation of 2-D Array A 2-D array is implemented as an array of 1-D arrays. To understand the idea, we construct the 2-D array stepby-step. int[][] myArray; declares a variable myArray myArray = new int[3][] ; // 2 Creates an array object. The array object has 3 slots. Each slot may refer (in the future) to an array of int (i.e., a row) myArray[0] = new int[3] ; // 1 // 3 Creates a 1-D array object and puts its reference in slot 0 of myArray. Implementation of 2-D Array A previously constructed 1-D array can be assigned to a row: int[] x = {0, 2}; int[] y = {0, 1, 2, 3, 4}; myArray[1] = x ; myArray[2] = y ; //4 The rows do not need to have the same number of elements Printing a 2-D Array Suppose we want to print every element of a 2-D array A It can be done by using nested loops. The expression A[row].length gives a different number for each row of the array. int[][] A = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }}; for ( int row=0; row < A.length; row++ ) { System.out.print("Row " + row + ": "); for ( int col=0; col < A[row].length; col++ ) System.out.print( A[row][col] + " "); System.out.println(); } The end Important to do at home : - read section 6.4 (pages 425-436) Exercises Write a program that creates a two dimensional array, fills it using Scanner, and then prints the sum of every column. Given a two-dimensional array, dataTable, of type double such that the rows can have different lengths. Write a code fragment that computes the average of each row and saves it in a singledimension array of size corresponding to the rows of dataTable. King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 13 : Methods A Java Program A Java Program A Java program consists of one or more classes A Java class consists of one or more methods A Java method consists of one or more statements Java classes Java Methods - What is a method … A Java application program consists of one or more classes. Each class has one or more methods Each method consists of one or more statements Each method has a name. One of the methods must be called main When a Java application program is run, the run-time system automatically invokes the method named main All Java application programs start with the main method … - What is a method … public class class-name { method1 method 2 method 3 … … method n } Example of a Java Program Example of a Java Program Class name Main method Class body Instruction Exercise Write a program that computes the factorial (n!) of 6 then the factorial of 3, then the factorial of 10. Exercise Write a program that computes the factorial (n!) of 6 then the factorial of 3, then the factorial of 10. Method invocation Return type Method parameter Method definition Return instruction -- Method Structure If method doesn’t return value Method name public or private<static> <void or typeReturned>myMethod(<parameters>) { statement Type of the return value Variable list statement statement Method body … … statement } - Invoking a Methods The statements inside a method body are executed when the corresponding method is called from another method. Calling a method is also called invoking a method Each time the method is invoked, its corresponding body is executed - return Statements … The body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation. … - return Statements A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed Example : write a method that prints all the numbers between 10 and 30 - Local Variables A variable declared within a method definition is called a local variable All variables declared inside the method are local variables All method parameters are local variables - Local Variables If two methods each have a local variable of the same name, they are still two entirely different variables. Example: Local variable in main method Local variable in factorial method Local variable in addition method - Method Parameters … A parameter list provides a description of the data required by a method It indicates the number and types of data pieces needed, the order in which they must be given, and the local name for these pieces as used in the method public double myMethod(int p1, int p2, double p3) Example: What is the parameter list of a method division that divides two integers and returns the result (double)? Parameters list … - Method Parameters … When a method is invoked, the appropriate values must be passed to the method in the form of arguments The number, order, and types of the arguments must exactly match that of the parameter list Error: type mismatch … - Method Parameters … Is this program correct? Yes it is! .. Details in the next slide .. … - Method Parameters … If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion In the preceding example, the int value of argument a would be cast to a double A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: byteshortintlongfloatdouble char … - Method Parameters … A parameters is often thought of as a blank or placeholder that is filled in by the value of its corresponding argument However, a parameter is more than that: it is actually a local variable When a method is invoked, the value of its argument is computed, and the corresponding parameter (i.e., local variable) is initialized to this value Even if the value of a formal parameter is changed within a method (i.e., it is used as a local variable) the value of the argument cannot be changed Call-by-Value Example Prints 10 Prints 10 - Method Parameters: Array Parameters Methods can have array parameters. Example: Write a program that prints the values of an array of integers, then increments each value of the array by two and then prints the new values of the same array. A parameter of type array - Details Array arguments are always passed by reference. This means any changes done to an array element by the invoked method, will also change the corresponding array element in the caller method. Example: Public static void m1() { int [] A = { 1, 2, 3}; m2(A); } public static void m2(int [] A) { A[1] = 5}; Method m2 changes the value of a[1] to 5; as a result the value of a[1] in m1 will also change to 5. - Method Overloading … In java the same class can have methods with the same name. Such methods are called overloaded methods. Overloaded methods must differ in the number or type of their arguments. The name of a method together with the number, order, and types of its arguments are called the method signature. No two methods of the same class must have the same signature. The compiler treats overloaded methods as completely different methods. It knows which one to call by using method signatures. - Method Overloading … These 3 methods have the same name but different signatures The end Important to do at home : - read pages 206-212 Exercises Write a method that takes as input an integer value and returns the sum of all integers less than that value. For example, if the input is 6, the output is 5+4+3+2+1 = 15. If the input is negative, the output should be -1. Write a method that takes as input an array of integers and returns the average of the values in the array. Exercises Write a method public void printTriangleNumbers(int n) such that: The call: printTriangleNumbers(5) prints the following on the screen: 12345 1234 123 12 1 The call: printTriangleNumbers(6) prints the following on the screen: 123456 12345 1234 123 12 1 The call: printTriangleNumbers(3) prints the following on the screen: 123 12 1 King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 14 : Classes Outline Introduction Class Definitions A Class Is a Type The new Operator Instance Variables and Methods Information Hiding public and private Modifiers Accessor and Mutator Methods Encapsulation - Introduction Classes are the most important language feature that make object-oriented programming (OOP) possible Programming in Java consists of defining a number of classes Every program is a class All helping software consists of classes All programmer-defined types are classes Classes are central to Java Example Suppose you are asked to write a program for a commercial company: The company has several: Employees Clients Products Stores If you use an object-oriented language such as Java, you will have to define: Class Class Class Class Employee : Client: Product: Store: public public public public class class class class Employee{ ..} Client{..} Product{..} Store{..} - Class Definitions You already know how to use classes and the objects created from them, and how to invoke their methods For example, you have already been using the predefined String and Scanner classes Now you will learn how to define your own classes and their methods, and how to create your own objects from them … next slide Class Definition A class definition is composed of two parts: Data members (Data part) Methods (Operations part) Example: define a class Employee - Details A class definition specifies the data items and methods that all of its objects will have These data items and methods are sometimes called members of the object Data items are called fields or instance variables Instance variable declarations and method definitions can be placed in any order within the class definition Object Declaration It is possible to declare several objects from a class: e1 e2 Class Employee e3 e4 s1 The same principle as: s2 String s3 s4 Note: classes Employee and TestClass should be saved in the same directory - A Class Is a Type A class is a special kind of programmer-defined type, and variables can be declared of a class type A value of a class type is called an object or an instance of the class e1 The following phrases are equivalent: “e1 is of type Employee," “e1 is an object of the class Employee," and “e1 is an instance of the class Employee" e2 Employee e3 e4 - Object Creation The instruction: Employee e1; only declares e1. But the object is still not created. To create the object the operator new must be used: e1 = new Employee(); These can be combined as follows: Employee e1 = new Employee(); - Object Creation Declaration Creation Question: What is the name of Employee e1? How to change the name of Employee e1? … next slide .. - Instance Variables and Methods … In order to refer to a particular instance variable, preface it with its object name as follows: objectName.instanceVar1 objectName.instanceVar2 Example: e1.name e1.age e1.salary To change the name of e1: e1.name = “Mohamed”; - Instance Variables and Methods … In order to invoke a method of a class, you need an object of that class: objectName.method1() objectName.method2(argument1) Example: e1.outputDetails(); e1.outputDetails(); - Instance Variables and Methods … Modifying the name Invoking a method Calling object Accessing the name - Information Hiding and Encapsulation Information hiding is the practice of separating how to use a class from the details of its implementation Abstraction is another term used to express the concept of discarding details in order to avoid information overload Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object), which hides the implementation details Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface In Java, hiding details is done by marking them private - public and private Modifiers … Instance variables and methods of a class can be declared Example: public, or private public String name; private int age; public void outputDetails{..} The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class It is considered good programming practice to make all instance variables private - public and private Modifiers … Illegal because we try to access a private member (age) from outside the class Employee … - public and private Modifiers Within the definition of a class, private members of any object of the class can be accessed, not just public members of the calling object Problem .. It is considered good programming practice to make all instance variables private Question: how to access and modify the instance variables of Employee objects e1, e2, e3 and e4? .. answer .. Use accessor and mutaor methods …. next slide .. - Accessor and Mutator Methods … Accessor methods allow the programmer to obtain the value of an object's instance variables The data can be accessed but not changed The name of an accessor method typically starts with the word get Example: public String getName() { return name;} Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word set Example: public void setName(String n) { name = n;} - Accessor and Mutator Methods (Example) Accessor method for instance variable name Mutator method for instance variable name Modifying the name of e1 using a mutator method The end Important to do at home : - read sections 4.1 and 4.2 (pages 200-243) Exercise Define a class Date with three instance variable: month of type String day of type integer year of type integer Provide a method WriteOutput to print the details of the Date Provide accessor and mutator methods for all instance variables. Solution Solution Solution King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 15 : Classes II Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(ParametersList){…} A constructor must have the same name as the class A constructor has no type returned, not even void Constructors are typically overloaded Constructor Example Constructor How Constructors are called A constructor is called when an object of the class is created using new ClassName objectName = new ClassName(anyArgs); The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator A constructor cannot be invoked like an ordinary method Example: Employee e1 = new Employee(“Mohamed”, 20, 5000); Constructors Constructor Calling the constructor Constructors In the previous lecture we saw this example: We did not define any constructor, but we created objects using new !! Explanation .. Next slide .. Include a No-Argument Constructor If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor in your class, Java will not provide this default constructor If you include any constructors in your class, be sure to provide your own no-argument constructor as well No-argument constructor No-argument constructor Copy Constructor A copy constructor is a constructor with a single argument of the same type as the class. It creates an object which is an exact copy of the argument object Example: How to invoke a copy constructor: - The methods equals and toString Java expects certain methods, such as equals and toString, to be in all, or almost all, classes The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal“ Note: You cannot use == to compare objects public boolean equals(ClassName objectName) The purpose of the toString method is to return a String value that represents the data in the object public String toString() equals example equals example Invoking equals method: equals invocation toString example toString invocation The end Important to do at home : - read sections 4.3 and 4.4 (pages 244-273) Exercise: Temperature Class (1/2) Write a Temperature class that has two instance variables: a temperature value (a floating-point number) and a character for the scale, either 'C' for Celsius or 'F' for Fahrenheit. The class should have four constructor methods: one for each instance variable (assume zero degrees if no value is specified and Celsius if no scale is specified), one with two parameters for the two instance variables, and a no-argument constructor (set to zero degrees Celsius). Include two accessor methods to return the temperature: getTempCelsius: to return the degrees Celsius, getTempFahrenheit: to return the degrees Fahrenheit IMPORTANT: use the following formulas : degreesC = 5(degreesF - 32)/9 degreesF = (9(degreesC)/5) + 32 Exercise: Temperature Class (2/2) Include three mutator methods, setValue to set the value, setScale to set the scale ('F' or 'C'), and setValueAndScale to set both; Include a suitable toString method. Include a equals method Then write a test class called TestTemperature that tests all the methods. Be sure to use each of the constructors. King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 16 : Classes III Class variables Vs Primitive type variables int i = 15; Employee e1 = new Employee(“Mohamed”, 20, 5000); i is a variable of type integer that contain the value 15. e1 is a variable of type Employee that contains the address where the object is located. The object named by the variable is stored in some other location in memory i e1 15 “Mohamed” 20 5000 July 17, 2016 ICS102: Classes 3/5 320 References What happens if we do: Employee e1 = new Employee(“Mohamed”, 20, 5000); Employee e2 = e1; e1 and e2 will refer to the same object! July 17, 2016 The assignment operator sets the reference (memory address) of one class type variable equal to that of another Any change to the object named by one of theses variables will produce a change to the object named by the other variable, since they are the same object !! ICS102: Classes 3/5 321 Example What will be printed here? - Class Parameters … All parameters in Java are call-by-value parameters A parameter is a local variable that is set equal to the value of its argument Therefore, any change to the value of the parameter cannot change the value of its argument Class type parameters appear to behave differently from primitive type parameters July 17, 2016 They appear to behave in a way similar to parameters in languages that have the call-by-reference parameter passing mechanism ICS102: Classes 3/5 323 Call-by-Value Call-by-Reference What salary will printed here? … - Class Parameters The value plugged into a class type parameter is a reference (memory address) July 17, 2016 Therefore, the parameter becomes another name for the argument Any change made to the object named by the parameter (i.e., changes made to the values of its instance variables) will be made to the object named by the argument, because they are the same object ICS102: Classes 3/5 326 - Differences Between Primitive and Class-Type Parameters July 17, 2016 A method cannot change the value of a variable of a primitive type that is an argument to the method In contrast, a method can change the values of the instance variables of a class type that is an argument to the method ICS102: Classes 3/5 327 Pitfall: Use of == with Class type variables The test for equality (==) also behaves differently for class type variables The == operator only checks that two class type variables have the same memory address Unlike the equals method, it does not check that their instance variables have the same values Two objects in two different locations whose instance variables have exactly the same values would still test as being "not equal“ Use equals method instead: July 17, 2016 ICS102: Classes 3/5 328 - The Constant null null is a special constant that may be assigned to a variable of any class type YourClass yourObject = null; It is used to indicate that the variable has no "real value“ July 17, 2016 ICS102: Classes 3/5 329 The end Important to do at home : - read section 5.2 (pages 310-324) Advanced Example An advanced example of classes is the Class Person defined in Display 5.19 of Chapter 5 of the textbook (Pages 296-304 of the 4th edition) King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department ICS102 Lecture 18 : Static Members Static Methods A static method is one that can be used without a calling object. A static method still belongs to a class, and its definition is given inside the class definition. When a static method is defined, the keyword static is placed in the method header public static returnedType myMethod(parameters) { . . . } Static methods are invoked using the class name in place of a calling object returnedValue = MyClass.myMethod(arguments); Static Variables Static variables can be declared and initialized at the same time private static int myStaticVariable = 0; If not explicitly initialized, a static variable will be automatically initialized to a default value boolean static variables are initialized to false Other primitive types static variables are initialized to the zero of their type Class type static variables are initialized to null It is always preferable to explicitly initialize static variables rather than rely on the default initialization Static Variables A static variable should always be defined private, unless it is also a defined constant The value of a static defined constant cannot be altered, therefore it is safe to make it public In addition to static, the declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed public static final int BIRTH_YEAR = 1954; When referring to such a defined constant outside its class, use the name of its class in place of a calling object int year = MyClass.BIRTH_YEAR; Pitfall: Invoking a Nonstatic Method Within a Static Method A static method cannot refer to an instance variable of the class, and it cannot invoke a nonstatic method of the class A static method has no this, so it cannot use an instance variable or method that has an implicit or explicit this for a calling object A static method can invoke another static method, however Simple Example static field static method Example (Part 1 of 4) Example (Part 2 of 4) Example (Part 3 of 4) Example (Part 4 of 4)