Summary

These lecture slides cover the fundamental concepts of object-oriented programming. The document explains the differences between procedure-oriented and object-oriented programming paradigms, and the important concepts of encapsulation, abstraction, inheritance, and polymorphism.

Full Transcript

Absolute Java Sixth Edition Chapter 1 Getting Started Modified by Dr. Zia Ud Din and Dr. Zara Hamid, WLU Copyright © 2016, 2013, 2010 Pear...

Absolute Java Sixth Edition Chapter 1 Getting Started Modified by Dr. Zia Ud Din and Dr. Zara Hamid, WLU Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Procedure Oriented Programming In a procedural language, the emphasis is on doing things(functions). A program is divided into functions and—ideally, at least—each function has a clearly defined purpose and a clearly defined interface to the other functions in the program. Procedural programs (functions and data structures) don’t model the real world very well. The real world does not consist of functions. Global data can be corrupted by functions that have no business changing it. To add new data items, all the functions that access the data must be modified so that they can also access these new items. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Object Oriented Programming Paradigm The fundamental idea behind object-oriented programming is: – The real world consists of objects. – Computer programs may contain computer world representations of the things (objects) that constitute the solutions of real world problems. Real world objects have two parts: – Properties (or state :characteristics that can change), – Behavior (or abilities :things they can do). To solve a programming problem in an object-oriented language, the programmer no longer asks how the problem will be divided into functions, but how it will be divided into objects. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Procedure Oriented vs Object Oriented Programming Global Data https://www.bloccoappunti.it/39-oop/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Object Oriented Programming Paradigm OOP allows you to describe the problem in terms of the problem, rather than in terms of the computer where the solution will run. Benefits of the object-oriented programming: Readability Understandability Low probability of errors Maintenance Reusability Teamwork Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Examples of things that can be represented as objects in object-oriented paradigm? Human entities: Employees, customers, salespeople, worker, manager Graphics program: Point, line, square, circle,... Mathematics: Complex numbers, matrix Computer user environment: Windows, menus, buttons Data-storage constructs: Customized arrays, stacks, linked lists Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Three Pillars of OOP From the programmer's point of view, an object-oriented language must support three very important explicit characteristics. We use these concepts extensively to model the real-world problems when we are trying to solve with our object-oriented programs. These three concepts are: – Encapsulation and data hiding, – Inheritance, – Polymorphism. The implicit characteristic is abstraction. We use it to specify new abstract data types, or ADT for short. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Encapsulation & Data Hiding Image from http://www.btechsmartclass.com/java/java- oop-concepts.html The concept of combining the data and the associated functions -that operate on that data- in a single unit called a class, or an object is called encapsulation. It is not possible to access the data directly. If you want to reach the data item in an object, you call a member function in the object. It will read the data item and return the value to you. The data is hidden, so it is considered as safe and far away from accidental alternation. This concept is called data hiding We use keywords public, private, and protected to control access Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Abstraction This is a thought process of hiding work style of an object and showing only those information which are required to understand the object. Or we can say, process of identifying the relevant qualities and behaviors of an object Abstraction is the specification of an abstract data type and includes a specification of the type’s data representation and behavior. It shows, what kind of data can be held in the new type of data, and all ways of manipulation of that data. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Encapsulation & Abstraction Since a car was invented, the steering mechanism has not changed functionality. It presents the same interface to the users: everybody knows how to use this mechanism through its interface. If we turn the steering wheel clockwise, the car will turn to the right, if we turn it counterclockwise, our car will turn to the left. We can use it without having any idea about implementation — everything is hidden for us under the hood, only a few of us have more details. Image from https://www.linkedin.com/pulse/encapsulation-vs-abstraction-pawan-verma/ Car object Outside world Client interface color setColor() model Accelerate() Hidden/encapsulated speed applyBrake() data Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes and Objects (1 of 2) An object has the same relationship to a class that a variable has to a data type. An object is said to be an instance of a class. A class is a template to its objects. Class definition does not allocate any memory. Memory allocation is done for each instance (object) when it is instantiated (created). Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes and Objects (2 of 2) https://leetusman.com/intermediate-programming/posts/classes-and-objects/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects Give me 5 examples of classes and objects… Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 1. Class: Car Attributes: model, brand, color, engineType, fuelLevel Methods: drive(), refuel(), park(), turnOn(), turnOff() Object (Instance): myCar = new Car("Model S", "Tesla", "Red", "Electric", 100%) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 2. Class: Student Attributes: name, studentID, major, GPA, enrolledCourses Methods: enrollCourse(), dropCourse(), updateGPA(), attendClass() Object (Instance): student1 = new Student("Alice Smith", "S12345", "Computer Science", 3.8, ["CP104", “CP213"]) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Exercise: Classes and Objects 3. Class: BankAccount Attributes: accountNumber, accountHolder, balance, accountType Methods: deposit(), withdraw(), transferFunds(), checkBalance() Object (Instance): myAccount = new BankAccount("123456789", "John Doe", 15000.00, "Checking") Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Inheritance Inheritance is one of the most powerful features of object- oriented programming Inheritance is the process of creating new classes, called subclasses, from existing or superclasses The derived class inherits all the capabilities of the base class but can add more capabilities of its own Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Polymorphism Derived from the Greek words: poly and morphs meaning many and forms. Polymorphism refers to the ability of a single object to take on multiple forms. This is achieved through inheritance, where a subclass can override the methods of its superclass. Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Inheritance Inherited properties Inherited/overridden behaviours http://www.btechsmartclass.com/java/java-oop-concepts.html Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Example: Polymorphism http://www.btechsmartclass.com/java/java-oop-concepts.html Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language – The syntax of expressions and assignments will be similar to that of other high-level languages – Details concerning the handling of strings and console output will probably be new Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (1 of 3) Created by Sun Microsystems team led by James Gosling in 1991 (now owned by Oracle) Originally designed for programming home appliances – Difficult task because appliances are controlled by a wide variety of computer processors – Team developed a two-step translation process to simplify the task of compiler writing for each class of appliances Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (2 of 3) Significance of Java translation process – Writing a compiler (translation program) for each type of appliance processor would have been very costly – Instead, developed intermediate language that is the same for all types of processors : Java byte-code – Therefore, only a small, easy to write program was needed to translate byte-code into the machine code for each processor Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Origins of the Java Language (3 of 3) Patrick Naughton and Jonathan Payne at Sun Microsystems developed a Web browser that could run programs over the Internet (1994) – Beginning of Java's connection to the Internet – Original browser evolves into HotJava Netscape made its Web browser capable of running Java programs (1995) – Other companies follow suit Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Objects and Methods Java is an object-oriented programming (OOP) language – Programming methodology that views a program as consisting of objects that interact with one another by means of actions (called methods) – Objects of the same kind are said to have the same type or be in the same class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Terminology Comparisons Other high-level languages have constructs called procedures, methods, functions, and/or subprograms – These types of constructs are called methods in Java – All programming constructs in Java, including methods, are part of a class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Java Application Programs Two common types of Java programs are applications and applets A Java application program or “regular” Java program is a class with a method named 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 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Applets A Java applet (little Java application) is a Java program that is meant to be run from a Web browser – Can be run from a location on the Internet – Can also be run with an applet viewer program for debugging – Applets always use a windowing interface In contrast, application programs may use a windowing interface or console (i.e., text) I/O Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved A Sample Java Application Program Display 1.1 A sample java Program Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved System.out.println (1 of 2) Java programs work by having things called objects perform actions – System.out: An object used for sending output to the screen The actions performed by an object are called methods – Print ln: The method or action that the System.out object performs Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved System.out.print ln (2 of 2) Invoking or calling a method: When an object performs an action using a method – Also called sending a message to the object – Method invocation syntax (in order): an object, a dot (period), the method name, and a pair of parentheses – Arguments: Zero or more pieces of information needed by the method that are placed inside the parentheses Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Variable declarations Variable declarations in Java are similar to those in other programming languages –Simply give the type of the variable followed by its name and a semicolon Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Using = and + In Java, the equal sign (=) is used as the assignment operator – The variable on the left side of the assignment operator is assigned the value of the expression on the right side of the assignment operator In Java, the plus sign (+) can be used to denote addition (as above) or concatenation – Using +, two strings can be connected together Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Computer Language Levels (1 of 2) High-level language: A language that people can read, write, and understand – A program written in a high-level language must be translated into a language that can be understood by a computer before it can be run Machine language: A language that a computer can understand Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Computer Language Levels (2 of 2) Low-level language: Machine language or any language similar to machine language Compiler: A program that translates a high-level language program into an equivalent low-level language program – This translation process is called compiling Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Byte-Code and the Java Virtual Machine (1 of 2) The compilers for most programming languages translate high-level programs directly into the machine language for a particular computer – Since different computers have different machine languages, a different compiler is needed for each one In contrast, the Java compiler translates Java programs into byte-code, a machine language for a fictitious computer called the Java Virtual Machine – Once compiled to byte-code, a Java program can be used on any computer, making it very portable Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Byte-Code and the Java Virtual Machine (2 of 2) Interpreter: The program that translates a program written in Java byte-code into the machine language for a particular computer when a Java program is executed – The interpreter translates and immediately executes each byte- code instruction, one after another – Translating byte-code into machine code is relatively easy compared to the initial compilation step Most Java programs today run using a Just-In-Time or JIT compiler which compiles a section of byte-code at a time Image from https://www.w3schools.in/java/java-virtual-machine into machine code Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Program terminology Code: A program or a part of a program Source code (or source program): A program written in a high-level language such as Java – The input to the compiler program Object code: The translated low-level program – The output from the compiler program, e.g., Java byte- code – In the case of Java byte-code, the input to the Java byte- code interpreter Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Class Loader Java programs are divided into smaller parts called classes – Each class definition is normally in a separate file and compiled separately Class Loader: A program that connects the byte-code of the classes needed to run a Java program – In other programming languages, the corresponding program is called a linker https://shishirkant.com/java-virtual-machine-jvm/ Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Compiling a Java Program or Class Each class definition must be in a file whose name is the same as the class name followed by.java – The class FirstProgram must be in a file named FirstProgram.java Each class is compiled with the command javac followed by the name of the file in which the class resides The result is a byte-code program whose filename is the same as the class name followed by.class Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Running a Java Program A Java program can be given the run command (java) after all its classes have been compiled – Only run the class that contains the main method (the system will automatically load and run the other classes, if any) – The main method begins with the line: – Follow the run command by the name of the class only (no.java or.class extension) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Syntax and Semantics Syntax: The arrangement of words and punctuations that are legal in a language, the grammar rules of a language Semantics: The meaning of things written while following the syntax rules of a Language Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Error Messages (1 of 2) Bug: A mistake in a program – The process of eliminating bugs is called debugging Syntax error: A grammatical mistake in a program – The compiler can detect these errors, and will output an error message saying what it thinks the error is, and where it thinks the error is Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Error Messages (2 of 2) Run-time error: An error that is not detected until a program is run – The compiler cannot detect these errors: an error message is not generated after compilation, but after execution Logic error: A mistake in the underlying algorithm for a program – The compiler cannot detect these errors, and no error message is generated after compilation or execution, but the program does not do what it is supposed to do Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Identifiers (1 of 2) Identifier: The name of a variable or other item (class, method, object, etc.) defined in a program – A Java identifier must not start with a digit, and all the characters must be letters, digits, or the underscore symbol – Java identifiers can theoretically be of any length – Java is a case-sensitive language:Rate, rate, and RATE are the names of three different variables Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Identifiers (2 of 2) Keywords and Reserved words: Identifiers that have a predefined meaning in Java – Do not use them to name anything else Predefined identifiers: Identifiers that are defined in libraries required by the Java language standard – Although they can be redefined, this could be confusing and dangerous if doing so would change their standard meaning Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Conventions Start the names of variables, classes, methods, and objects with a lowercase letter, indicate “word” boundaries with an uppercase letter, and restrict the remaining characters to digits and lowercase letters Start the names of classes with an uppercase letter and, otherwise, adhere to the rules above Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Variable Declarations Every variable in a Java program must be declared before it is used – A variable declaration tells the compiler what kind of data (type) will be stored in the variable – The type of the variable is followed by one or more variable names separated by commas, and terminated with a semicolon – Variables are typically declared just before they are used or at the start of a block (indicated by an opening brace { ) – Basic types in Java are called primitive types Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements Display 1.2 Primitive Types Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements With Primitive Types (1 of 2) In Java, the assignment statement is used to change the value of a variable – The equal sign (=) is used as the assignment operator – An assignment statement consists of a variable on the left side of the operator, and an expression on the right side of the operator – An expression consists of a variable, number, or mix of variables, numbers, operators, and/or method invocations Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Statements With Primitive Types (2 of 2) – 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 – Note that a variable can occur on both sides of the assignment operator – The assignment operator is automatically executed from right-to-left, so assignment statements can be chained Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Initialize Variables (1 of 2) 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 – It is best not to rely on this – Explicitly initialized variables have the added benefit of improving program clarity Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Tip: Initialize Variables (2 of 2) The declaration of a variable can be combined with its initialization via an assignment statement – Note that some variables can be initialized and others can remain uninitialized in the same declaration Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Shorthand Assignment Statements (1 of 2) Shorthand assignment notation combines the assignment operator (=) and an arithmetic operator It is used to change the value of a variable by adding, subtracting, multiplying, or dividing by a specified value The general form is which is equivalent to – The Expression can be another variable, a constant, or a more complicated expression – Some examples of what Op can be are +, −, *, /, or % Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Shorthand Assignment Statements (2 of 2) Example: Equivalent To: Count plus equalto two Count = count plus two Sum minus equal to dicount Sum equal to sum minus discount semicolon Bonus astrich equal to two Bonus equal to bonus multiplied by two Time slash equal to rushfactor Time equal to time divided by rush factor Change percent equal to hundred semicolon Change equal to change percentage hundred Amount astrich equal to count one plus count two Amount equal to amount multiplied by open bracket count one plus semicolon count two close bracket semicolon Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (1 of 3) In general, the value of one type cannot be stored in a variable of another type – The above example results in a type mismatch because a double value cannot be stored in an int variable However, there are exceptions to this – For example, an int value can be stored in a double type Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (2 of 3) 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 – Note that as your move down the list from left to right, the range of allowed values for the types becomes larger Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Assignment Compatibility (3 of 3) An explicit type cast is required to assign a value of one type to a variable whose type appears to the left of it on the above list (e.g., double to int) Note that in Java an int cannot be assigned to a variable of type boolean, nor can a boolean be assigned to a variable of type int Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (1 of 3) Constant (or literal): An item in Java which has one specific value that cannot change – Constants of an integer type may not be written with a decimal point (e.g.,10) – Constants of a floating-point type can be written in ordinary decimal fraction form (e.g., 367000.0 or 0.000589) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (2 of 3) Constant of a floating-point type can also be written in scientific (or floating-point) notation (e.g., 3.67e 5or 5.89e -4 ) ▪ Note that the number before the e may contain a decimal point, but the number after the e may not Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Constants (3 of 3) Constants of type char are expressed by placing a single character in single quotes (e.g., ‘z’) Constants for strings of characters are enclosed by double quotes (e.g., “ Welcome to Java”) There are only two boolean type constants, true and false – Note that they must be spelled with all lowercase letters Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (1 of 3) As in most languages, expressions can be formed in Java using variables, constants, and arithmetic operators – These operators are + (addition), −(subtraction), * (multiplication), / (division), and % (modulo, remainder) – An expression can be used anyplace it is legal to use a value of the type produced by the expression Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (2 of 3) 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 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Arithmetic Operators and Expressions (2 of 2) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Parentheses and Precedence Rules (1 of 2) An expression can be fully parenthesized in order to specify exactly what subexpressions are combined with each operator 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 – However, it's best (and sometimes necessary) to include them Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Parentheses and Precedence Rules (2 of 2) Display 1.3 Precedence Rules Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Precedence and Associativity Rules (1 of 2) When the order of two adjacent operations must be determined, the operation of higher precedence (and its apparent arguments) is grouped before the operation of lower precedence is evaluated as When two operations have equal precedence, the order of operations is determined by associativity rules Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Precedence and Associativity Rules (2 of 2) – Unary operators of equal precedence are grouped right-to-left +−+rate is evaluated as + (− (+ rate )) – Binary operators of equal precedence are grouped left-to-right base + rate + hours is evaluated as (base + rate) + hours – Exception: A string of assignment operators is grouped right-to-left – n1 = n2 = n3; is evaluated as n1 = (n2 = n3 ) ; Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Pitfall: Round-Off Errors in Floating-Point Numbers Floating point numbers are only approximate quantities – Mathematically, the floating-point number 1.0/3.0 is equal to 0.3333333 … – A computer has a finite amount of storage space ▪ It may store 1.0/3.0 as something like 0.3333333333, which is slightly smaller than one-third Computers actually store numbers in binary notation, but the consequences are the same: floating-point numbers may lose accuracy Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved 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 Be careful to make at least one of the operands a floating- point type if the fractional portion is needed Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved The % 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 – To count by twos, perform the operation number % 2, and when the result is 0, number is even Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Type Casting A type cast takes a value of one type and produces a value of another type with an “equivalent” value – If n and m are integers to be divided, and the fractional portion of the result must be preserved, at least one of the two must be type cast to a floating-point type before the division operation is performed – Note that the desired type is placed inside parentheses immediately in front of the variable to be cast – Note also that the type and value of the variable to be cast does not change Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved More Details About Type Casting 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 When the value of an integer type is assigned to a variable of a floating-point type, Java performs an automatic type cast called a type coercion In contrast, it is illegal to place a double value into an int variable without an explicit type cast Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Increment and Decrement Operators (1 of 2) The increment operator (++) adds one to the value of a variable – If n is equal to 2, then n++ or ++n will change the value of n to 3 The decrement operator (−−) subtracts one from the value of a variable – If n is equal to 4, then n−−or −−n will change the value of n to 3 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Increment and Decrement Operators (2 of 2) When either operator precedes its variable, and is part of an expression, then the expression is evaluated using the changed value of the variable – If n is equal to 2, then 2 * (+ +n) evaluates to 6 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 – If n is equal to 2, then 2 * (n + + ) evaluates to 4 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved The Class String There is no primitive type for strings in Java The class String is a predefined class in Java that is used to store and process strings Objects of type String are made up of strings of characters that are written within double quotes – Any quoted string is a constant of type String “Live long and prosper.” A variable of type String can be given the value of a String object String blessing = “Live long and prosper.”; Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Concatenation of Strings Concatenation: Using the + operator on two strings in order to connect them to form one longer string – If greeting is equal to “Hello”, and javaClass is equal to “class”, then greeting + javaClass is equal to “Hello class” Any number of strings can be concatenated together When a string is combined with almost any other type of item, the result is a string – “The answer is” + 42 evaluates to “The answer is 42” Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes, Objects, and Methods (1 of 2) A class is the name for a type whose values are objects Objects are entities that store data and take actions – Objects of the String class store data consisting of strings of characters The actions that an object can take are called methods – Methods can return a value of a single type and/or perform an action – All objects within a class have the same methods, but each can have different data values Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Classes, Objects, and Methods (2 of 2) Invoking or calling a method: a method is called into action by writing the name of the calling object, followed by a dot, followed by the method name, followed by parentheses – This is sometimes referred to as sending a message to the object – The parentheses contain the information (if any) needed by the method – This information is called an argument (or arguments) Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (1 of 10) The String class contains many useful methods for string- processing applications – A String method is called by writing a String object, a dot, the name of the method, and a pair of parentheses to enclose any arguments – If a String method returns a value, then it can be placed anywhere that a value of its type can be used Always count from zero when referring to the position or index of a character in a string Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (2 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (3 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (4 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (5 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (6 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (7 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (8 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (9 of 10) Display 1.4 Some Methods in the class String Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Methods (10 of 10) Display 1.5 String Indexes Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Escape Sequences (1 of 2) A backslash (\) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character – 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 Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Escape Sequences (2 of 2) Display 1.6 Escape Sequences Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved String Processing A String object in Java is considered to be immutable, i.e., the characters it contains cannot be changed There is another class in Java called StringBuffer that has methods for editing its string objects However, it is possible to change the value of a String variable by using an assignment statement Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Character Sets ASCII: A character set used by many programming languages that contains all the characters normally used on an English-language keyboard, plus a few special characters – Each character is represented by a particular number Unicode: A character set used by the Java language that includes all the ASCII characters plus many of the characters used in languages with a different alphabet from English Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Constants Instead of using “anonymous” numbers in a program, always declare them as named constants, and use their name instead – This prevents a value from being changed inadvertently – It has the added advantage that when a value must be modified, it need only be changed in one place – Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore character Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Comments A line comment begins with the symbols //, and causes the compiler to ignore the remainder of the line – This type of comment is used for the code writer or for a programmer who modifies the code A block comment begins with the symbol pair – The compiler ignores anything in between – This type of comment can span several lines – This type of comment provides documentation for the users of the program Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Program Documentation Java comes with a program called javadoc that will automatically extract documentation from block comments in the classes you define – As long as their opening has an extra asterisk (/**) Ultimately, a well written program is self-documenting – Its structure is made clear by the choice of identifier names and the indenting pattern – When one structure is nested inside another, the inside structure is indented one more level Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Naming Constant Display 1.8 Comments and Named Constant Copyright © 2016, 2013, 2010 Pearson Education Inc. All Rights Reserved Copyright Copyright © 2016,2013,2010 Pearson Education Inc. All Rights Reserved Absolute Java Sixth Edition Chapter 2 Console Input and Output Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved System.out.println for Console Output System.out is an object that is part of the Java language Print ln is a method invoked by the System.out object that can be used for console output – The data to be output is given as an argument in parentheses – A plus sign is used to connect more than one item – Every invocation of print ln ends a line of output Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Print ln Versus Print Another method that can be invoked by the System.out object is print The print method is like print ln, except that it does not end a line – With print ln, the next output goes on a new line – With print, the next output goes on the same line Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with printf (1 of 2) Starting with version 5.0, Java includes a method named printf that can be used to produce output in a specific format The Java method printf is similar to the print method – Like print, printf does not advance the output to the next line System.out.printf can have any number of arguments Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with printf (2 of 2) – The first argument is always a format string that contains one or more format specifiers for the remaining arguments – All the arguments except the first are values to be output to the screen Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Printf Format Specifier (1 of 2) The code will output the line $19.80 each Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Printf Format Specifier (2 of 2) The format string “%6.2f” indicates the following: – End any text to be output and start the format specifier (%) – Display up to 6 right-justified characters, pad fewer than six characters on the left with blank spaces (i.e., field width is 6) – Display exactly 2 digits after the decimal point (.2) – Display a floating point number, and end the format specifier (i.e., the conversion character is f) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Right and Left Justification in Printf (1 of 2) The code will output the following Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Right and Left Justification in Printf (2 of 2) The format string “Start%8.2fEnd” produces output that is right justified with three blank spaces before the 12.12 The format string “Start%-8.2fEnd” produces output that is left justified with three blank spaces after the 12.12 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Multiple Arguments with Printf (1 of 2) The following code contains a printf statement having three arguments – The code will output Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Multiple Arguments with printf (2 of 2) – Note that the first argument is a format string containing two format specifiers (%6.2f and %s) – These format specifiers match up with the two arguments that follow (price and name) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Line Breaks with Printf Line breaks can be included in a format string using %n The code will output Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with Printf (1 of 4) Display 2.1 Format Specifiers for System.out.printf Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with Printf (2 of 4) Display 2.2 The printf Method Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with Printf (3 of 4) Display 2.2 The printf Method Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Output with Printf (4 of 4) Display 2.2 The printf Method Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Formatting Money Amounts with Printf A good format specifier for outputting an amount of money stored as a double type is %.2f It says to include exactly two digits after the decimal point and to use the smallest field width that the value will fit into: produces the output: Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Legacy Code Code that is “old fashioned” but too expensive to replace is called legacy code Sometimes legacy code is translated into a more modern language The Java method printf is just like a C language function of the same name This was done intentionally to make it easier to translate C code into Java Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Money Formats (1 of 2) Using the NumberFormat class enables a program to output amounts of money using the appropriate format – The NumberFormat class must first be imported in order to use it – An object of NumberFormat must then be created using the getCurrencyInstance() method – The format method takes a floating-point number as an argument and returns a String value representation of the number in the local currency Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Money Formats (2 of 2) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Money Formats (3 of 3) Output of the previous program Default location: $19.80 $19.81 $19.90 $19.00 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Specifying Locale (1 of 3) Invoking the getCurrencyInstance() method without any arguments produces an object that will format numbers according to the default location In contrast, the location can be explicitly specified by providing a location from the Locale class as an argument to the getCurrencyInstance() method – When doing so, the Locale class must first be imported Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Specifying Locale (2 of 3) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Specifying Locale (3 of 3) Output of the previous program US as location: $19.80 $19.81 $19.90 $19.00 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Importing Packages and Classes (1 of 4) Display 2.4 Locale Constants for Currencies Of Different Countries Locale.CANADA Canada (for currency, the format is the same as US) Locale.CHINA China Locale.FRANCE France Locale.GERMANY Germany Locale.ITALY Italy Locale.JAPAN Japan Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Importing Packages and Classes (2 of 4) Locale.KOREA Korea Locale.TAIWAN Taiwan Locale.UK United Kingdom (English pound) Locale.US United States Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Importing Packages and Classes (3 of 4) Libraries in Java are called packages – A package is a collection of classes that is stored in a manner that makes it easily accessible to any program – In order to use a class that belongs to a package, the class must be brought into a program using an import statement Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Importing Packages and Classes (4 of 4) – Classes found in the package java.lang are imported automatically into every Java program Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The DecimalFormat Class (1 of 4) Using the DecimalFormat class enables a program to format numbers in a variety of ways – The DecimalFormat class must first be imported – A DecimalFormat object is associated with a pattern when it is created using the new command – The object can then be used with the method format to create strings that satisfy the format – An object of the class DecimalFormat has a number of different methods that can be used to produce numeral strings in various formats Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The DecimalFormat Class (2 of 4) Display 2.5 The DecimalFormat Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The DecimalFormat Class (3 of 4) Display 2.5 The DecimalFormat Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The DecimalFormat Class (4 of 4) Display 2.5 The DecimalFormat Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (1 of 6) Starting with version 5.0, 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: 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 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (2 of 6) The following line creates an object of the class Scanner and names the object keyboard : 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 Once a Scanner object has been created, a program can then use that object to perform keyboard input using methods of the Scanner class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (3 of 6) The method nextInt reads one int value typed in at the keyboard and assigns it to a variable: The method nextDouble reads one double value typed in at the keyboard and assigns it to a variable: 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 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (4 of 6) 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 and the input line jelly beans The value of word1 would be jelly, and the value of word2 would be beans Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (5 of 6) The method nextLine reads an entire line of keyboard input The code, reads in an entire line and places the string that is read into the variable line Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Console Input Using the Scanner Class (6 of 6) 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) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Scanner Class (1 of 5) Display 2.6 Keyboard Input Demonstration Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Scanner Class (2 of 5) Display 2.6 Keyboard Input Demonstration Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Scanner Class (3 of 5) Display 2.7 Another Keyboard Input Demonstration Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Scanner Class (4 of 5) Display 2.7 Another Keyboard Input Demonstration Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Scanner Class (5 of 5) Display 2.7 Another Keyboard Input Demonstration Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Pitfall: Dealing with the Line Terminator, ‘\n’ (1 of 3) 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 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Pitfall: Dealing with the Line Terminator, ‘\n’ (2 of 3) Given the code, and the input, 2 Heads are better than 1 head. what are the values of n, s1, and s2? Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Pitfall: Dealing with the Line Terminator, ‘\n’ (3 of 3) 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’) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Methods in the Class Scanner (1 of 3) Display 2.8 Methods of the Scanner Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Methods in the Class Scanner (2 of 3) Display 2.8 Methods of the Scanner Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Methods in the Class Scanner (3 of 3) Display 2.8 Methods of the Scanner Class Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Programming Tip: Prompt for Input A program should always prompt the user when he or she needs to input some data: Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Programming Tip: Echo Input Always echo all input that a program receives from the keyboard In this way a user can check that he or she has entered the input correctly – Even though the input is automatically displayed as the user enters it, echoing the input may expose subtle errors (such as entering the letter “O” instead of a zero) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Self-Service Checkout Line (1 of 2) Display 2.9 Self-Service Check Out Line Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Self-Service Checkout Line (2 of 2) Display 2.9 Self-Service Check Out Line Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved The Empty String A string can have any number of characters, including zero characters – “” is the empty string When a program executes the nextLine method to read a line of text, and the user types nothing on the line but presses the Enter key, then the nextLine Method reads the empty string Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Other Input Delimiters The delimiters that separate keyboard input can be changed when using the Scanner class For example, the following code could be used to create a Scanner object and change the delimiter from whitespace to “##” After invocation of the useDelimiter method, “##” and not whitespace will be the only input delimiter for the input object keyboard2 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Other Input Delimiters (1 of 3) Display 2.10 Changing the Input Delimiter Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Other Input Delimiters (2 of 3) Display 2.10 Changing the Input Delimiter Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Other Input Delimiters (3 of 3) Display 2.10 Changing the Input Delimiter Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Introduction to File Input/Output The Scanner class can also be used to read from files on the disk Here we only present the basic structure of reading from text files – Some keywords are introduced without full explanation – More detail in Chapter 10 – By covering the basics here your programs can work with real-world data that would otherwise be too much work to type into your program every time it is run Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Text Input Import the necessary classes in addition to Scanner Open the file inside a try/catch block – If an error occurs while trying to open the file then execution jumps to the catch block – This is discussed in more detail in Chapter 9 Use nextInt(), nextLine(), etc. to read from the Scanner like reading from the console, except the input comes from the file Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Try/Catch Block Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Text File to Read This file should be stored in the same folder as the Java program in the following display Display 2.11 Sample Text File, Player.txt, to Store a Player’s High Score and Name 100510 Gordon Freeman Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Program to Read a Text File (1 of 2) Display 2.12 Program to Read the Text File in Display 2.11 Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Program to Read a Text File (2 of 2) Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Copyright Copyright © 2016, 2013, 2010 Pearson Education, Inc. All Rights Reserved Absolute Java Sixth Edition Chapter 3 Flow of Control Modified by Dr. Zara Hamid, WLU Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Flow of Control As in most programming languages, flow of control in Java refers to its branching and looping mechanisms Java has several branching mechanisms: if-else, if, and switch statements Java has three types of loop statements: the while, do- while, and for statements Most branching and looping statements are controlled by Boolean expressions – A Boolean expression evaluates to either true or false – The primitive type boolean may only take the values true or false Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Branching with an if-else Statement (1 of 2) An if-else statement chooses between two alternative statements based on the value of a Boolean expression – The Boolean_Expression must be enclosed in parentheses – If the Boolean_Expression is true, then the Yes_Statement is executed – If the Boolean_Expression is false, then the No_Statement is executed Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Branching with an if-else Statement (2 of 2) An if-else statement chooses between two alternative statements based on the value of a Boolean expression – The Boolean_Expression must be enclosed in parentheses – If the Boolean_Expression is true, then the Yes_Statement is executed – If the Boolean_Expression is false, then the No_Statement is executed Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Compound Statements (1 of 2) Each Yes_Statement and No_Statement branch of an if-else can be a made up of a single statement or many statements Compound Statement: A branch statement that is made up of a list of statements – A compound statement must always be enclosed in a pair of braces ({ }) – A compound statement can be used anywhere that a single statement can be used Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Compound Statements (2 of 2) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Omitting the else Part The else part may be omitted to obtain what is often called an if statement – If the Boolean_Expression is true, then the Action_Statement is executed – The Action_Statement can be a single or compound statement – Otherwise, nothing happens, and the program goes on to the next statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Nested Statements if-else statements and if statements both contain smaller statements within them – For example, single or compound statements In fact, any statement at all can be used as a subpart of an if-else or if statement, including another if-else or if statement – Each level of a nested if-else or if should be indented further than the previous level – Exception: multiway if-else statements Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Nested if statements Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The dangling else problem When an if statement is nested inside the then clause of another if statement, the else clause is paired with the closest if statement without an else clause. if ( x == 10 ) if ( y == 9 ) System.out.println( "Line 1" ); else Misleading Indentation System.out.println( "Line 2" ); What will be output if: x = 9, y=9 x=10, y=8 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The dangling else problem In reality it is: if ( x == 10 ) if ( y == 9 ) System.out.println( "Line 1" ); else System.out.println( "Line 2" ); Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The dangling else problem Use braces to pair else with the outer if if ( x == 10 ) { if ( y == 9 ) System.out.println( "Line 1" ); } else { System.out.println( "Line 2" );} Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Multiway if-else Statements (1 of 3) The multiway if-else statement is simply a normal if- else statement that nests another if-else statement at every else branch – 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Multiway if-else Statement (2 of 3) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Multiway if-else Statement (3 of 3) https://dev.to/paulike/nested-if-and-multi-way-if-else-statements-3neh Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Multiway if-else Statement Example Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The switch Statement (1 of 5) 1. What happens if you forget to add break to a case? 2. What happens if you do not include a default case? Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Switch Statement (2 of 5) 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 ▪ The controlling expression must evaluate to a char,int,short,or byte Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Switch Statement (3 of 5) Each branch statement in a switch statement starts with the reserved word case, followed by a constant called a case label, followed by a colon, and then a sequence of statements – Each case label must be of the same type as the controlling expression – Case labels need not be listed in order or span a complete interval, but each one may appear only once – Each sequence of statements may be followed by a break statement ( break;) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Switch Statement (4 of 5) There can also be a section labeled default: – The default section is optional, and is usually last – Even if the case labels cover all possible outcomes in a given switch statement, it is still a good practice to include a default section ▪ It can be used to output an error message, for example When the controlling expression is evaluated, the code for the case label whose value matches the controlling expression is executed – If no case label matches, then the only statements executed are those following the default label (if there is one) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Switch Statement (4 of 5) The switch statement ends when it executes a break statement, or when the end of the switch statement is reached – When the computer executes the statements after a case label, it continues until a break statement is reached – If the break statement is omitted, then after executing the code for one case, the computer will go on to execute the code for the next case – If the break statement is omitted inadvertently, the compiler will not issue an error message Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Switch Statement (5 of 5) https://www.programiz.com/java-programming/switch-statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Conditional Operator (1 of 2) The conditional operator is a notational variant on certain forms of the if-else statement – Also called the ternary operator or arithmetic if – The following examples are equivalent: versus Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Conditional Operator (2 of 2) – The expression to the right of the assignment operator is a conditional operator expression – If the Boolean expression is true, then the expression evaluates to the value of the first expression (n1), otherwise it evaluates to the value of the second expression (n2) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Boolean Expressions A Boolean expression is an expression that is either true or false The simplest Boolean expressions compare the value of two expressions – Note that Java uses two equal signs (==) to perform equality testing: A single equal sign (=) is used only for assignment – A Boolean expression does not need to be enclosed in parentheses, unless it is used in an if-else statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Simple Boolean Expressions Display 3.3 Java Comparison Operators Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Pitfall: Using == with Strings String s1 ="Hello"; String s2 = "Hello"; String s3 =new String("Hello"); System.out.println(s1==s2); //true System.out.println(s1==s3); //false s1 Hello s2 Hello s3 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Lexicographic and Alphabetical Order (1 of 2) 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 comes before s2 in lexicographic ordering, returns zero if the two strings are equal, and returns a positive number if s2 comes before s1 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Lexicographic and Alphabetical Order (2 of 2) 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Building Boolean Expressions (1 of 2) When two Boolean expressions are combined using the "and" (&&) operator, the entire expression is true provided both expressions are true – Otherwise the expression is false 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Building Boolean Expressions (2 of 2) Any Boolean expression can be negated using the ! Operator – Place the expression in parentheses and place the ! operator in front of it Unlike mathematical notation, strings of inequalities must be joined by && – Use (min  result) & & (result  max) rather than min  result  max Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Truth Tables (1 of 3) AND Exp underscore one Exp underscore two Exp underscore one and exp underscore two Exp_1 Exp_2 Exp_1 & & Exp_2 true true true true false false false true false false false false Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Truth Tables (2 of 3) OR Exp underscore one Exp underscore two Exp underscore one or exp underscore two Exp_1 Exp_2 Exp_1 || Exp_2 true true true true false true false true true false false false Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Truth Tables (3 of 3) NOT ! (Exp) Not of exp Exp true false false true Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Short-Circuit and Complete Evaluation (1 of 2) Java can take a shortcut when the evaluation of the first part of a Boolean expression produces a result that evaluation of the second part cannot change This is called short-circuit evaluation or lazy evaluation – For example, when evaluating two Boolean subexpressions joined by &&, if the first subexpression evaluates to false, then the entire expression will evaluate to false, no matter the value of the second subexpression – In like manner, when evaluating two Boolean subexpressions joined by ||, if the first subexpression evaluates to true, then the entire expression will evaluate to true Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Short-Circuit and Complete Evaluation (2 of 2) There are times when using short-circuit evaluation can prevent a runtime error – In the following example, if the number of kids is equal to zero, then the second subexpression will not be evaluated, thus preventing a divide by zero error – Note that reversing the order of the subexpressions will not prevent this if ((kids ! = 0) & & ((toys/kids) = 2))... Sometimes it is preferable to always evaluate both expressions, i.e., request complete evaluation – In this case, use the & and | operators instead of && and || Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Precedence and Associativity Rules (1 of 2) 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 – 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Precedence and Associativity Rules (2 of 2) Display 3.6 Precedence and Associativity Rules Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Evaluating Expressions (1 of 2) In general, parentheses in an expression help to document the programmer's intent – Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious Binding: The association of operands with their operators – A fully parenthesized expression accomplishes binding for all the operators in an expression Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Evaluating Expressions (2 of 2) Side Effects: When, in addition to returning a value, an expression changes something, such as the value of a variable – The assignment, increment, and decrement operators all produce side effects Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Rules for Evaluating Expressions Perform binding – Determine the equivalent fully parenthesized expression using the precedence and associativity rules – Proceeding left to right, evaluate whatever subexpressions can be immediately evaluated – These subexpressions will be operands or method arguments, e.g., numeric constants or variables Evaluate each outer operation and method invocation as soon as all of its operands (i.e., arguments) have been evaluated Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Loops Loops in Java are similar to those in other high-level languages Java has three types of loop statements: the while, the do-while, and the for statements – 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved While Statement 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 ▪ 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 ({ }) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved While Syntax or Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Do-While Statement (1 of 2) 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 the loop body is executed Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Do-While Statement (2 of 2) – The Boolean expression is checked after each iteration of the loop body ▪ 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 ({ }) Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Do-While Syntax or Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Equivalence of while and do-while loop (1 of 2) Given the following structure for a do-while loop: The equivalent while loop is: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Equivalence of while and do-while loop (2 of 2) Given the following structure for a while loop: The equivalent do-while loop is: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Algorithms and Pseudocode (1 of 2) The hard part of solving a problem with a computer program is not dealing with the syntax rules of a programming language Rather, coming up with the underlying solution method is the most difficult part An algorithm is a set of precise instructions that lead to a solution Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Algorithms and Pseudocode (2 of 2) – An algorithm is normally written in pseudocode, which is a mixture of programming language and a human language, like English – Pseudocode must be precise and clear enough so that a good programmer can convert it to syntactically correct code – However, pseudocode is much less rigid than code: One needn't worry about the fine points of syntax or declaring variables, for example Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement (1 of 5) 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement (2 of 5) – 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement Syntax The Body may consist of a single statement or a list of statements enclosed in a pair of braces ({ }) 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement (3 of 5) Display 3.9 Semantics of the for statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement (4 of 5) Display 3.10 for Statement syntax and alternative Semantics (Part 1 of 2) The For Statement Syntax: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The for Statement (5 of 5) Display 3.10 for Statement syntax and alternative Semantics (Part 2 of 2) Equivalent while loop: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Comma in for Statements (1 of 2) A for loop can contain multiple initialization actions separated with commas – Caution must be used when combining a declaration with multiple actions – It is illegal to combine multiple type declarations with multiple actions, for example – To avoid possible problems, it is best to declare all variables outside the for statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Comma in for Statements (2 of 2) A for loop can contain multiple update actions, separated with commas, also – It is even possible to eliminate the loop body in this way However, a for loop can contain only one Boolean expression to test for ending the loop Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Infinite Loops A while, do-while, or for loop should be designed so that the value tested in the Boolean expression is changed in a way that eventually makes it false, and terminates the loop If the Boolean expression remains true, then the loop will run forever, resulting in an infinite loop – Loops that check for equality or inequality (== or !=) are especially prone to this error and should be avoided if possible Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved 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 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The break and continue Statements (1 of 2) The break statement consists of the keyword break followed by a semicolon – When executed, the break statement ends the nearest enclosing switch or loop statement The continue statement consists of the keyword continue followed by a semicolon – When executed, the continue statement ends the current loop body iteration of the nearest enclosing loop statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The break and continue Statements (2 of 2) – Note that in a for loop, the continue statement transfers control to the update expression When loop statements are nested, remember that any break or continue statement applies to the innermost, containing loop statement Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved What will be the output of the following for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); } Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The Labeled break Statement There is a type of break statement that, when used in nested loops, can end any containing loop, not just the innermost loop If an enclosing loop statement is labeled with an Identifier, then the following version of the break statement will exit the labeled loop, even if it is not the innermost enclosing loop: break someIdentifier; To label a loop, simply precede it with an Identifier and a colon: someIdentifier: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved The exit Statement A break statement will end a loop or switch statement, but will not end the program The exit statement will immediately end the program as soon as it is invoked: System.exit(0); The exit statement takes one integer argument – By tradition, a zero argument is used to indicate a normal ending of the program Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Loop Bugs The two most common kinds of loop errors are unintended infinite loops and off-by-one errors – An off-by-one error is when a loop repeats the loop body one too many or one too few times ▪ This usually results from a carelessly designed Boolean test expression – Use of == in the controlling Boolean expression can lead to an infinite loop or an off-by-one error ▪ This sort of testing works only for characters and integers, and should never be used for floating- point Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Tracing Variables (1 of 2) Tracing variables involves watching one or more variables change value while a program is running This can make it easier to discover errors in a program and debug them Many IDEs (Integrated Development Environments) have a built-in utility that allows variables to be traced without making any changes to the program Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Tracing Variables (2 of 2) Another way to trace variables is to simply insert temporary output statements in a program – When the error is found and corrected, the trace statements can simply be commented out Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved General Debugging Techniques Examine the system as a whole – don’t assume the bug occurs in one particular place Try different test cases and check the input values Comment out blocks of code to narrow down the offending code Check common pitfalls Take a break and come back later DO NOT make random changes just hoping that the change will fix the problem! Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (1 of 9) The following code is supposed to present a menu and get user input until either ‘a’ or ‘b’ is entered. Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (2 of 9) Result: Syntax error: Using the “random change” debugging technique we might try to change the data type of c to String, to make the types match This results in more errors since the rest of the code treats c like a char Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (3 of 9) First problem: substring returns a String, use charAt to get the first character: Now the program compiles, but it is stuck in an infinite loop. Employ tracing: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (4 of 9) From tracing we can see that the string is never changed to lowercase. Reassign the lowercase string back to s. Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (5 of 9) The following code is supposed to present a menu and get user input until either ‘a’ or ‘b’ is entered. However, it’s still stuck in an infinite loop. What to try next? Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (6 of 9) Could try the following “patch” This works, but it is ugly! Considered a coding atrocity, it doesn’t fix the underlying problem. The boolean condition after the while loop has also become meaningless.Try more tracing: Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (7 of 9) From the trace we can see that the loop’s boolean expression is true because c cannot be not equal to ‘a’ and not equal to ‘b’ at the same time. Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (8 of 9) Fix: We use && instead of || Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Debugging Example (9 of 9) Even better: Declare a boolean variable to control the do- while loop. This makes it clear when the loop exits if we pick a meaningful variable name. Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Do debugging to fix the following code String result = ""; String message = "watch out"; int pos = 0; while (pos < message.length()) { result = result + message.substring(pos,pos+2); pos = pos + 1; } System.out.println(result); Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Assertion Checks (1 of 2) An assertion is a sentence that says (asserts) something about the state of a program – An assertion must be either true or false, and should be true if a program is working properly – Assertions can be placed in a program as comments Java has a statement that can check if an assertion is true – If assertion checking is turned on and the Boolean_Expression evaluates to false, the program ends, and outputs an assertion failed error message – Otherwise, the program finishes execution normally Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Assertion Checks (2 of 2) A program or other class containing assertions is compiled in the usual way After compilation, a program can run with assertion checking turned on or turned off – Normally a program runs with assertion checking turned off In order to run a program with assertion checking turned on, use the following command (using the actual Program Name): Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Preventive Coding Incremental Development – Write a little bit of code at a time and test it before moving on Code Review – Have others look at your code Pair Programming – Programming in a team, one typing while the other watches, and periodically switch roles Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Generating Random Numbers (1 of 2) The Random class can be used to generate pseudo- random numbers – Not truly random, but uniform distribution based on a mathematical function and good enough in most cases Add the following import Create an object of type Random Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Generating Random Numbers To generate random numbers use the nextInt() method to get a random number from 0 to n-1 int i = rnd.nextInt (10); // Random number from 0 to 9 Use the nextDouble() method to get a random number from 0 to 1 (always less than 1) double d = rnd.nextDouble(); // d is = 0 and  1 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Simulating a Coin Flip Display 3.11 Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved Copyright Copyright © 2016,2013,2010 Pearson Education, Inc. All Rights Reserved CP213: Object-Oriented Programming Defining Classes I Dr. Zia Ud Din Modified by Dr. Zara Hamid, WLU Lecture Outline  Classes, Objects, Fields, and Methods  new Operator  Encapsulation and Data Hiding  Accessor (Getter) and Mutator (Setter) Methods  Method Overloading  Constructors  this Parameter  Data Validation in Mutators, and Constructors Zia Ud Din CP213: Object-Oriented Programming 2 Lecture Outline  Classes, Objects, Fields, and Methods  new Operator  Encapsulation and Data Hiding  Accessor (Getter) and Mutator (Setter) Methods  Method Overloading  Constructors  this Parameter  Data Validation in Mutators, and Constructors Zia Ud Din CP213: Object-Oriented Programming 3 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 

Use Quizgecko on...
Browser
Browser