Week 1: Review of Java Programming Basics



Similar documents
Chapter 2 Introduction to Java programming

Chapter 2: Elements of Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Building Java Programs

Building Java Programs

Topic 11 Scanner object, conditional execution

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Comp 248 Introduction to Programming

AP Computer Science Java Subset

Introduction to Java. CS 3: Computer Programming in Java

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Install Java Development Kit (JDK) 1.8

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Pemrograman Dasar. Basic Elements Of Java

Lecture 5: Java Fundamentals III

CS 106 Introduction to Computer Science I

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

java Features Version April 19, 2013 by Thorsten Kracht

Object-Oriented Programming in Java

Chapter 3. Input and output. 3.1 The System class

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Programming and Data Structures with Java and JUnit. Rick Mercer

Java Interview Questions and Answers

Chapter 2 Elementary Programming

Computer Programming I

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

6.1. Example: A Tip Calculator 6-1

Chapter 1 Java Program Design and Development

Building Java Programs

Introduction to Java Lecture Notes. Ryan Dougherty

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Fundamentals of Java Programming

JavaScript: Control Statements I

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Explain the relationship between a class and an object. Which is general and which is specific?

Lecture 1 Introduction to Java

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Some Scanner Class Methods

13 File Output and Input

Basics of Java Programming Input and the Scanner class

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Using Files as Input/Output in Java 5.0 Applications

Java Programming Fundamentals

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Sample CSE8A midterm Multiple Choice (circle one)

Example of a Java program

Moving from CS 61A Scheme to CS 61B Java

Java Basics: Data Types, Variables, and Loops

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Event-Driven Programming

Object Oriented Software Design

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Introduction to Programming

CS 106 Introduction to Computer Science I

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Programming in Java Course Technology, a part of Cengage Learning.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

D06 PROGRAMMING with JAVA

ECE 122. Engineering Problem Solving with Java

Variables, Constants, and Data Types

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Basic Programming and PC Skills: Basic Programming and PC Skills:

Chapter 5 Functions. Introducing Functions

Quick Introduction to Java

Sources: On the Web: Slides will be available on:

CS 111 Classes I 1. Software Organization View to this point:

CS506 Web Design and Development Solved Online Quiz No. 01

Chapter 2 Basics of Scanning and Conventional Programming in Java

J a v a Quiz (Unit 3, Test 0 Practice)

Object Oriented Software Design

Course Intro Instructor Intro Java Intro, Continued

AP Computer Science Static Methods, Strings, User Input

PL / SQL Basics. Chapter 3

Arrays. Introduction. Chapter 7

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

An Overview of Java. overview-1

CS106A, Stanford Handout #38. Strings and Chars

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

The following program is aiming to extract from a simple text file an analysis of the content such as:

Building a Multi-Threaded Web Server

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

AP Computer Science File Input with Scanner

Computer Programming Tutorial

More on Objects and Classes

Crash Course in Java

Transcription:

Week 1: Review of Java Programming Basics Sources: Chapter 2 in Supplementary Book (Murach s Java Programming) Appendix A in Textbook (Carrano) Slide 1

Outline Objectives A simple Java Program Data-types Control Structures Slide 2

Objectives Applied Given the specifications for an application that requires only the language elements presented in this chapter, write, test, and debug the application. Given the Java code for an application that uses any of the language elements presented in this chapter, explain what each statement in the application does. Given the name of a package and a class, look it up in the documentation for the Java API. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 3

Objectives (cont.) Knowledge Name two types of comments that are provided by Java and explain how to code them. Given a list of names, identify the valid identifiers for Java classes and variables. Given a list of names, identify the ones that follow the naming recommendations for classes presented in this chapter. Given a list of names, identify the ones that follow the naming recommendations for variables presented in this chapter. Describe the difference between a main method and other methods. Name three things you can assign to a numeric variable. Distinguish between the int and double data types. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 4

Objectives (cont.) Explain what happens when an arithmetic expression uses both int and double values. Name three things you can assign to a String variable. Explain what an escape sequence is and when you would use one. Explain what a static method is and how it differs from other methods. Explain what importing a class means and when you typically do that. Explain what the System.out object can be used for. Explain what a Scanner object can be used for. Explain what a Boolean expression is and when you might use one. Explain how an if/else statement works and what it allows you to do. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 5

Objectives (cont.) Explain what it means for a variable to have block scope. Explain how a while loop works and what it allows you to do. Describe the difference between testing an application and debugging an application. Describe the difference between a compile-time error, a runtime error, and a logical error. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 6

Outline Objectives A simple Java Program Comments, identifiers, keywords Specifying a class with a main method, Data-types Control Structures Slide 7

A sample application import java.util.scanner; public class InvoiceApp { public static void main(string[] args) { // display a welcome message System.out.println("Welcome to Invoice Calculator"); // get the input from the user Scanner sc = new Scanner(System.in); System.out.print("Enter subtotal: "); double subtotal = sc.nextdouble(); // calculate the discount amount and total double discountpercent =.2; double discountamount = subtotal * discountpercent; double invoicetotal = subtotal - discountamount; // format and display the result String message = "Discount percent: " + discountpercent + "\n" + } } "Discount amount: " + discountamount + "\n" + "Invoice total: " + invoicetotal + "\n"; System.out.println(message); Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 8

A block comment /* * Author: J. Murach * Purpose: This program uses the console to get a subtotal * from the user, and it calculates the discount amount and * total and displays them. */ Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 9

Valid identifiers InvoiceApp $ordertotal i Invoice _ordertotal x InvoiceApp2 input_string TITLE subtotal _get_total MONTHS_PER_YEAR discountpercent $_64_Valid The rules for naming an identifier Start each identifier with a letter, underscore, or dollar sign. Use letters, dollar signs, underscores, or digits for subsequent characters. Use up to 255 characters. Don t use Java keywords. Exercise: Which of the following are not valid identifiers? 1. Point 2. final 3. #students 4. order_total$ Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 10

Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break throw implements short public default try import double static for catch synchronized int new continue finally const long this do transient goto abstract super extends instanceof null Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 11

Classification of keywords Values: true, false, null, void Primitive Data-Types (8): boolean, char, byte, short, int, float, long, double Control Structures : if, else, switch, case, default, for, while, do, break, continue, return, goto Exception Handling throw, try, catch, finally Abstract Data Types package, import class, interface, extends, implements, throws, instanceof, new, this, super private, protected, public, const, final, static, abstract synchronized, volatile, transient native Slide 12

The syntax for declaring a class public private class ClassName { statements } The syntax for declaring a main method public static void main(string[] args) { statements } Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 13

A public class that contains a main method public class InvoiceApp // declare the class { // begin the class public static void main(string[] args) { System.out.println( "Welcome to the Invoice Total Calculator"); } } // end the class The same class with different brace placement public class InvoiceApp { // declare and begin the class public static void main(string[] args){ System.out.println( "Welcome to the Invoice Total Calculator"); } } // end the class Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 14

Recommended rules for naming a class Start the name with a capital letter. Use letters and digits only. Follow the other rules for naming an identifier. Recommendations for naming a class Start every word within a class name with an initial cap. Each class name should be a noun or a noun that s preceded by one or more adjectives. Exercise: Which class names follow recommendations? 1. Point_2_Dimensional 2. array 3. Array 4. boolean 5. Boolean Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 15

Outline Objectives A simple Java Program Data-types Primitive data-types numbers, arithmetic Strings Objects, Classes, Packages Control Structures Slide 16

Two of the eight primitive data types int double Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 17

How to declare and initialize a variable in one statement Syntax type variablename = value; Examples int scorecounter = 1; // initialize an integer variable double unitprice = 14.95; // initialize a double variable Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 18

How to code assignment statements int quantity = 0; int maxquantity = 100; // initialize an // integer variable // initialize another // integer variable // two assignment statements quantity = 10; // quantity is now 10 quantity = maxquantity; // quantity is now 100 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 19

Naming recommendations for variables Start variable names with a lowercase letter and capitalize the first letter in all words after the first word. Each variable name should be a noun or a noun preceded by one or more adjectives. Try to use meaningful names that are easy to remember. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 20

The basic operators for arithmetic expressions Operator Name + Addition - Subtraction * Multiplication / Division (or Quotient) % Remainder Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 21

Statements that use simple arithmetic expressions // integer arithmetic int x = 14; int y = 8; int result1 = x + y; // result1 = 22 int result2 = x - y; // result2 = 6 int result3 = x * y; // result3 = 112 int result4 = x / y; // result4 = 1 // double arithmetic double a = 8.5; double b = 3.4; double result5 = a + b; // result5 = 11.9 double result6 = a - b; // result6 = 5.1 double result7= a * b; // result7 = 28.9 double result8 = a / b; // result8 = 2.5 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 22

Statements that increment a counter variable int invoicecount = 0; invoicecount = invoicecount + 1; // invoicecount = 1 invoicecount = invoicecount + 1; // invoicecount = 2 Statements that add amounts to a total double invoiceamount1 = 150.25; double invoiceamount2 = 100.75; double invoicetotal = 0.0; invoicetotal = invoicetotal + invoiceamount1; // invoicetotal = 150.25 invoicetotal = invoicetotal + invoiceamount2; // invoicetotal = 251.00 Statements that mix int and double variables int result9 = invoicetotal / invoicecount ; double result10 = invoicetotal / invoicecount ; // Leading Q? Which statement is legal? Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 23

Type Conversion or Casting Source: (Carrano, Append A, Pages A-9,A-11) Implicit: byte short int long float double int wholerate = 7; double interestrate = wholerate; Explicit int rate = interestrate ; // Illegal int rate = (int) interestrate ; // Value truncated, not rounded! Exercise: What are values of result1 and result2 after: int a = 11; int b = 3; float result1 = a / b ; float c = 11.0; float d = 3.0; float result result2 = c /d ; Slide 24

Math class: Representative Methods Source: (Carrano, Append A, Figure A-2, page A-16) Methods with double valued argument and result: sqrt(x), cbrt(x), hypot(x, y) cos(x), sin(x), tan(x), todegrees(x), toradians(x) ceil(x), floor(x), pow(x, y), exp(x), log(x), log10(x) random(x) Methods for int, long, float or double abs(x) max(x, y) min(x, y) Method int round(float x) long round(double x) Slide 25

Outline Objectives A simple Java Program Data-types Primitive data-types numbers, arithmetic Strings Objects, Classes, Packages Control Structures Slide 26

The syntax for declaring and initializing a string variable String variablename = value; Statements that declare and initialize a string String message1 = "Invalid data entry."; String message2 = ""; String message3 = null; Exercise: Categorize String into one of the following: 1. Primitive data-type 2. Object 3. Class 4. Package Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 27

How to join strings String firstname = "Bob"; // firstname is Bob String lastname = "Smith"; // lastname is Smith String name = firstname + " " + lastname; // name is Bob Smith How to join a string and a number double price = 14.95; String pricestring = "Price: " + price; Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 28

How to append one string to another with the + operator firstname = "Bob"; // firstname is Bob lastname = "Smith"; // lastname is Smith name = firstname + " "; // name is Bob followed by a space name = name + lastname; // name is Bob Smith How to append one string to another with the += operator firstname = "Bob"; // firstname is Bob lastname = "Smith"; // lastname is Smith name = firstname + " "; // name is Bob followed by a space name += lastname; // name is Bob Smith Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 29

Common escape sequences \n \t \r \" \\ Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 30

A string with a new line String "Code: JSPS\nPrice: $49.50" Result Code: JSPS Price: $49.50 A string with tabs and returns String "Joe\tSmith\rKate\tLewis" Result Joe Kate Smith Lewis Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 31

A string with quotation marks String "Type \"x\" to exit" Result Type "x" to exit A string with a backslash String "C:\\java\\files" Result C:\java\files Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 32

More on Strings Source: Textbook (Cerrano) Appendix A (pp. A-38 to A-41) Methods in String class length(), concat(), trim() charat( index ), indexof( substring ) tolowercase(), touppercase() compareto( anotherstring), comparetoignorecase( anotherstring) Related Classes StringBuilder methods of append, delete, insert, replace, setcharat, Scanner to extract a piece (e.g., a number) from a String Discussed in later slides Exercise: Compare and contrast the following pairs: 1. compareto() method vs. == operator 2. String vs. StringBuilder 3. String vs. Scanner Slide 33

Outline Objectives A simple Java Program Data-types Primitive data-types String Objects, Classes, Packages Overview (java.lang.)system, System.in, System.out java.util.scanner, System.in Control Structures Slide 34

How to create an object from a class Syntax ClassName objectname = new ClassName(arguments); Examples Scanner sc = new Scanner(System.in); // creates a Scanner object named sc Date now = new Date(); // creates a Date object named now How to call a method from an object Syntax: objectname.methodname(arguments) Examples double subtotal = sc.nextdouble(); // get a double entry from the console String currentdate = now.tostring(); // convert the date to a string Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 35

How to call a static method from a class Syntax ClassName.methodName(arguments) Examples String sprice = Double.toString(price); // convert a double to a string double total = Double.parseDouble(userEntry); // convert a string to a double Note: Class-name (e.g., Double) prefixed class method-names Leading Question: How does Double relate to primitive data-type double? Double is a wrapper class Provides additional methods for manipulating double valued variables Leading Question: Are wrapper classes available for other primitive data-types (e.g., int)? Where are wrapper classes defined? Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 36

Common packages java.lang classes for String, System, Math, java.text - classes for text, date, java.util Scanner, classes for collections, java.io classes for file read/write java.sql classes for database management systems java.applet, java.awt, java.awt.event, javax.swing 2000+ packages with 20,000+ classes Note: java.lang is implicitly imported in all java programs. It provides Classes: String, StringBuffer, StringBuilder, System with automatically created objects named in, out, Number, Math, and wrapper classes, e.g., Int, Double, Boolean, Throwable, StackTraceElement, Thread, Process, Interfaces: Comparable, Ref.: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/package-summary.html Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 37

The syntax of the import statement import packagename.classname; or import packagename.*; Examples import java.text.numberformat; import java.util.scanner; import java.util.*; import javax.swing.*; Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 38

Outline Objectives A simple Java Program Data-types Primitive data-types String Objects, Classes, Packages Overview (java.lang.)system.out java.util.scanner Control Structures Slide 39

Two methods of the System.out object println(data) // print data followed by a newline print(data) Code that uses the println method System.out.println( "Welcome to the Invoice Total Calculator"); System.out.println("Total: " + total); System.out.println(message); System.out.println(); Code that uses the print method System.out.print("Total: "); System.out.print(total); System.out.print("\n"); // print a blank line Question: What is System.out? It represents the standard output, e.g., screen Question: Where is System.out defined? Recall java.lang is implicitly imported in all java programs It has a class named System With automatically created objects named in, out, Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 40

An application that prints data to the console public class InvoiceApp { public static void main(string[] args) { double subtotal = 100; double discountpercent =.2; // compute discount and invoice total double discountamount = subtotal * discountpercent; double invoicetotal = subtotal - discountamount; // print the data to the console System.out.println("Welcome to the Invoice Calculator"); } } System.out.println(); System.out.println("Subtotal: " + subtotal); System.out.println("Discount percent: " + discountpercent); System.out.println("Discount amount: " + discountamount); System.out.println("Total: " + invoicetotal); Welcome to the Invoice Calculator The console output Subtotal: 100.0 Discount percent: 0.2 Discount amount: 20.0 Total: 80.0 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 41

Outline Objectives A simple Java Program Data-types Primitive data-types Objects, Classes, Packages Overview (java.lang.)system.out java.util.scanner, (java.lang.)system.in Control Structures Slide 42

How to use the Scanner class to create an object With an import statement Scanner sc = new Scanner(System.in); Without an import statement java.util.scanner sc = new java.util.scanner(system.in); Question: Name packages and classes in the import statement. Question: What is System.in? It represents the standard input, e.g., keyboard It allows Scanner object sc to read from standard input Question: Categorize System and System.in (a) System is a package, System.in is a class (b) System is a class and System.in is an object Question: Why didn t we use java.lang.system.in? Where is System.in defined? Recall java.lang is implicitly imported in all java programs It has a class named System With automatically created objects named in, out, Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 43

The documentation for the Scanner class Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 44

The Scanner class java.util.scanner How to create a Scanner object Scanner sc = new Scanner(System.in); Common methods of a Scanner object next() nextint() nextdouble() nextline() How to use the methods of a Scanner object String name = sc.next(); int count = sc.nextint(); double subtotal = sc.nextdouble(); String cityname = sc.nextline(); Note The Scanner class was introduced in version 1.5 of the JDK. Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 45

Code that gets three values from the user Scanner sc = new Scanner(System.in); // create a Scanner object // read a string, a double value, and an int System.out.print("Enter product code: "); String productcode = sc.next(); System.out.print("Enter price: "); double price = sc.nextdouble(); System.out.print("Enter quantity: "); int quantity = sc.nextint(); // perform a calculation and display the result double total = price * quantity; System.out.println(); System.out.println(quantity + " " + productcode + " @ " + price + " = " + total); System.out.println(); The console after the program finishes Enter product code: cshp Enter price: 49.50 Enter quantity: 2 2 cshp @ 49.5 = 99.0 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 46

Code that reads three values from one line // read three int values System.out.print("Enter three integer values: "); int i1 = sc.nextint(); int i2 = sc.nextint(); int i3 = sc.nextint(); // calculate the average and display the result int total = i1 + i2 + i3; int avg = total / 3; System.out.println("Average: " + avg); System.out.println(); The console after the program finishes Enter three integer values: 99 88 92 Average: 93 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 47

More on Scanner Source: Textbook (Cerrano) Appendix A (pp. A-42 to A-44) Other Methods in Scanner class usedelimiter( astring ) - change default of whitespace for next(), nextint(), Example in A.82 (pp. A-42) usedelimiter(, ) Figure A-6 (pp. A-43) shows common delimiters digits ( \d), whitespace ( \s), letter_digit_underscore ( \w), any character (_) Regular expression:?, *, +, {n}, {n,}, Exercise: Specify delimiters to read next element on current line for 1. A Spreadsheet (.csv format) 2. A Unix password file 3. Non-comment parts of a Java program Slide 48

Outline Objectives A simple Java Program Data-types Control Structures Tests Conditionals Loops Slide 49

Examples of conditional expressions discountpercent == 2.3 // equal to a numeric literal subtotal!= 0 // not equal to a numeric literal years > 0 // greater than a numeric literal i < months // less than a numeric variable subtotal >= 500 // greater than or equal to a numeric literal quantity <= reorderpoint // less than or equal to a numeric variable Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 50

Relational operators Operator Name == Equality!= Inequality > Greater Than < Less Than >= Greater Than Or Equal <= Less Than Or Equal Comparison with Mathematics Source: Textbook (Cerrano) Appendix A, Fig. A-3 (pp. A-21) Leading Question? Which data-types do relational operators compare? primitive data types, e.g., int, boolean, float objects, e.g. String, Date, Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 51

Two methods of the String class equals(string) equalsignorecase(string) Examples userentry.equals("y") // equal to a string literal userentry.equalsignorecase("y") // equal to a string literal (!lastname.equals("jones")) // not equal to a string literal code.equalsignorecase(productcode) // equal to another string variable Leading Question? Consider following Strings in Java: String s1 = abcd ; String s2 = abcd ; String s3 = s1; Which of the following are true? (a) s1.equals( s2) (b) s1 == s2 (c ) s1.equals( s3) (d) s1 == s2 (e) s2.equals(s3) (f) s2 == s3 Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 52

Outline Objectives A simple Java Program Data-types Control Structures Tests Conditionals Loops Slide 53

The syntax of the if/else statement if (booleanexpression) {statements} [else if (booleanexpression) {statements}]... [else {statements}] If statements without else if or else clauses With a single statement if (subtotal >= 100) discountpercent =.2; With a block of statements if (subtotal >= 100) { discountpercent =.2; status = "Bulk rate"; } Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 54

An if statement with an else clause if (subtotal >= 100) discountpercent =.2; else discountpercent =.1; An if statement with else if and else clauses if (customertype.equals("t")) discountpercent =.4; else if (customertype.equals("c")) discountpercent =.2; else if (subtotal >= 100) discountpercent =.2; else discountpercent =.1; Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 55

Outline Objectives A simple Java Program Data-types Control Structures Tests Conditionals Loops Slide 56

The syntax of the while loop while (booleanexpression) { statements } A loop that calculates the sum of the numbers 1 through 4 int i = 1; int sum = 0; while (i < 5) { sum = sum + i; i = i + 1; } Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 57

A loop that continues while choice is y or Y String choice = "y"; while (choice.equalsignorecase("y")) { // get the invoice subtotal from the user Scanner sc = new Scanner(System.in); System.out.print("Enter subtotal: "); double subtotal = sc.nextdouble(); // the code that processes the user's entry goes here } // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.next(); System.out.println(); Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 58

Outline Objectives A simple Java Program Data-types Control Structures Tests Conditionals Loops Refined Java Program Slide 59

The code for the Invoice application import java.util.scanner;// Q? Why didn t we import System? public class InvoiceApp { public static void main(string[] args) { System.out.println( "Welcome to the Invoice Calculator"); System.out.println(); // print a blank line Scanner sc = new Scanner(System.in); // perform invoice calculations until choice isn't // equal to "y" or "Y" String choice = "y"; while (choice.equalsignorecase("y")) { // get the invoice subtotal from the user System.out.print("Enter subtotal: "); double subtotal = sc.nextdouble(); Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 60

The code for the application (cont.) // calculate the discount amount and total double discountpercent = 0.0; if (subtotal >= 200) discountpercent =.2; else if (subtotal >= 100) discountpercent =.1; else discountpercent = 0.0; double discountamount = subtotal * discountpercent; double total = subtotal - discountamount; } } } // display the discount amount and total String message = "Discount percent: " + discountpercent + "\n" + "Discount amount: " + discountamount + "\n" + "Invoice total: " + total + "\n"; System.out.println(message); // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.next(); System.out.println(); Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 61

The console input and output for a test run of the Invoice application Welcome to the Invoice Calculator Enter subtotal: 150 Discount percent: 0.1 Discount amount: 15.0 Invoice total: 135.0 Continue? (y/n): Murach s Java Programming, C2 2011, Mike Murach & Associates, Inc. Slide 62

Review Quiz 1.Which of the following can you assign to a String variable? (a.) an empty string (b.) null (c.) a string literal (d.) all of these 2. To refer to a Java class without qualification, you need to import the class unless that class (a.) contains only static methods (b.) is stored in a package (c.) is stored in a package that has already been imported 3. You can use a Scanner object to (a.) get the next token in an input line (b.) display a prompt on the console, (c.) display a blank line on a console (d.) check your Java code for exceptions 4. You can use relational operators (e.g., ==) to (a.) compare String variables (b.) compare numeric variable (c.) both a and b (d.) neither a nor b 5. How many times will the while loop that follows be executed if months has a value of 5? int i = 1; double v = 100; while (i < months) { v = v * (1 + i); i = i+1; } (a.) 0 (b.) 4 (c.) 5 (d.) 6 6. Which two keywords should always be used on the declaration of the main method? (a.) private and static (b.) public and static (c.) private and int (d.) public and static 7. Which package is automatically available to all Java programs? (a.) java.lang (b.) java.util (c.) java.text (d.) java.basic 8. What happens when you use both integer and double values in an arithmetic expression? (a.) an exception occurs (b.) the integer values are cast to double values (c.) the double values are cast to integer values (d.) all values are cast to the type of the result variable Slide 63