Your SlideShare is downloading. ×
0
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Lecture 3 java basics
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Lecture 3 java basics

2,001

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,001
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
284
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

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

×