O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Lecture 3 java basics

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Próximos SlideShares
C progrmming
C progrmming
Carregando em…3
×

Confira estes a seguir

1 de 252 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Anúncio

Semelhante a Lecture 3 java basics (20)

Lecture 3 java basics

  1. 1. Introduction to Computer Science II Lecture 3 : Java Essentials (Chapter 1) COSC 1320/6305
  2. 2. Preventive Coding <ul><li>Incremental Development </li></ul><ul><ul><li>Write a little bit of code at a time and test it before moving on </li></ul></ul><ul><li>Code Review </li></ul><ul><ul><li>Have others look at your code </li></ul></ul><ul><li>Pair Programming </li></ul><ul><ul><li>Programming in a team, one typing while the other watches, and periodically switch roles </li></ul></ul>3-
  3. 3. 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  4. 4. Class Participation NetBeans Projects
  5. 5. Java <ul><li>Most people are familiar with Java as a language for Internet applications </li></ul><ul><li>We will study Java as a general purpose programming language </li></ul><ul><ul><li>The syntax of expressions and assignments will be similar to that of other high-level languages </li></ul></ul><ul><ul><li>Details concerning the handling of strings and console output will probably be new </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  6. 6. Origins of the Java Language <ul><li>Created by Sun Microsystems team led by James Gosling ( 1991 ) </li></ul><ul><li>Originally designed for programming home appliances </li></ul><ul><ul><li>Difficult task because appliances are controlled by a wide variety of computer processors </li></ul></ul><ul><ul><li>Team developed a two-step translation process to simplify the task of compiler writing for each class of appliances </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  7. 7. Origins of the Java Language <ul><li>Significance of Java translation process </li></ul><ul><ul><li>Writing a compiler (translation program) for each type of appliance processor would have been very costly </li></ul></ul><ul><ul><li>Instead, developed intermediate language that is the same for all types of processors : Java byte-code </li></ul></ul><ul><ul><li>Therefore, only a small, easy to write program was needed to translate byte-code into the machine code for each processor </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  8. 8. Java is Compiled and Interpreted Text Editor Compiler Interpreter Programmer Source Code .java file Byte Code . class file Hardware and Operating System Notepad, emacs,vi javac java appletviewer netscape
  9. 9. Compiled Languages Text Editor Compiler Linker Programmer Source Code .c file Object Code . o file Notepad, emacs,vi gcc Executable Code a.out file
  10. 10. Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Windows 95 Macintosh Solaris Windows NT (translator) (same for all platforms) (one for each different system)
  11. 11. Architecture Neutral & Portable <ul><li>Java Compiler - Java source code (file with extension . java ) to bytecode ( file with extension .class ) </li></ul><ul><li>Bytecode - an intermediate form, closer to machine representation </li></ul><ul><li>A interpreter (virtual machine) on any target platform interprets the bytecode. </li></ul>
  12. 12. Architecture Neutral & Portable <ul><li>Porting the java system to any new platform involves writing an interpreter . </li></ul><ul><li>The interpreter will figure out what the equivalent machine dependent code to run </li></ul>
  13. 13. Rich Class Environment <ul><li>Core Classes </li></ul><ul><ul><li>language </li></ul></ul><ul><ul><li>Utilities </li></ul></ul><ul><ul><li>Input/Output </li></ul></ul><ul><ul><li>Low-Level Networking </li></ul></ul><ul><ul><li>Abstract Graphical User Interface </li></ul></ul><ul><li>Internet Classes </li></ul><ul><ul><li>TCP/IP Networking </li></ul></ul><ul><ul><li>WWW and HTML </li></ul></ul><ul><ul><li>Distributed Programs </li></ul></ul>
  14. 14. Java Development Kit <ul><li>javac - The Java Compiler </li></ul><ul><li>java - The Java Interpreter </li></ul><ul><li>jdb- The Java Debugger </li></ul><ul><li>appletviewer -Tool to run the applets </li></ul><ul><li>javap - to print the Java bytecodes </li></ul><ul><li>javaprof - Java profiler </li></ul><ul><li>javadoc - documentation generator </li></ul><ul><li>javah - creates C header files </li></ul>
  15. 15. Java Environment
  16. 16. Java Development Kit <ul><li>javac - The Java Compiler </li></ul><ul><li>java - The Java Interpreter </li></ul><ul><li>jdb- The Java Debugger </li></ul><ul><li>appletviewer -Tool to run the applets </li></ul><ul><li>javap - to print the Java bytecodes </li></ul><ul><li>javaprof - Java profiler </li></ul><ul><li>javadoc - documentation generator </li></ul><ul><li>javah - creates C header files </li></ul>
  17. 17. Process of Building and Running Java Programs Text Editor Java Source Code javac Java Class File java Outout javadoc javah jdb HTML Files Header Files
  18. 18. How Does Java compares to C++
  19. 19. Overlap of C , C++ , and Java C C++ Java
  20. 20. Origins of the Java Language <ul><li>Patrick Naughton and Jonathan Payne at Sun Microsystems developed a Web browser that could run programs over the Internet ( 1994 ) </li></ul><ul><ul><li>Beginning of Java's connection to the Internet </li></ul></ul><ul><ul><li>Original browser evolves into HotJava </li></ul></ul><ul><li>Netscape Incorporated made its Web browser capable of running Java programs (1995) </li></ul><ul><ul><li>Other companies follow suit </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  21. 21. Objects and Methods <ul><li>Java is an object-oriented programming (OOP) language </li></ul><ul><ul><li>Programming methodology that views a program as consisting of objects that interact with one another by means of actions (called methods ) </li></ul></ul><ul><ul><li>Objects of the same kind are said to have the same type or be in the same class </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  22. 22. Terminology Comparisons <ul><li>Other high-level languages have constructs called procedures, methods, functions, and/or subprograms </li></ul><ul><ul><li>These types of constructs are called methods in Java </li></ul></ul><ul><ul><li>All programming constructs in Java, including methods , are part of a class </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  23. 23. Computer Language Levels <ul><li>High-level language : A language that people can read, write, and understand </li></ul><ul><ul><li>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 </li></ul></ul><ul><li>Machine language : A language that a computer can understand </li></ul><ul><li>Low-level language : Machine language or any language similar to machine language </li></ul><ul><li>Compiler : A program that translates a high-level language program into an equivalent low-level language program </li></ul><ul><ul><li>This translation process is called compiling </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  24. 24. Byte-Code and the Java Virtual Machine <ul><li>The compilers for most programming languages translate high-level programs directly into the machine language for a particular computer </li></ul><ul><ul><li>Since different computers have different machine languages, a different compiler is needed for each one </li></ul></ul><ul><li>In contrast, the Java compiler translates Java programs into byte-code , a machine language for a fictitious computer called the Java Virtual Machine </li></ul><ul><ul><li>Once compiled to byte-code , a Java program can be used on any computer , making it very portable </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  25. 25. Byte-Code and the Java Virtual Machine <ul><li>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 </li></ul><ul><ul><li>The interpreter translates and immediately executes each byte-code instruction, one after another </li></ul></ul><ul><ul><li>Translating byte-code into machine code is relatively easy compared to the initial compilation step </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  26. 26. Program terminology <ul><li>Code : A program or a part of a program </li></ul><ul><li>Source code (or source program ): A program written in a high-level language such as Java </li></ul><ul><ul><li>The input to the compiler program </li></ul></ul><ul><li>Object code : The translated low-level program </li></ul><ul><ul><li>The output from the compiler program, e.g., Java byte-code </li></ul></ul><ul><ul><li>In the case of Java byte-code, the input to the Java byte-code interpreter </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  27. 27. Class Loader <ul><li>Java programs are divided into smaller parts called classes </li></ul><ul><ul><li>Each class definition is normally in a separate file and compiled separately </li></ul></ul><ul><li>Class Loader : A program that connects the byte-code of the classes needed to run a Java program </li></ul><ul><ul><li>In other programming languages, the corresponding program is called a linker </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  28. 28. Compiling a Java Program or Class <ul><li>Each class definition must be in a file whose name is the same as the class name followed by . java </li></ul><ul><ul><li>The class FirstProgram must be in a file named FirstProgram.java </li></ul></ul><ul><li>Each class is compiled with the command javac followed by the name of the file in which the class resides </li></ul><ul><ul><li>javac FirstProgram.java </li></ul></ul><ul><ul><li>The result is a byte-code program whose filename is the same as the class name followed by . class </li></ul></ul><ul><ul><li>FirstProgram.class </li></ul></ul>1-
  29. 29. Running a Java Program <ul><li>A Java program can be given the run command ( java ) after all its classes have been compiled </li></ul><ul><ul><li>Only run the class that contains the main method (the system will automatically load and run the other classes, if any) </li></ul></ul><ul><ul><li>The main method begins with the line: </li></ul></ul><ul><ul><li>public static void main(String[ ] args) </li></ul></ul><ul><ul><li>Follow the run command by the name of the class only (no .java or . class extension) </li></ul></ul><ul><ul><li>java FirstProgram </li></ul></ul>1-
  30. 30. Syntax and Semantics <ul><li>Syntax : The arrangement of words and punctuations that are legal in a language, the grammar rules of a language </li></ul><ul><li>Semantics : The meaning of things written while following the syntax rules of a language </li></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  31. 31. Tip: Error Messages <ul><li>Bug : A mistake in a program </li></ul><ul><ul><li>The process of eliminating bugs is called debugging </li></ul></ul><ul><li>Syntax error: A grammatical mistake in a program </li></ul><ul><ul><li>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 </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  32. 32. Tip: Error Messages <ul><li>Run-time error: An error that is not detected until a program is run </li></ul><ul><ul><li>The compiler cannot detect these errors: an error message is not generated after compilation, but after execution </li></ul></ul><ul><li>Logic error: A mistake in the underlying algorithm for a program </li></ul><ul><ul><li>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 </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  33. 34. Identifiers <ul><li>Identifier : The name of a variable or other item (class, method, object, etc.) defined in a program </li></ul><ul><ul><li>A Java identifier must not start with a digit, and all the characters must be letters, digits, or the underscore symbol </li></ul></ul><ul><ul><li>Java identifiers can theoretically be of any length </li></ul></ul><ul><ul><li>Java is a case-sensitive language: Rate , rate , and RATE are the names of three different variables </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  34. 35. Identifiers <ul><li>Keywords and Reserved words: Identifiers that have a predefined meaning in Java </li></ul><ul><ul><li>Do not use them to name anything else </li></ul></ul><ul><ul><li>public class void static </li></ul></ul><ul><li>Predefined identifiers: Identifiers that are defined in libraries required by the Java language standard </li></ul><ul><ul><li>Although they can be redefined, this could be confusing and dangerous if doing so would change their standard meaning </li></ul></ul><ul><ul><li>System String println </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  35. 36. Naming Conventions <ul><li>Start the names of variables, classes, methods, and objects with a lowercase letter, indicate &quot;word&quot; boundaries with an uppercase letter, and restrict the remaining characters to digits and lowercase letters </li></ul><ul><ul><li>topSpeed bankRate1 timeOfArrival </li></ul></ul><ul><li>Start the names of classes with an uppercase letter and, otherwise, adhere to the rules above </li></ul><ul><ul><li>FirstProgram MyClass String </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  36. 38. Variable Declarations <ul><li>Every variable in a Java program must be declared before it is used </li></ul><ul><ul><li>A variable declaration tells the compiler what kind of data (type) will be stored in the variable </li></ul></ul><ul><ul><li>The type of the variable is followed by one or more variable names separated by commas, and terminated with a semicolon </li></ul></ul><ul><ul><li>Variables are typically declared just before they are used or at the start of a block (indicated by an opening brace { ) </li></ul></ul><ul><ul><li>Basic types in Java are called primitive types </li></ul></ul><ul><ul><ul><li>int numberOfBeans; </li></ul></ul></ul><ul><ul><ul><li>double oneWeight, totalWeight; </li></ul></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  37. 40. Primitive Types 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  38. 42. Assignment Statements With Primitive Types <ul><li>In Java, the assignment statement is used to change the value of a variable </li></ul><ul><ul><li>The equal sign ( = ) is used as the assignment operator </li></ul></ul><ul><ul><li>An assignment statement consists of a variable on the left side of the operator, and an expression on the right side of the operator </li></ul></ul><ul><ul><ul><li>Variable = Expression; </li></ul></ul></ul><ul><ul><li>An expression consists of a variable, number, or mix of variables, numbers, operators, and/or method invocations </li></ul></ul><ul><ul><li>temperature = 98.6; </li></ul></ul><ul><ul><li>count = numberOfBeans; </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  39. 43. Assignment Statements With Primitive Types <ul><ul><li>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 </li></ul></ul><ul><ul><li>distance = rate * time; </li></ul></ul><ul><ul><li>Note that a variable can occur on both sides of the assignment operator </li></ul></ul><ul><ul><li>count = count + 2; </li></ul></ul><ul><ul><li>The assignment operator is automatically executed from right-to-left, so assignment statements can be chained </li></ul></ul><ul><ul><li>number2 = number1 = 3; </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  40. 45. Tip: Initialize Variables <ul><li>A variable that has been declared but that has not yet been given a value by some means is said to be uninitialized </li></ul><ul><li>In certain cases an uninitialized variable is given a default value </li></ul><ul><ul><li>It is best not to rely on this </li></ul></ul><ul><ul><li>Explicitly initialized variables have the added benefit of improving program clarity </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  41. 46. Tip: Initialize Variables <ul><li>The declaration of a variable can be combined with its initialization via an assignment statement </li></ul><ul><ul><ul><li>int count = 0; </li></ul></ul></ul><ul><ul><ul><li>double distance = 55 * .5; </li></ul></ul></ul><ul><ul><ul><li>char grade = 'A'; </li></ul></ul></ul><ul><ul><li>Note that some variables can be initialized and others can remain uninitialized in the same declaration </li></ul></ul><ul><ul><li>int initialCount = 50, finalCount; </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  42. 48. Shorthand Assignment Statements <ul><li>Shorthand assignment notation combines the assignment operator ( = ) and an arithmetic operator </li></ul><ul><li>It is used to change the value of a variable by adding, subtracting, multiplying, or dividing by a specified value </li></ul><ul><li>The general form is </li></ul><ul><ul><li>Variable Op = Expression </li></ul></ul><ul><ul><li>which is equivalent to </li></ul></ul><ul><ul><li>Variable = Variable Op (Expression) </li></ul></ul><ul><ul><li>The Expression can be another variable, a constant, or a more complicated expression </li></ul></ul><ul><ul><li>Some examples of what Op can be are + , - , * , / , or % </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  43. 49. Shorthand Assignment Statements 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 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);
  44. 51. Assignment Compatibility <ul><li>In general, the value of one type cannot be stored in a variable of another type </li></ul><ul><ul><li>int intVariable = 2.99; //Illegal </li></ul></ul><ul><ul><li>The above example results in a type mismatch because a double value cannot be stored in an int variable </li></ul></ul><ul><li>However, there are exceptions to this </li></ul><ul><ul><li>double doubleVariable = 2; </li></ul></ul><ul><ul><li>For example, an int value can be stored in a double type </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  45. 52. Assignment Compatibility <ul><li>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 </li></ul><ul><ul><li>byte  short  int  long  float  double </li></ul></ul><ul><ul><li>char </li></ul></ul><ul><ul><li>Note that as your move down the list from left to right, the range of allowed values for the types becomes larger </li></ul></ul><ul><li>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 ) </li></ul><ul><li>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 </li></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  46. 53. Constants <ul><li>Constant (or literal ): An item in Java which has one specific value that cannot change </li></ul><ul><ul><li>Constants of an integer type may not be written with a decimal point (e.g., 10 ) </li></ul></ul><ul><ul><li>Constants of a floating-point type can be written in ordinary decimal fraction form (e.g., 367000.0 or 0.000589 ) </li></ul></ul><ul><ul><li>Constant of a floating-point type can also be written in scientific (or floating-point ) notation (e.g., 3.67e5 or 5.89e-4 ) </li></ul></ul><ul><ul><ul><li>Note that the number before the e may contain a decimal point, but the number after the e may not </li></ul></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  47. 54. Constants <ul><li>Constants of type char are expressed by placing a single character in single quotes (e.g., ' Z ' ) </li></ul><ul><li>Constants for strings of characters are enclosed by double quotes (e.g., &quot; Welcome to Java&quot; ) </li></ul><ul><li>There are only two boolean type constants, true and false </li></ul><ul><ul><li>Note that they must be spelled with all lowercase letters </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  48. 55. Arithmetic Operators and Expressions <ul><li>As in most languages, expressions can be formed in Java using variables, constants, and arithmetic operators </li></ul><ul><ul><li>These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo, remainder) </li></ul></ul><ul><ul><li>An expression can be used anyplace it is legal to use a value of the type produced by the expression </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  49. 56. Arithmetic Operators and Expressions <ul><li>If an arithmetic operator is combined with int operands, then the resulting type is int </li></ul><ul><li>If an arithmetic operator is combined with one or two double operands, then the resulting type is double </li></ul><ul><li>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 </li></ul><ul><ul><li>byte  short  int  long  float  double </li></ul></ul><ul><ul><li>char </li></ul></ul><ul><ul><li>Exception: If the type produced should be byte or short (according to the rules above), then the type produced will actually be an int </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  50. 57. Parentheses and Precedence Rules <ul><li>An expression can be fully parenthesized in order to specify exactly what subexpressions are combined with each operator </li></ul><ul><li>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 </li></ul><ul><ul><li>However, it's best (and sometimes necessary) to include them </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  51. 58. Precedence Rules 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  52. 59. Precedence and Associativity Rules <ul><li>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 </li></ul><ul><ul><ul><li>base + rate * hours is evaluated as </li></ul></ul></ul><ul><ul><ul><li>base + (rate * hours) </li></ul></ul></ul><ul><li>When two operations have equal precedence, the order of operations is determined by associativity rules </li></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  53. 60. Precedence and Associativity Rules <ul><ul><li>Unary operators of equal precedence are grouped right-to-left </li></ul></ul><ul><ul><ul><li>+-+rate is evaluated as +(-(+rate)) </li></ul></ul></ul><ul><ul><li>Binary operators of equal precedence are grouped left-to-right </li></ul></ul><ul><ul><ul><li>base + rate + hours is evaluated as </li></ul></ul></ul><ul><ul><ul><li>(base + rate) + hours </li></ul></ul></ul><ul><ul><li>Exception: A string of assignment operators is grouped right-to-left </li></ul></ul><ul><ul><ul><li>n1 = n2 = n3; is evaluated as n1 = (n2 = n3); </li></ul></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  54. 61. Pitfall: Round-Off Errors in Floating-Point Numbers <ul><li>Floating point numbers are only approximate quantities </li></ul><ul><ul><li>Mathematically, the floating-point number 1.0/3.0 is equal to 0.3333333 . . . </li></ul></ul><ul><ul><li>A computer has a finite amount of storage space </li></ul></ul><ul><ul><ul><li>It may store 1.0/3.0 as something like 0.3333333333, which is slightly smaller than one-third </li></ul></ul></ul><ul><ul><li>Computers actually store numbers in binary notation, but the consequences are the same: floating-point numbers may lose accuracy </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  55. 62. Integer and Floating-Point Division <ul><li>When one or both operands are a floating-point type, division results in a floating-point type </li></ul><ul><ul><li>15.0/2 evaluates to 7.5 </li></ul></ul><ul><li>When both operands are integer types, division results in an integer type </li></ul><ul><ul><li>Any fractional part is discarded </li></ul></ul><ul><ul><li>The number is not rounded </li></ul></ul><ul><ul><ul><li>15/2 evaluates to 7 </li></ul></ul></ul><ul><li>Be careful to make at least one of the operands a floating-point type if the fractional portion is needed </li></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  56. 63. The % Operator <ul><li>The % operator is used with operands of type int to recover the information lost after performing integer division </li></ul><ul><ul><li>15/2 evaluates to the quotient 7 </li></ul></ul><ul><ul><li>15%2 evaluates to the remainder 1 </li></ul></ul><ul><li>The % operator can be used to count by 2's, 3's, or any other number </li></ul><ul><ul><li>To count by twos, perform the operation number % 2 , and when the result is 0 , number is even </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  57. 64. Type Casting <ul><li>A type cast takes a value of one type and produces a value of another type with an &quot;equivalent&quot; value </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><ul><li>double ans = n / (double) m; </li></ul></ul></ul><ul><ul><li>Note that the desired type is placed inside parentheses immediately in front of the variable to be cast </li></ul></ul><ul><ul><li>Note also that the type and value of the variable to be cast does not change </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  58. 65. More Details About Type Casting <ul><li>When type casting from a floating-point to an integer type, the number is truncated, not rounded </li></ul><ul><ul><li>(int)2.9 evaluates to 2 , not 3 </li></ul></ul><ul><li>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 </li></ul><ul><ul><ul><li>double d = 5; </li></ul></ul></ul><ul><li>In contrast, it is illegal to place a double value into an int variable without an explicit type cast </li></ul><ul><ul><ul><li>int i = 5.5; // Illegal </li></ul></ul></ul><ul><ul><ul><li>int i = (int) 5.5 // Correct </li></ul></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  59. 66. Increment and Decrement Operators <ul><li>The increment operator ( ++ ) adds one to the value of a variable </li></ul><ul><ul><li>If n is equal to 2 , then n++ or ++n will change the value of n to 3 </li></ul></ul><ul><li>The decrement operator ( -- ) subtracts one from the value of a variable </li></ul><ul><ul><li>If n is equal to 4 , then n-- or --n will change the value of n to 3 </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  60. 67. Increment and Decrement Operators <ul><li>When either operator precedes its variable, and is part of an expression, then the expression is evaluated using the changed value of the variable </li></ul><ul><ul><li>If n is equal to 2 , then 2*(++n) evaluates to 6 </li></ul></ul><ul><li>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 </li></ul><ul><ul><li>If n is equal to 2 , then 2*(n++) evaluates to 4 </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  61. 69. 4- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  62. 70. CLASS Participation A ! (pp. 44)
  63. 71. 13- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  64. 72. The Class String <ul><li>There is no primitive type for strings in Java </li></ul><ul><li>The class String is a predefined class in Java that is used to store and process strings </li></ul><ul><li>Objects of type String are made up of strings of characters that are written within double quotes </li></ul><ul><ul><li>Any quoted string is a constant of type String </li></ul></ul><ul><ul><ul><li>&quot;Live long and prosper.“ </li></ul></ul></ul><ul><li>A variable of type String can be given the value of a String object </li></ul><ul><ul><li>String blessing = &quot;Live long and prosper.&quot;; </li></ul></ul>
  65. 73. Concatenation of Strings <ul><li>Concatenation : Using the + operator on two strings in order to connect them to form one longer string </li></ul><ul><ul><li>If greeting is equal to &quot;Hello &quot; , and javaClass is equal to &quot;class&quot; , then greeting + javaClass is equal to &quot;Hello class“ </li></ul></ul><ul><li>Any number of strings can be concatenated together </li></ul><ul><li>When a string is combined with almost any other type of item, the result is a string </li></ul><ul><ul><li>&quot;The answer is &quot; + 42 evaluates to </li></ul></ul><ul><ul><li>&quot;The answer is 42&quot; </li></ul></ul>
  66. 74. Classes, Objects , and Methods <ul><li>A class is the name for a type whose values are objects </li></ul><ul><li>Objects are entities that store data and take actions </li></ul><ul><ul><li>Objects of the String class store data consisting of strings of characters </li></ul></ul><ul><li>The actions that an object can take are called methods </li></ul><ul><ul><li>Methods can return a value of a single type and/or perform an action </li></ul></ul><ul><ul><li>All objects within a class have the same methods , but each can have different data values </li></ul></ul>
  67. 75. Classes, Objects , and Methods <ul><li>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 </li></ul><ul><ul><li>This is sometimes referred to as sending a message to the object </li></ul></ul><ul><ul><li>The parentheses contain the information (if any) needed by the method </li></ul></ul><ul><ul><li>This information is called an argument (or arguments ) </li></ul></ul>
  68. 76. String Methods <ul><li>The String class contains many useful methods for string-processing applications </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>If a String method returns a value, then it can be placed anywhere that a value of its type can be used </li></ul></ul><ul><ul><ul><li>String greeting = &quot;Hello&quot;; </li></ul></ul></ul><ul><ul><ul><li>int count = greeting . length () ; </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Length is &quot; + greeting . length () ); </li></ul></ul></ul><ul><ul><li>Always count from zero when referring to the position or index of a character in a string </li></ul></ul>
  69. 77. Some Methods in the Class String (Part 1 of 8)
  70. 78. Some Methods in the Class String (Part 2 of 8) 1-
  71. 79. Some Methods in the Class String (Part 3 of 8) 1-
  72. 80. Some Methods in the Class String (Part 4 of 8) 1-
  73. 81. Some Methods in the Class String (Part 5 of 8)
  74. 82. Some Methods in the Class String (Part 6 of 8) 1-
  75. 83. Some Methods in the Class String (Part 7 of 8) 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  76. 84. Some Methods in the Class String (Part 8 of 8) 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  77. 85. String Indexes 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  78. 86. Escape Sequences <ul><li>A backslash ( ) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character </li></ul><ul><ul><li>The character following the backslash does not have its usual meaning </li></ul></ul><ul><ul><li>Although it is formed using two symbols, it is regarded as a single character </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  79. 87. Escape Sequences 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  80. 88. String Processing <ul><li>A String object in Java is considered to be immutable, i.e., the characters it contains cannot be changed </li></ul><ul><li>There is another class in Java called StringBuffer that has methods for editing its string objects </li></ul><ul><li>However, it is possible to change the value of a String variable by using an assignment statement </li></ul><ul><ul><ul><li>String name = &quot;Soprano&quot;; </li></ul></ul></ul><ul><ul><ul><li>name = &quot;Anthony &quot; + name ; </li></ul></ul></ul>
  81. 89. Character Sets <ul><li>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 </li></ul><ul><ul><li>Each character is represented by a particular number </li></ul></ul><ul><li>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 </li></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  82. 91. Naming Constants <ul><li>Instead of using &quot;anonymous&quot; numbers in a program, always declare them as named constants, and use their name instead </li></ul><ul><ul><li>public static final int INCHES_PER_FOOT = 12; </li></ul></ul><ul><ul><li>public static final double RATE = 0.14; </li></ul></ul><ul><ul><li>This prevents a value from being changed inadvertently </li></ul></ul><ul><ul><li>It has the added advantage that when a value must be modified, it need only be changed in one place </li></ul></ul><ul><ul><li>Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore character </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  83. 92. Comments <ul><li>A line comment begins with the symbols // , and causes the compiler to ignore the remainder of the line </li></ul><ul><ul><li>This type of comment is used for the code writer or for a programmer who modifies the code </li></ul></ul><ul><li>A block comment begins with the symbol pair /* , and ends with the symbol pair */ </li></ul><ul><ul><li>The compiler ignores anything in between </li></ul></ul><ul><ul><li>This type of comment can span several lines </li></ul></ul><ul><ul><li>This type of comment provides documentation for the users of the program </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  84. 93. Program Documentation <ul><li>Java comes with a program called javadoc that will automatically extract documentation from block comments in the classes you define </li></ul><ul><ul><li>As long as their opening has an extra asterisk ( /** ) </li></ul></ul><ul><li>Ultimately, a well written program is self-documenting </li></ul><ul><ul><li>Its structure is made clear by the choice of identifier names and the indenting pattern </li></ul></ul><ul><ul><li>When one structure is nested inside another, the inside structure is indented one more level </li></ul></ul>1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  85. 94. Comments and a Named Constant 1- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  86. 95. Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C
  87. 96. Contents <ul><li>Hello World Program Statements Explained </li></ul><ul><li>Java Program Structure in General </li></ul><ul><li>Java Classes and Static Methods </li></ul><ul><li>Data Types, Variables and Constants </li></ul><ul><li>Java Comments and Documents </li></ul><ul><li>Control Flow </li></ul><ul><li>Reading from Keyboard </li></ul><ul><li>Command Line Arguments Processing </li></ul><ul><li>Summary and References </li></ul>
  88. 97. Hello World <ul><li>// HelloWorld.java: Hello World program </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>class HelloWorld </li></ul><ul><li>{ </li></ul><ul><li>public static void main (String args[]) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Hello World”); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  89. 98. Hello World: Java and C <ul><li>// HelloWorld.java : Hello World program </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>class HelloWorld </li></ul><ul><li>{ </li></ul><ul><li>public static void main (String args[]) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(“Hello World”); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>/* helloworld.c : Hello World program */ #define <stdio.h> void main(int argc, char *argv[]) { printf(“Hello World”); } S1: S2: S3: S4: S6:
  90. 99. Program Processing <ul><li>Compilation </li></ul><ul><ul><li># javac HelloWorld.java </li></ul></ul><ul><ul><li>results in HelloWorld.class </li></ul></ul><ul><li>Execution </li></ul><ul><ul><li># java HelloWorld </li></ul></ul><ul><ul><li>Hello World </li></ul></ul>
  91. 100. Closer Look at - Hello World <ul><li>The class has one method – main() </li></ul><ul><ul><ul><li>public static void main(String args[]) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“Hello World”); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><li>Command line input arguments are passed in the String array args[] </li></ul><ul><ul><li>e.g java HelloWorld John Jane </li></ul></ul><ul><ul><li>args[0] – John args[1] – Jane </li></ul></ul>
  92. 101. Closer Look at - Hello World <ul><li>import java.lang.*; </li></ul><ul><ul><li>Java allows grouping of related classes into a package. </li></ul></ul><ul><ul><li>It allows different companies can develop different packages, may even have same class and method names, but they differ by package name: </li></ul></ul><ul><ul><ul><li>ibm.mathlib.* </li></ul></ul></ul><ul><ul><ul><li>microsoft.mathlib.* </li></ul></ul></ul><ul><ul><ul><li>Helps in managing name clash problems. </li></ul></ul></ul><ul><ul><li>Think of this package as library. </li></ul></ul><ul><ul><li>“ import” statement somewhat serves similar purpose as C’s #include </li></ul></ul><ul><ul><li>If you don’t add import statement, then you need utilise fully qualified name. </li></ul></ul><ul><ul><ul><li>ibm.mathlib.sin() </li></ul></ul></ul><ul><ul><ul><li>If you do “import ibm.*” then you can use mathlib.sin() instead. </li></ul></ul></ul>
  93. 102. Java imports java.lang.* by default <ul><li>So, You don't need to import java.lang.* </li></ul><ul><li>That means, you can invoke services of java’s “lang” package classes/entities, you don’t need to use fully qualified names. </li></ul><ul><ul><li>We used System.out.println() instead of </li></ul></ul><ul><ul><ul><li>java.lang. System.out.println() </li></ul></ul></ul>
  94. 103. public static void main (String args[]) <ul><li>public : The keyword “public” is an access specifier that declares the main method as unprotected. </li></ul><ul><li>static : It says this method belongs to the entire class and NOT a part of any objects of class. The main must always be declared static since the interpreter users this before any objects are created. </li></ul><ul><li>void : The type modifier that states that main does not return any value. </li></ul>
  95. 104. System.out.println(“Hello World”); <ul><li>java.lang.* </li></ul><ul><ul><li>All classes/items in “lang” package of java package. </li></ul></ul><ul><li>System is really the java.lang.System class. </li></ul><ul><li>This class has a public static field called out which is an instance of the java.io.PrintStream class. So when we write System.out.println(), we are really invoking the println() method of the “out” field of the java.lang.System class. </li></ul>
  96. 105. Java Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class { }
  97. 106. More Java: Classes and static methods <ul><li>// SquareRoot.java: compute square root of number </li></ul><ul><li>import java.lang. Math ; </li></ul><ul><li>class SquareRoot </li></ul><ul><li>{ </li></ul><ul><li>public static void main (String args []) </li></ul><ul><li>{ </li></ul><ul><li>double x = 4; </li></ul><ul><li>double y; </li></ul><ul><li>y = Math . sqrt (x); </li></ul><ul><li>System.out.println(&quot;y= &quot;+y); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  98. 107. Basic Data Types <ul><li>Types </li></ul><ul><ul><li>boolean either true or false </li></ul></ul><ul><ul><li>char 16 bit Unicode 1.1 </li></ul></ul><ul><ul><li>byte 8-bit integer (signed) </li></ul></ul><ul><ul><li>short 16-bit integer (signed) </li></ul></ul><ul><ul><li>int 32-bit integer (signed) </li></ul></ul><ul><ul><li>long 64-bit integer (singed) </li></ul></ul><ul><ul><li>float 32-bit floating point (IEEE 754-1985) </li></ul></ul><ul><ul><li>double 64-bit floating point (IEEE 754-1985) </li></ul></ul><ul><li>String (class for manipulating strings) </li></ul><ul><li>Java uses Unicode to represent characters internally </li></ul>
  99. 108. Variables <ul><li>Local Variables are declared within the block of code </li></ul><ul><li>Variable has a type preceding the name </li></ul><ul><li>Initial value is set by initialization expressions. </li></ul><ul><li> type variableName = initialValue; </li></ul><ul><li>e.g. int x = 1 ; </li></ul><ul><li>Variables can be defined just before their usage (unlike C) </li></ul><ul><ul><li>for( int i = 0; i < 10; i++) </li></ul></ul>
  100. 109. Constants <ul><li>Constants are similar to variables except that they hold a fixed value. They are also called “READ” only variables. </li></ul><ul><li>Constants are declared with the reserved word “ final ”. </li></ul><ul><ul><li>final int MAX_LENGTH = 420; </li></ul></ul><ul><ul><li>final double PI = 3.1428; </li></ul></ul><ul><li>By convention upper case letters are used for defining constants. </li></ul>
  101. 110. Declaring Constants - example <ul><ul><li>class CircleArea </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>public static void main(String args[]) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>final double PI = 3.1428; </li></ul></ul><ul><ul><li>double radius = 5.5; // in cms </li></ul></ul><ul><ul><li>double area; </li></ul></ul><ul><ul><li>area = PI * radius * radius; </li></ul></ul><ul><ul><li>System.out.println(&quot;Circle Radius = &quot;+radius+&quot; Area=&quot;+area); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  102. 111. Control Flow <ul><li>Control Flow Statements in JAVA </li></ul><ul><ul><li>while loop </li></ul></ul><ul><ul><li>for loop </li></ul></ul><ul><ul><li>do-while loop </li></ul></ul><ul><ul><li>if-else statement </li></ul></ul><ul><ul><li>switch statement </li></ul></ul><ul><li>JAVA does not support a goto statement </li></ul>
  103. 112. <ul><li>while loop </li></ul><ul><ul><ul><li>while (squared <= MAX) { </li></ul></ul></ul><ul><ul><ul><li>squared = lo * lo; // Calculate square </li></ul></ul></ul><ul><ul><ul><li>System.out.println(squared); </li></ul></ul></ul><ul><ul><ul><li>lo = lo + 1; /* Compute the new lo value */ </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Control Flow - Examples
  104. 113. Control Flow - Examples <ul><li>for loop </li></ul><ul><ul><ul><li>for (int i = 1; i < MAX; i++) { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(i); // prints 1 2 3 4 5 … </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  105. 114. <ul><li>do-while loop </li></ul><ul><ul><ul><li>do { </li></ul></ul></ul><ul><ul><ul><li>squared = lo * lo; // Calculate square </li></ul></ul></ul><ul><ul><ul><li>System.out.println(squared); </li></ul></ul></ul><ul><ul><ul><li>lo = lo + 1; /* Compute the new lo value */ </li></ul></ul></ul><ul><ul><ul><li>} while (squared <= MAX); </li></ul></ul></ul>Control Flow - Examples
  106. 115. <ul><li>if-else loop </li></ul><ul><ul><ul><li>if ( i < 10) { </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“i is less than 10” ); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>else { </li></ul></ul></ul><ul><ul><ul><li> System.out.println(“i is greater than or equal to 10”); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Control Flow - Examples
  107. 116. Control Flow - Examples <ul><li>switch statement </li></ul><ul><ul><ul><li>switch (c) { </li></ul></ul></ul><ul><ul><ul><li>case ‘a’: </li></ul></ul></ul><ul><ul><ul><li> System.out.println (“ The character is ‘a’” ); </li></ul></ul></ul><ul><ul><ul><li> break; </li></ul></ul></ul><ul><ul><ul><li>case ‘b’; </li></ul></ul></ul><ul><ul><ul><li>System.out.println (“ The character is ‘b’” ); </li></ul></ul></ul><ul><ul><ul><li> break; </li></ul></ul></ul><ul><ul><ul><li>default; </li></ul></ul></ul><ul><ul><ul><li>System.out.println (“ The character is not ‘a’ or ‘b’” ); </li></ul></ul></ul><ul><ul><ul><li> break; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  108. 117. Reading from Keyboard <ul><li>As Java does not support a simple APIs for Keyboard Input, we created a class called &quot;Keyboard&quot;, which you can use in your program. The Keyboard class facilitates keyboard input by abstracting details about input parsing, conversions, and exception handling. This class reads from standard input (keyboard) and converts the characters into an appropriate type based on the method you call. Some methods you can use are: </li></ul><ul><ul><li>Keyboard.readString() </li></ul></ul><ul><ul><li>Keyboard.readWord() </li></ul></ul><ul><ul><li>Keyboard.readChar() </li></ul></ul><ul><ul><li>Keyboard.readBoolean() </li></ul></ul><ul><ul><li>Keyboard.readInt() </li></ul></ul><ul><ul><li>Keyboard.readLong() </li></ul></ul><ul><ul><li>Keyboard.readFloat() </li></ul></ul><ul><ul><li>Keyboard.readDouble() </li></ul></ul>
  109. 118. Keyboard class Usage Example <ul><li>Simply copy the Keyboard.java file from: http://www.cs.mu.oz.au/254/Keyboard/keyboard.html into your program directory and access its methods as if they are standard methods. The Java complier will link them automatically. </li></ul><ul><li>An Example Program: </li></ul><ul><ul><li>// A class to execute one or more Keyboard methods </li></ul></ul><ul><ul><li>class Test </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>public static void main(String[] args) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>System.out.print(&quot;Please enter a string: &quot;); </li></ul></ul><ul><ul><li>String str = Keyboard.readString(); </li></ul></ul><ul><ul><li>System.out.println(&quot;String = &quot; + str); </li></ul></ul><ul><ul><li> </li></ul></ul><ul><ul><li>System.out.print(&quot;Please enter an int number: &quot;); </li></ul></ul><ul><ul><li>int numInt = Keyboard.readInt(); </li></ul></ul><ul><ul><li>System.out.println(&quot;int = &quot; + numInt); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  110. 119. Command Line Arguments <ul><li>Command line arguments provide one of the ways for supplying input data at the time of execution instead of including them in the program. They are supplied as parameters to the main() method: </li></ul><ul><ul><ul><li>public static void main(String args[]) </li></ul></ul></ul><ul><li>“ args” is declared of an array of strings (aka string objects). </li></ul><ul><ul><li>args[0] is the first parameter, args[1] is the 2 nd argument and so on </li></ul></ul><ul><li>The number of arguments passed identified by: </li></ul><ul><ul><li>args.length </li></ul></ul><ul><ul><li>E.g. count = args.length; </li></ul></ul><ul><li>Example Invocation and values: </li></ul><ul><ul><li>java MyProgram hello melbourne </li></ul></ul><ul><ul><li>args.length will be 2 </li></ul></ul><ul><ul><li>args[0] will be “hello” and args[1] will be “melborune” </li></ul></ul>
  111. 120. Printing command line arguments <ul><li>// ComLineTest.java: testing command line arguments </li></ul><ul><li>class ComLineTest </li></ul><ul><li>{ </li></ul><ul><li>public static void main(String args[]) </li></ul><ul><li>{ </li></ul><ul><li>int count, i = 0; </li></ul><ul><li>String myString; </li></ul><ul><li>count = args.length; </li></ul><ul><li>System.out.println(&quot;Number of Arguments = &quot;+count); </li></ul><ul><li>while( i < count ) </li></ul><ul><li>{ </li></ul><ul><li>myString = args[i]; </li></ul><ul><li>i = i + 1; </li></ul><ul><li>System.out.println(i + &quot; : &quot; + &quot;Java is &quot;+myString+ &quot; !&quot;); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>+ concatenates strings or numbers
  112. 121. Execution Example <ul><li>java ComLineTest Simple Object_Oriented Distributed Robust Secure Portable Multithread Dynamic </li></ul><ul><li>The output of program will be: </li></ul><ul><ul><li>Number of Arguments = 8 </li></ul></ul><ul><ul><li>1 : Java is Simple ! </li></ul></ul><ul><ul><li>2 : Java is Object_Oriented ! </li></ul></ul><ul><ul><li>3 : Java is Distributed ! </li></ul></ul><ul><ul><li>4 : Java is Robust ! </li></ul></ul><ul><ul><li>5 : Java is Secure ! </li></ul></ul><ul><ul><li>6 : Java is Portable ! </li></ul></ul><ul><ul><li>7 : Java is Multithread ! </li></ul></ul><ul><ul><li>8 : Java is Dynamic ! </li></ul></ul>
  113. 122. Summary <ul><li>We discussed meaning of statements in “hello world” program </li></ul><ul><li>We discussed various basic constructs and syntax. </li></ul><ul><li>Apart from OO specific items, most keywords or constructs in Java have similar meaning and usage style as C. </li></ul>
  114. 123. Introduction to Computer Science II COSC 1320/6305 Lecture 3: Console Input and Output (Chapter 2)
  115. 124. 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  116. 126. System.out.println for console output <ul><li>System.out is an object that is part of the Java language </li></ul><ul><li>println is a method invoked by the System.out object that can be used for console output </li></ul><ul><ul><li>The data to be output is given as an argument in parentheses </li></ul></ul><ul><ul><li>A plus sign is used to connect more than one item </li></ul></ul><ul><ul><li>Every invocation of println ends a line of output </li></ul></ul><ul><ul><ul><li>System.out.println(&quot;The answer is &quot; + 42); </li></ul></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  117. 128. println Versus print <ul><li>Another method that can be invoked by the System.out object is print </li></ul><ul><li>The print method is like println , except that it does not end a line </li></ul><ul><ul><li>With println , the next output goes on a new line </li></ul></ul><ul><ul><li>With print , the next output goes on the same line </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  118. 130. Formatting Output with printf <ul><li>Starting with version 5.0, Java includes a method named printf that can be used to produce output in a specific format </li></ul><ul><li>The Java method printf is similar to the print method </li></ul><ul><ul><li>Like print , printf does not advance the output to the next line </li></ul></ul><ul><li>System.out.printf can have any number of arguments </li></ul><ul><ul><li>The first argument is always a format string that contains one or more format specifiers for the remaining arguments </li></ul></ul><ul><ul><li>All the arguments except the first are values to be output to the screen </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  119. 131. printf Format Specifier <ul><li>The code </li></ul><ul><ul><li>double price = 19.8; </li></ul></ul><ul><ul><li>System.out.print(&quot;$&quot;); </li></ul></ul><ul><ul><li>System.out.printf(&quot;%6.2f&quot;, price); </li></ul></ul><ul><ul><li>System.out.println(&quot; each&quot;); </li></ul></ul><ul><li>will output the line </li></ul><ul><ul><li>$ 19.80 each </li></ul></ul><ul><li>The format string &quot;%6.2f&quot; indicates the following: </li></ul><ul><ul><li>End any text to be output and start the format specifier ( % ) </li></ul></ul><ul><ul><li>Display up to 6 right-justified characters, pad fewer than six characters on the left with blank spaces (i.e., field width is 6 ) </li></ul></ul><ul><ul><li>Display exactly 2 digits after the decimal point ( .2 ) </li></ul></ul><ul><ul><li>Display a floating point number, and end the format specifier (i.e., the conversion character is f ) </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  120. 132. Right and Left Justification in printf <ul><li>The code </li></ul><ul><ul><ul><li>double value = 12.123; </li></ul></ul></ul><ul><ul><ul><li>System.out.printf(&quot;Start%8.2fEnd&quot;, value); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(); </li></ul></ul></ul><ul><ul><ul><li>System.out.printf(&quot;Start%-8.2fEnd&quot;, value); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(); </li></ul></ul></ul><ul><ul><li>will output the following </li></ul></ul><ul><ul><ul><li>Start 12.12End </li></ul></ul></ul><ul><ul><ul><li>Start12.12 End </li></ul></ul></ul><ul><li>The format string &quot;Start%8.2fEnd&quot; produces output that is right justified with three blank spaces before the 12.12 </li></ul><ul><li>The format string &quot;Start%-8.2fEnd&quot; produces output that is left justified with three blank spaces after the 12.12 </li></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  121. 133. Multiple arguments with printf <ul><li>The following code contains a printf statement having three arguments </li></ul><ul><ul><li>The code </li></ul></ul><ul><ul><ul><li>double price = 19.8; </li></ul></ul></ul><ul><ul><ul><li>String name = &quot;magic apple&quot;; </li></ul></ul></ul><ul><ul><ul><li>System.out.printf(&quot;$%6.2f for each %s.&quot;, </li></ul></ul></ul><ul><ul><ul><li>price, name); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Wow&quot;); </li></ul></ul></ul><ul><ul><li>will output </li></ul></ul><ul><ul><ul><li>$ 19.80 for each magic apple. </li></ul></ul></ul><ul><ul><ul><li>Wow </li></ul></ul></ul><ul><ul><li>Note that the first argument is a format string containing two format specifiers ( %6.2f and %s ) </li></ul></ul><ul><ul><li>These format specifiers match up with the two arguments that follow ( price and name ) </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  122. 134. Line Breaks with printf <ul><li>Line breaks can be included in a format string using %n </li></ul><ul><li>The code </li></ul><ul><ul><ul><li>double price = 19.8; </li></ul></ul></ul><ul><ul><ul><li>String name = &quot;magic apple&quot;; </li></ul></ul></ul><ul><ul><ul><li>System.outprintf(&quot;$%6.2f for each %s.%n&quot;, price, name); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(&quot;Wow&quot;); </li></ul></ul></ul><ul><li>will output </li></ul><ul><ul><ul><li>$ 19.80 for each magic apple. </li></ul></ul></ul><ul><ul><ul><li>Wow </li></ul></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  123. 135. Format Specifiers for System.out.printf 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  124. 136. The printf Method (Part 1 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  125. 137. The printf Method (Part 2 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  126. 138. The printf Method (Part 3 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  127. 139. Formatting Money Amounts with printf <ul><li>A good format specifier for outputting an amount of money stored as a double type is %.2f </li></ul><ul><li>It says to include exactly two digits after the decimal point and to use the smallest field width that the value will fit into: </li></ul><ul><ul><li>double price = 19.99; </li></ul></ul><ul><ul><li>System.out.printf(&quot;The price is $ %.2 f each.&quot;) </li></ul></ul><ul><li>produces the output: </li></ul><ul><ul><li>The price is $19.99 each. </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  128. 140. Legacy Code <ul><li>Code that is &quot;old fashioned&quot; but too expensive to replace is called legacy code </li></ul><ul><li>Sometimes legacy code is translated into a more modern language </li></ul><ul><li>The Java method printf is just like a C language function of the same name </li></ul><ul><li>This was done intentionally to make it easier to translate C code into Java </li></ul>2-
  129. 141. Money Formats <ul><li>Using the NumberFormat class enables a program to output amounts of money using the appropriate format </li></ul><ul><ul><li>The NumberFormat class must first be imported in order to use it </li></ul></ul><ul><ul><ul><li>import java.text.NumberFormat </li></ul></ul></ul><ul><ul><li>An object of NumberFormat must then be created using the getCurrencyInstance() method </li></ul></ul><ul><ul><li>The format method takes a floating-point number as an argument and returns a String value representation of the number in the local currency </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  130. 142. Money Formats <ul><li>import java.text.NumberFormat; </li></ul><ul><li>public class CurrencyFormatDemo </li></ul><ul><li>{ </li></ul><ul><li>public static void main(String[] args) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;Default location:&quot;); </li></ul><ul><li>NumberFormat moneyFormater = </li></ul><ul><li>NumberFormat.getCurrencyInstance(); </li></ul><ul><li>System.out.println(moneyFormater.format(19.8)); </li></ul><ul><li>System.out.println(moneyFormater.format(19.81111)); </li></ul><ul><li>System.out.println(moneyFormater.format(19.89999)); </li></ul><ul><li>System.out.println(moneyFormater.format(19)); </li></ul><ul><li>System.out.println(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  131. 143. Money Formats <ul><li>Output of the previous program </li></ul><ul><ul><li>Default location: </li></ul></ul><ul><ul><li>$19.80 </li></ul></ul><ul><ul><li>$19.81 </li></ul></ul><ul><ul><li>$19.90 </li></ul></ul><ul><ul><li>$19.00 </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  132. 144. Specifying Locale <ul><li>Invoking the getCurrencyInstance() method without any arguments produces an object that will format numbers according to the default location </li></ul><ul><li>In contrast, the location can be explicitly specified by providing a location from the Locale class as an argument to the getCurrencyInstance() method </li></ul><ul><ul><li>When doing so, the Locale class must first be imported </li></ul></ul><ul><ul><ul><li>import java.util.Locale; </li></ul></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  133. 145. Specifiying Locale <ul><li>import java.text.NumberFormat; </li></ul><ul><li>import java.util.Locale; </li></ul><ul><li>public class CurrencyFormatDemo </li></ul><ul><li>{ </li></ul><ul><li>public static void main(String[] args) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;US as location:&quot;); </li></ul><ul><li>NumberFormat moneyFormater2 = </li></ul><ul><li>NumberFormat.getCurrencyInstance(Locale.US); </li></ul><ul><li>System.out.println(moneyFormater2.format(19.8)); </li></ul><ul><li>System.out.println(moneyFormater2.format(19.81111)); </li></ul><ul><li>System.out.println(moneyFormater2.format(19.89999)); </li></ul><ul><li>System.out.println(moneyFormater2.format(19)); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  134. 146. Specifying Locale <ul><li>Output of the previous program </li></ul><ul><ul><li>US as location: </li></ul></ul><ul><ul><li>$19.80 </li></ul></ul><ul><ul><li>$19.81 </li></ul></ul><ul><ul><li>$19.90 </li></ul></ul><ul><ul><li>$19.00 </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  135. 147. Locale Constants for Currencies of Different Countries 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  136. 148. Importing Packages and Classes <ul><li>Libraries in Java are called packages </li></ul><ul><ul><li>A package is a collection of classes that is stored in a manner that makes it easily accessible to any program </li></ul></ul><ul><ul><li>In order to use a class that belongs to a package, the class must be brought into a program using an import statement </li></ul></ul><ul><ul><li>Classes found in the package java.lang are imported automatically into every Java program </li></ul></ul><ul><ul><ul><li>import java.text.NumberFormat; </li></ul></ul></ul><ul><ul><li>// import theNumberFormat class only </li></ul></ul><ul><ul><ul><li>import java.text.*; </li></ul></ul></ul><ul><ul><li>//import all the classes in package java.text </li></ul></ul>
  137. 149. The DecimalFormat Class <ul><li>Using the DecimalFormat class enables a program to format numbers in a variety of ways </li></ul><ul><ul><li>The DecimalFormat class must first be imported </li></ul></ul><ul><ul><li>A DecimalFormat object is associated with a pattern when it is created using the new command </li></ul></ul><ul><ul><li>The object can then be used with the method format to create strings that satisfy the format </li></ul></ul><ul><ul><li>An object of the class DecimalFormat has a number of different methods that can be used to produce numeral strings in various formats </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  138. 150. The DecimalFormat Class (Part 1 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  139. 151. The DecimalFormat Class (Part 2 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  140. 152. The DecimalFormat Class (Part 3 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  141. 154. Console Input Using the Scanner Class <ul><li>Starting with version 5.0, Java includes a class for doing simple keyboard input named the Scanner class </li></ul><ul><li>In order to use the Scanner class, a program must include the following line near the start of the file: </li></ul><ul><ul><li>import java.util.Scanner </li></ul></ul><ul><li>This statement tells Java to </li></ul><ul><ul><li>Make the Scanner class available to the program </li></ul></ul><ul><ul><li>Find the Scanner class in a library of classes (i.e., Java package ) named java.util </li></ul></ul>2-
  142. 155. Console Input Using the Scanner Class <ul><li>The following line creates an object of the class Scanner and names the object keyboard : </li></ul><ul><ul><li>Scanner keyboard = new Scanner(System.in); </li></ul></ul><ul><li>Although a name like keyboard is often used, a Scanner object can be given any name </li></ul><ul><ul><li>For example, in the following code the Scanner object is named </li></ul></ul><ul><ul><li>Scanner scannerObject = new Scanner(System.in); </li></ul></ul><ul><li>Once a Scanner object has been created, a program can then use that object to perform keyboard input using methods of the Scanner class </li></ul>2-
  143. 156. Console Input Using the Scanner Class <ul><li>The method nextInt reads one int value typed in at the keyboard and assigns it to a variable: </li></ul><ul><ul><li>int numberOfPods = keyboard . nextInt (); </li></ul></ul><ul><li>The method nextDouble reads one double value typed in at the keyboard and assigns it to a variable: </li></ul><ul><ul><li>double d1 = keyboard . nextDouble (); </li></ul></ul><ul><li>Multiple inputs must be separated by whitespace and read by multiple invocations of the appropriate method </li></ul><ul><ul><li>Whitespace is any string of characters, such as blank spaces, tabs, and line breaks that print out as white space </li></ul></ul>
  144. 157. Console Input Using the Scanner Class <ul><li>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 </li></ul><ul><li>Given the code </li></ul><ul><ul><li>String word1 = keyboard . next (); </li></ul></ul><ul><ul><li>String word2 = keyboard . next (); </li></ul></ul><ul><li>and the input line </li></ul><ul><ul><li>jelly beans </li></ul></ul><ul><li>The value of word1 would be jelly , and the value of word2 would be beans </li></ul>
  145. 158. Console Input Using the Scanner Class <ul><li>The method nextLine reads an entire line of keyboard input </li></ul><ul><li>The code, </li></ul><ul><ul><li>String line = keyboard . nextLine (); </li></ul></ul><ul><li>reads in an entire line and places the string that is read into the variable line </li></ul><ul><li>The end of an input line is indicated by the escape sequence '' </li></ul><ul><ul><li>This is the character input when the Enter key is pressed </li></ul></ul><ul><ul><li>On the screen it is indicated by the ending of one line and the beginning of the next line </li></ul></ul><ul><li>When nextLine reads a line of text, it reads the '' character, so the next reading of input begins on the next line </li></ul><ul><ul><li>However, the '' does not become part of the string value returned (e.g., the string named by the variable line above does not end with the '' character) </li></ul></ul>
  146. 159. Keyboard Input Demonstration (Part 1 of 2) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  147. 160. Keyboard Input Demonstration (Part 2 of 2) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  148. 161. Another Keyboard Input Demonstration (Part 1 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  149. 162. Another Keyboard Input Demonstration (Part 2 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  150. 163. Another Keyboard Input Demonstration (Part 3 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  151. 164. Pitfall: Dealing with the Line Terminator, '' <ul><li>The method nextLine of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off </li></ul><ul><li>This can cause problems when combining it with different methods for reading from the keyboard such as nextInt </li></ul><ul><li>Given the code, </li></ul><ul><ul><li>Scanner keyboard = new Scanner(System.in); </li></ul></ul><ul><ul><li>int n = keyboard .nextInt(); </li></ul></ul><ul><ul><li>String s1 = keyboard .nextLine(); </li></ul></ul><ul><ul><li>String s2 = keyboard .nextLine(); </li></ul></ul><ul><li>and the input, </li></ul><ul><ul><li>2 </li></ul></ul><ul><ul><li>Heads are better than </li></ul></ul><ul><ul><li>1 head. </li></ul></ul><ul><li>what are the values of n , s1 , and s2 ? </li></ul>
  152. 165. Pitfall: Dealing with the Line Terminator, '' <ul><li>Given the code and input on the previous slide </li></ul><ul><ul><li>n will be equal to &quot;2&quot; , </li></ul></ul><ul><ul><li>s1 will be equal to &quot;&quot; , and </li></ul></ul><ul><ul><li>s2 will be equal to &quot;heads are better than“ </li></ul></ul><ul><li>If the following results were desired instead </li></ul><ul><ul><li>n equal to &quot;2&quot; , </li></ul></ul><ul><ul><li>s1 equal to &quot;heads are better than&quot; , and </li></ul></ul><ul><ul><li>s2 equal to &quot;1 head“ </li></ul></ul><ul><li>then an extra invocation of nextLine would be needed to get rid of the end of line character ( '' ) </li></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  153. 166. Methods in the Class Scanner (Part 1 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  154. 167. Methods in the Class Scanner (Part 2 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  155. 168. Methods in the Class Scanner (Part 3 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  156. 169. Programming Tip: Prompt for Input <ul><li>A program should always prompt the user when he or she needs to input some data: </li></ul><ul><ul><li>System.out. println ( </li></ul></ul><ul><ul><li>&quot;Enter the number of pods followed by&quot;); </li></ul></ul><ul><ul><li>System.out. println ( </li></ul></ul><ul><ul><li>&quot;the number of peas in a pod:&quot;); </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  157. 170. Programming Tip: Echo Input <ul><li>Always echo all input that a program receives from the keyboard </li></ul><ul><li>In this way a user can check that he or she has entered the input correctly </li></ul><ul><ul><li>Even though the input is automatically displayed as the user enters it, echoing the input may expose subtle errors (such as entering the letter &quot;O&quot; instead of a zero) </li></ul></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  158. 171. Self-Service Checkout Line (Part 1 of 2) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  159. 172. Self-Service Checkout Line (Part 2 of 2) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  160. 173. The Empty String <ul><li>A string can have any number of characters, including zero characters </li></ul><ul><ul><li>&quot;&quot; is the empty string </li></ul></ul><ul><li>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 </li></ul>2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  161. 174. CLASS Participation B ! (pp. 88)
  162. 175. 13- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  163. 176. 13- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  164. 177. 13- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  165. 178. Other Input Delimiters <ul><li>The delimiters that separate keyboard input can be changed when using the Scanner class </li></ul><ul><li>For example, the following code could be used to create a Scanner object and change the delimiter from whitespace to &quot;##“ </li></ul><ul><ul><li>Scanner keyboard2 = new Scanner(System.in); </li></ul></ul><ul><ul><li>Keyboard2 . useDelimiter (&quot;##&quot;); </li></ul></ul><ul><li>After invocation of the useDelimiter method, &quot;##&quot; and not whitespace will be the only input delimiter for the input object keyboard2 </li></ul>
  166. 179. Changing the Input Delimiter (Part 1 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  167. 180. Changing the Input Delimiter (Part 2 of 3)
  168. 181. Changing the Input Delimiter (Part 3 of 3) 2- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  169. 182. Introduction to Computer Science II COSC 1320/6305 06.06.2011 Lecture 3: Flow Of Control (Chapter 3)
  170. 183. 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  171. 184. Flow of Control <ul><li>As in most programming languages, flow of control in Java refers to its branching and looping mechanisms </li></ul><ul><li>Java has several branching mechanisms: if-else , if , and switch statements </li></ul><ul><li>Java has three types of loop statements: the while , do-while , and for statements </li></ul><ul><li>Most branching and looping statements are controlled by Boolean expressions </li></ul><ul><ul><li>A Boolean expression evaluates to either true or false </li></ul></ul><ul><ul><li>The primitive type boolean may only take the values true or false </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  172. 186. Branching with an if-else Statement <ul><li>An if-else statement chooses between two alternative statements based on the value of a Boolean expression </li></ul><ul><ul><ul><li>if ( Boolean_Expression ) </li></ul></ul></ul><ul><ul><ul><li>Yes_Statement </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>No_Statement </li></ul></ul></ul><ul><ul><li>The Boolean_Expression must be enclosed in parentheses </li></ul></ul><ul><ul><li>If the Boolean_Expression is true , then the Yes_Statement is executed </li></ul></ul><ul><ul><li>If the Boolean_Expression is false, then the No_Statement is executed </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  173. 187. Compound Statements <ul><li>Each Yes_Statement and No_Statement branch of an if-else can be a made up of a single statement or many statements </li></ul><ul><li>Compound Statement : A branch statement that is made up of a list of statements </li></ul><ul><ul><li>A compound statement must always be enclosed in a pair of braces ( { } ) </li></ul></ul><ul><ul><li>A compound statement can be used anywhere that a single statement can be used </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  174. 188. Compound Statements <ul><li>if (myScore > your Score) </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;I win!&quot;); </li></ul><ul><li>wager = wager + 100; </li></ul><ul><li>} </li></ul><ul><li>else </li></ul><ul><li>{ </li></ul><ul><li>System.out.println </li></ul><ul><li>(&quot;I wish these were golf scores.&quot;); </li></ul><ul><li>wager = 0; </li></ul><ul><li>} </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  175. 189. Omitting the else Part <ul><li>The else part may be omitted to obtain what is often called an if statement </li></ul><ul><ul><ul><li>if (Boolean_Expression) </li></ul></ul></ul><ul><ul><ul><li>Action_Statement </li></ul></ul></ul><ul><ul><li>If the Boolean_Expression is true, then the Action_Statement is executed </li></ul></ul><ul><ul><li>The Action_Statement can be a single or compound statement </li></ul></ul><ul><ul><li>Otherwise, nothing happens, and the program goes on to the next statement </li></ul></ul><ul><ul><ul><li>if (weight > ideal) </li></ul></ul></ul><ul><ul><ul><li>calorieIntake = calorieIntake – 500; </li></ul></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  176. 190. Nested Statements <ul><li>if-else statements and if statements both contain smaller statements within them </li></ul><ul><ul><li>For example, single or compound statements </li></ul></ul><ul><li>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 </li></ul><ul><ul><li>Each level of a nested if-else or if should be indented further than the previous level </li></ul></ul><ul><ul><li>Exception: multiway if-else statements </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  177. 191. Multiway if - else Statements <ul><li>The multiway if-else statement is simply a normal if-else statement that nests another if-else statement at every else branch </li></ul><ul><ul><li>It is indented differently from other nested statements </li></ul></ul><ul><ul><li>All of the Boolean_Expressions are aligned with one another, and their corresponding actions are also aligned with one another </li></ul></ul><ul><ul><li>The Boolean_Expressions are evaluated in order until one that evaluates to true is found </li></ul></ul><ul><ul><li>The final else is optional </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  178. 192. Multiway if-else Statement <ul><li>if (Boolean_Expression) </li></ul><ul><li>Statement_1 </li></ul><ul><li>else if (Boolean_Expression) </li></ul><ul><li>Statement_2 </li></ul><ul><li>else if (Boolean_Expression_n) </li></ul><ul><li>Statement_n </li></ul><ul><li>else </li></ul><ul><li>Statement_For_All_Other_Possibilities </li></ul>. . . 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  179. 194. CLASS Participation C ! (pp. 106)
  180. 195. The switch Statement <ul><li>The switch statement is the only other kind of Java statement that implements multiway branching </li></ul><ul><ul><li>When a switch statement is evaluated, one of a number of different branches is executed </li></ul></ul><ul><ul><li>The choice of which branch to execute is determined by a controlling expression enclosed in parentheses after the keyword switch </li></ul></ul><ul><ul><ul><li>The controlling expression must evaluate to a char , int , short , or byte </li></ul></ul></ul>
  181. 196. The switch Statement <ul><li>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 </li></ul><ul><ul><li>Each case label must be of the same type as the controlling expression </li></ul></ul><ul><ul><li>Case labels need not be listed in order or span a complete interval, but each one may appear only once </li></ul></ul><ul><ul><li>Each sequence of statements may be followed by a break statement ( break; ) </li></ul></ul>
  182. 197. The switch Statement <ul><li>There can also be a section labeled default : </li></ul><ul><ul><li>The default section is optional, and is usually last </li></ul></ul><ul><ul><li>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 </li></ul></ul><ul><ul><ul><li>It can be used to output an error message, for example </li></ul></ul></ul><ul><li>When the controlling expression is evaluated, the code for the case label whose value matches the controlling expression is executed </li></ul><ul><ul><li>If no case label matches , then the only statements executed are those following the default label ( if there is one ) </li></ul></ul>
  183. 198. The switch Statement <ul><li>The switch statement ends when it executes a break statement, or when the end of the switch statement is reached </li></ul><ul><ul><li>When the computer executes the statements after a case label, it continues until a break statement is reached </li></ul></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>If the break statement is omitted inadvertently, the compiler will not issue an error message </li></ul></ul>
  184. 199. The switch Statement <ul><li>switch (Controlling_Expression) </li></ul><ul><li>{ </li></ul><ul><li>case Case_Label_1: </li></ul><ul><li>Statement_Sequence_1 </li></ul><ul><li>break; </li></ul><ul><li>case Case_Label_2: </li></ul><ul><li>Statement_Sequence_2 </li></ul><ul><li>break; </li></ul><ul><li>case Case_Label_n: </li></ul><ul><li>Statement_Sequence_n </li></ul><ul><li>break; </li></ul><ul><li>default: </li></ul><ul><li>Default_Statement Sequence </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul>. . .
  185. 200. <ul><li>The conditional operator is a notational variant on certain forms of the if-else statement </li></ul><ul><ul><li>Also called the ternary operator or arithmetic if </li></ul></ul><ul><ul><li>The following examples are equivalent: </li></ul></ul><ul><ul><ul><li>if (n1 > n2) max = n1; </li></ul></ul></ul><ul><ul><ul><li>else max = n2; </li></ul></ul></ul><ul><ul><li>vs. </li></ul></ul><ul><ul><ul><li>max = (n1 > n2) ? n1 : n2; </li></ul></ul></ul><ul><ul><li>The expression to the right of the assignment operator is a conditional operator expression </li></ul></ul><ul><ul><li>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 ) </li></ul></ul>The Conditional Operator 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  186. 201. Boolean Expressions <ul><li>A Boolean expression is an expression that is either true or false </li></ul><ul><li>The simplest Boolean expressions compare the value of two expressions </li></ul><ul><ul><ul><li>time < limit </li></ul></ul></ul><ul><ul><ul><li>yourScore == myScore </li></ul></ul></ul><ul><ul><li>Note that Java uses two equal signs ( == ) to perform equality testing: A single equal sign ( = ) is used only for assignment </li></ul></ul><ul><ul><li>A Boolean expression does not need to be enclosed in parentheses, unless it is used in an if-else statement </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  187. 203. Java Comparison Operators 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  188. 204. Pitfall: Using == with Strings <ul><li>The equality comparison operator ( == ) can correctly test two values of a primitive type </li></ul><ul><li>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 </li></ul><ul><li>In order to test two strings to see if they have equal values, use the method equals , or equalsIgnoreCase </li></ul><ul><ul><ul><li>string1.equals(string2) </li></ul></ul></ul><ul><ul><ul><li>string1.equalsIgnoreCase(string2) </li></ul></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  189. 205. Lexicographic and Alphabetical Order <ul><li>Lexicographic ordering is the same as ASCII ordering, and includes letters, numbers, and other characters </li></ul><ul><ul><li>All uppercase letters are in alphabetic order, and all lowercase letters are in alphabetic order, but all uppercase letters come before lowercase letters </li></ul></ul><ul><ul><li>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 </li></ul></ul><ul><li>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 </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  190. 207. Building Boolean Expressions <ul><li>When two Boolean expressions are combined using the &quot;and&quot; ( && ) operator, the entire expression is true provided both expressions are true </li></ul><ul><ul><li>Otherwise the expression is false </li></ul></ul><ul><li>When two Boolean expressions are combined using the &quot;or&quot; ( || ) operator, the entire expression is true as long as one of the expressions is true </li></ul><ul><ul><li>The expression is false only if both expressions are false </li></ul></ul><ul><li>Any Boolean expression can be negated using the ! operator </li></ul><ul><ul><li>Place the expression in parentheses and place the ! operator in front of it </li></ul></ul><ul><li>Unlike mathematical notation, strings of inequalities must be joined by && </li></ul><ul><ul><li>Use (min < result) && (result < max) rather than min < result < max </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  191. 209. Evaluating Boolean Expressions <ul><li>Even though Boolean expressions are used to control branch and loop statements, Boolean expressions can exist independently as well </li></ul><ul><ul><li>A Boolean variable can be given the value of a Boolean expression by using an assignment statement </li></ul></ul><ul><li>A Boolean expression can be evaluated in the same way that an arithmetic expression is evaluated </li></ul><ul><ul><ul><li>The only difference is that arithmetic expressions produce a number as a result, while Boolean expressions produce either true or false as their result </li></ul></ul></ul><ul><ul><li>boolean madeIt = (time < limit) && (limit < max); </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  192. 211. Truth Tables 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  193. 212. Short-Circuit and Complete Evaluation <ul><li>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 </li></ul><ul><li>This is called short-circuit evaluation or lazy evaluation </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>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 </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  194. 213. Short-Circuit and Complete Evaluation <ul><li>There are times when using short-circuit evaluation can prevent a runtime error </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>Note that reversing the order of the subexpressions will not prevent this </li></ul></ul><ul><ul><li>if ((kids !=0) && ((toys/kids) >=2)) . . . </li></ul></ul><ul><li>Sometimes it is preferable to always evaluate both expressions, i.e., request complete evaluation </li></ul><ul><ul><li>In this case, use the & and | operators instead of && and || </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  195. 214. Precedence and Associativity Rules <ul><li>Boolean and arithmetic expressions need not be fully parenthesized </li></ul><ul><li>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 </li></ul><ul><ul><li>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 </li></ul></ul><ul><ul><li>If two operators have the same precedence, then associativity rules determine which is grouped first </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  196. 215. Precedence and Associativity Rules 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  197. 216. Evaluating Expressions <ul><li>In general, parentheses in an expression help to document the programmer's intent </li></ul><ul><ul><li>Instead of relying on precedence and associativity rules, it is best to include most parentheses, except where the intended meaning is obvious </li></ul></ul><ul><li>Binding : The association of operands with their operators </li></ul><ul><ul><li>A fully parenthesized expression accomplishes binding for all the operators in an expression </li></ul></ul><ul><li>Side Effects : When, in addition to returning a value, an expression changes something, such as the value of a variable </li></ul><ul><ul><li>The assignment , increment , and decrement operators all produce side effects </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  198. 217. Rules for Evaluating Expressions <ul><li>Perform binding </li></ul><ul><ul><li>Determine the equivalent fully parenthesized expression using the precedence and associativity rules </li></ul></ul><ul><li>Proceeding left to right, evaluate whatever subexpressions can be immediately evaluated </li></ul><ul><ul><li>These subexpressions will be operands or method arguments, e.g., numeric constants or variables </li></ul></ul><ul><li>Evaluate each outer operation and method invocation as soon as all of its operands (i.e., arguments) have been evaluated </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  199. 218. Loops <ul><li>Loops in Java are similar to those in other high-level languages </li></ul><ul><li>Java has three types of loop statements: the while , the do-while , and the for statements </li></ul><ul><ul><li>The code that is repeated in a loop is called the body of the loop </li></ul></ul><ul><ul><li>Each repetition of the loop body is called an iteration of the loop </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  200. 220. while statement <ul><li>A while statement is used to repeat a portion of code (i.e., the loop body) based on the evaluation of a Boolean expression </li></ul><ul><ul><li>The Boolean expression is checked before the loop body is executed </li></ul></ul><ul><ul><ul><li>When false, the loop body is not executed at all </li></ul></ul></ul><ul><ul><li>Before the execution of each following iteration of the loop body, the Boolean expression is checked again </li></ul></ul><ul><ul><ul><li>If true, the loop body is executed again </li></ul></ul></ul><ul><ul><ul><li>If false, the loop statement ends </li></ul></ul></ul><ul><ul><li>The loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ( { } ) </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  201. 221. <ul><li>while (Boolean_Expression) </li></ul><ul><li>Statement </li></ul><ul><li>Or </li></ul><ul><li>while (Boolean_Expression) </li></ul><ul><li>{ </li></ul><ul><li>Statement_1 </li></ul><ul><li>Statement_2 </li></ul><ul><li>Statement_Last </li></ul><ul><li>} </li></ul>while Syntax . . . 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  202. 222. do-while Statement <ul><li>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 </li></ul><ul><ul><li>The loop body is executed at least once </li></ul></ul><ul><ul><ul><li>The Boolean expression is checked after the loop body is executed </li></ul></ul></ul><ul><ul><li>The Boolean expression is checked after each iteration of the loop body </li></ul></ul><ul><ul><ul><li>If true, the loop body is executed again </li></ul></ul></ul><ul><ul><ul><li>If false, the loop statement ends </li></ul></ul></ul><ul><ul><ul><li>Don't forget to put a semicolon after the Boolean expression </li></ul></ul></ul><ul><ul><li>Like the while statement, the loop body can consist of a single statement, or multiple statements enclosed in a pair of braces ( { } ) </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  203. 223. <ul><li>do </li></ul><ul><li>Statement </li></ul><ul><li>while (Boolean_Expression); </li></ul><ul><li>Or </li></ul><ul><li>do </li></ul><ul><li>{ </li></ul><ul><li>Statement_1 </li></ul><ul><li>Statement_2 </li></ul><ul><li>Statement_Last </li></ul><ul><li>} while (Boolean_Expression); </li></ul>do-while Syntax . . . 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  204. 224. Algorithms and Pseudocode <ul><li>The hard part of solving a problem with a computer program is not dealing with the syntax rules of a programming language </li></ul><ul><li>Rather, coming up with the underlying solution method is the most difficult part </li></ul><ul><li>An algorithm is a set of precise instructions that lead to a solution </li></ul><ul><ul><li>An algorithm is normally written in pseudocode , which is a mixture of programming language and a human language, like English </li></ul></ul><ul><ul><li>Pseudocode must be precise and clear enough so that a good programmer can convert it to syntactically correct code </li></ul></ul><ul><ul><li>However, pseudocode is much less rigid than code: One needn't worry about the fine points of syntax or declaring variables, for example </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  205. 226. The for Statement <ul><li>The for statement is most commonly used to step through an integer variable in equal increments </li></ul><ul><li>It begins with the keyword for , followed by three expressions in parentheses that describe what to do with one or more controlling variables </li></ul><ul><ul><li>The first expression tells how the control variable or variables are initialized or declared and initialized before the first iteration </li></ul></ul><ul><ul><li>The second expression determines when the loop should end , based on the evaluation of a Boolean expression before each iteration </li></ul></ul><ul><ul><li>The third expression tells how the control variable or variables are updated after each iteration of the loop body </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  206. 227. The for Statement Syntax <ul><li>for (Initializing; Boolean_Expression; Update) </li></ul><ul><li>Body </li></ul><ul><li>The Body may consist of a single statement or a list of statements enclosed in a pair of braces ( { } ) </li></ul><ul><li>Note that the three control expressions are separated by two, not three, semicolons </li></ul><ul><li>Note that there is no semicolon after the closing parenthesis at the beginning of the loop </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  207. 228. Semantics of the for Statement 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  208. 229. for Statement Syntax and Alternate Semantics 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  209. 230. for Statement Syntax and Alternate Semantics 3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  210. 231. The Comma in for Statements <ul><li>A for loop can contain multiple initialization actions separated with commas </li></ul><ul><ul><li>Caution must be used when combining a declaration with multiple actions </li></ul></ul><ul><ul><li>It is illegal to combine multiple type declarations with multiple actions, for example </li></ul></ul><ul><ul><li>To avoid possible problems, it is best to declare all variables outside the for statement </li></ul></ul><ul><li>A for loop can contain multiple update actions, separated with commas, also </li></ul><ul><ul><li>It is even possible to eliminate the loop body in this way </li></ul></ul><ul><li>However, a for loop can contain only one Boolean expression to test for ending the loop </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  211. 232. Infinite Loops <ul><li>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 </li></ul><ul><li>If the Boolean expression remains true, then the loop will run forever, resulting in an infinite loop </li></ul><ul><ul><li>Loops that check for equality or inequality ( == or != ) are especially prone to this error and should be avoided if possible </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  212. 233. Nested Loops <ul><li>Loops can be nested , just like other Java structures </li></ul><ul><ul><li>When nested, the inner loop iterates from beginning to end for each single iteration of the outer loop </li></ul></ul><ul><ul><li>int rowNum, columnNum; </li></ul></ul><ul><ul><li>for (rowNum = 1; rowNum <=3; rowNum++) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>for (columnNum = 1; columnNum <=2; </li></ul></ul><ul><ul><li>columnNum++) </li></ul></ul><ul><ul><li>System.out.print(&quot; row &quot; + rowNum + </li></ul></ul><ul><ul><li>&quot; column &quot; + columnNum); </li></ul></ul><ul><ul><li>System.out.println(); </li></ul></ul><ul><ul><li>} </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  213. 234. The break and continue Statements <ul><li>The break statement consists of the keyword break followed by a semicolon </li></ul><ul><ul><li>When executed, the break statement ends the nearest enclosing switch or loop statement </li></ul></ul><ul><li>The continue statement consists of the keyword continue followed by a semicolon </li></ul><ul><ul><li>When executed, the continue statement ends the current loop body iteration of the nearest enclosing loop statement </li></ul></ul><ul><ul><li>Note that in a for loop, the continue statement transfers control to the update expression </li></ul></ul><ul><li>When loop statements are nested, remember that any break or continue statement applies to the innermost, containing loop statement </li></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  214. 235. The Labeled break Statement <ul><li>There is a type of break statement that, when used in nested loops, can end any containing loop, not just the innermost loop </li></ul><ul><li>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: </li></ul><ul><ul><li>break someIdentifier; </li></ul></ul><ul><li>To label a loop, simply precede it with an Identifier and a colon: </li></ul><ul><ul><li>someIdentifier: </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  215. 236. The exit Statement <ul><li>A break statement will end a loop or switch statement, but will not end the program </li></ul><ul><li>The exit statement will immediately end the program as soon as it is invoked: </li></ul><ul><ul><li>System.exit(0); </li></ul></ul><ul><li>The exit statement takes one integer argument </li></ul><ul><ul><li>By tradition, a zero argument is used to indicate a normal ending of the program </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  216. 237. Loop Bugs <ul><li>The two most common kinds of loop errors are unintended infinite loops and off-by-one errors </li></ul><ul><ul><li>An off-by-one error is when a loop repeats the loop body one too many or one too few times </li></ul></ul><ul><ul><ul><li>This usually results from a carelessly designed Boolean test expression </li></ul></ul></ul><ul><ul><li>Use of == in the controlling Boolean expression can lead to an infinite loop or an off-by-one error </li></ul></ul><ul><ul><ul><li>This sort of testing works only for characters and integers, and should never be used for floating-point </li></ul></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  217. 238. Tracing Variables <ul><li>Tracing variables involves watching one or more variables change value while a program is running </li></ul><ul><li>This can make it easier to discover errors in a program and debug them </li></ul><ul><li>Many IDE s ( Integrated Development Environments ) have a built-in utility that allows variables to be traced without making any changes to the program </li></ul><ul><li>Another way to trace variables is to simply insert temporary output statements in a program </li></ul><ul><ul><li>System.out.println(&quot;n = &quot; + n); // Tracing n </li></ul></ul><ul><ul><li>When the error is found and corrected, the trace statements can simply be commented out </li></ul></ul>3- Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
  218. 239. General Debugging Techniques <ul><li>Examine the system as a whole – don’t assume the bug occurs in one particular place </li></ul><ul><li>Try different test cases and check the input values </li></ul><ul><li>Comment out blocks of code to narrow down the offending code </li></ul><ul><li>Check common pitfalls </li></ul><ul><li>Take a break and come back later </li></ul><ul><li>DO NOT make random changes just hoping that the change will fix the problem! <

×