Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Chapter 2 - Introduction to Java Applications Outline 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 Introduction A First Program in Java: Printing a Line of Text Modifying Our First Java Program Displaying Text in a Dialog Box Another Java Application: Adding Integers Memory Concepts Arithmetic Decision Making: Equality and Relational Operators 2003 Prentice Hall, Inc. All rights reserved. 2 2.1 Introduction • In this chapter – Introduce examples to illustrate features of Java – Simple java programs • • • • • displaying messages geting information from the user performing aritmetic and logical opperations primitive types in java illiustrate decision making 2003 Prentice Hall, Inc. All rights reserved. 3 2.2 A First Program in Java: Printing a Line of Text • Application – Program that executes using the java interpreter • Sample program – Show program, then analyze each line 2003 Prentice Hall, Inc. All rights reserved. 4 Outline 1 2 3 4 5 6 7 8 9 10 11 12 13 // Fig. 2.1: Welcome1.java // Text-printing program. Welcome1.java public class Welcome1 { // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome to Java Programming!" ); } // end method main } // end class Welcome1 Welcome to Java Programming! Program Output 2003 Prentice Hall, Inc. All rights reserved. 5 2.2 1 A First Program in Java: Printing a Line of Text // Fig. 2.1: Welcome1.java – Comments start with: // end of line comment • Comments ignored during program execution • Document and describe code • Provides code readability – Traditional comments: /* ... */ /* This is a traditional comment. It can be split over many lines */ 2 // Text-printing program. – Another line of comments – Note: line numbers not part of program, added for reference 2003 Prentice Hall, Inc. All rights reserved. 6 2.2 A First Program in Java: Printing a Line of Text • javadoc comments – delimited by /** end */ – all text between the delimiter is ignored as in treditional comments – the javadoc utility program • reads javadoc comments and prepare a documentation in HTML format • eee Appendix K 2003 Prentice Hall, Inc. All rights reserved. 7 2.2 A Simple Program: Printing a Line of Text 3 – Blank line • Makes program more readable • Blank lines, spaces, and tabs are white-space characters – Ignored by compiler 4 public class Welcome1 { – Begins class declaration for class Welcome1 • Every Java program has at least one user-defined class • Keyword: words reserved for use by Java – class keyword followed by class name • Naming classes: capitalize every word – SampleClassName 2003 Prentice Hall, Inc. All rights reserved. 8 2.2 4 A Simple Program: Printing a Line of Text public class Welcome1 { – Name of class called identifier • Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) • Does not begin with a digit, has no spaces • Examples: Welcome1, $value, _value, button7 – 7button, first line are invalid • Java is case sensitive (capitalization matters) – a1 and A1 are different – For chapters 2 to 7, use public keyword • Certain details not important now • Mimic certain features, discussions later 2003 Prentice Hall, Inc. All rights reserved. 9 2.2 4 A Simple Program: Printing a Line of Text public class Welcome1 { – Saving files • File name must be class name with .java extension • Welcome1.java – Left brace { • Begins body of every class decleration • Right brace ends declarations (line 13) 7 public static void main( String args[] ) – Part of every Java application • Applications begin executing at main – Parenthesis indicate main is a method (ch. 6) – Java applications contain one or more methods 2003 Prentice Hall, Inc. All rights reserved. 10 2.2 7 A Simple Program: Printing a Line of Text public static void main( String args[] ) • Exactly one method must be called main – Methods can perform tasks and return information • void means main returns no information • For now, mimic main's first line 8 { – Left brace begins body of method declaration • Ended by right brace } (line 11) 2003 Prentice Hall, Inc. All rights reserved. 11 2.2 9 A Simple Program: Printing a Line of Text System.out.println( "Welcome to Java Programming!" ); – Instructs computer to perform an action • Prints string of characters – String - series characters inside double quotes • White-spaces in strings are not ignored by compiler – System.out • Standard output object • Print to command window (i.e., MS-DOS prompt) – Method System.out.println • Displays line of text • Argument inside parenthesis • compleating printing, position the cursor to tbe begiining of next line – This line known as a statement • Statements must end with semicolon ; 2003 Prentice Hall, Inc. All rights reserved. 12 2.2 11 A Simple Program: Printing a Line of Text } // end method main – Ends method declaration 13 – – – – – } // end class Welcome1 Ends class declaration Can add comments to keep track of ending braces Lines 8 and 9 could be rewritten as: Remember, compiler ignores comments Comments can start on same line after code 2003 Prentice Hall, Inc. All rights reserved. 13 2.2 A Simple Program: Printing a Line of Text • Compiling a program – Open a command prompt window, go to directory where program is stored – Type javac Welcome1.java – If no errors, Welcome1.class created • Has bytecodes that represent application • Bytecodes passed to Java interpreter 2003 Prentice Hall, Inc. All rights reserved. 14 2.2 A Simple Program: Printing a Line of Text • Executing a program – Type java Welcome1 • Interpreter loads .class file for class Welcome1 • .class extension omitted from command – Interpreter calls method main Fig. 2.2 Executing Welcome1 in a Microsoft Windows 2000 Command Prompt. 2003 Prentice Hall, Inc. All rights reserved. 15 2.3 Modifying Our First Java Program • Modify example in Fig. 2.1 to print same contents using different code 2003 Prentice Hall, Inc. All rights reserved. 16 2.3 Modifying Our First Java Program • Displaying single line of text with multiple statemetns – Welcome2.java (Fig. 2.3) produces same output as Welcome1.java (Fig. 2.1) – Using different code 9 10 System.out.print( "Welcome to " ); System.out.println( "Java Programming!" ); – Line 9 displays “Welcome to ” with cursor remaining on printed line – Line 10 displays “Java Programming! ” on same line with cursor on next line 2003 Prentice Hall, Inc. All rights reserved. 17 Outline Welcome2.java 1. Comments 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Fig. 2.3: Welcome2.java // Printing a line of text with multiple statements. public class Welcome2 { // main method begins execution of Java application public static void main( String args[] ) { System.out.print( "Welcome to " ); System.out.println( "Java Programming!" ); } // end method main } // end class Welcome2 System.out.print keeps the cursor on the same line, so System.out.println continues on the same line. Welcome to Java Programming! 2. Blank line 3. Begin class Welcome2 3.1 Method main 4. Method System.out.prin t 4.1 Method System.out.prin tln 5. end main, Welcome2 Program Output 2003 Prentice Hall, Inc. All rights reserved. 18 2.3 Modifying Our First Java Program • Displaying multiple lines of text with single statement • Newline characters (\n) – Interpreted as “special characters” by methods System.out.print and System.out.println – Indicates cursor should be on next line – Welcome3.java (Fig. 2.4) 9 System.out.println( "Welcome\nto\nJava\nProgramming!" ); – Line breaks at \n • Usage – Can use in System.out.println or System.out.print to create new lines • System.out.println( "Welcome\nto\nJava\nProgramming!" ); 2003 Prentice Hall, Inc. All rights reserved. 19 Outline 1 2 3 4 5 6 7 8 9 10 11 12 13 // Fig. 2.4: Welcome3.java // Printing multiple lines of text with a single statement. Welcome3.java public class Welcome3 { 1. main // main method begins execution of Java application public static void main( String args[] ) { System.out.println( "Welcome\nto\nJava\nProgramming!" ); } // end method main 2. System.out.prin tln (uses \n for new line) } // end class Welcome3 Program Output Welcome to Java Programming! Notice how a new line is output for each \n escape sequence. 2003 Prentice Hall, Inc. All rights reserved. 20 2.3 Modifying Our First Java Program Escape characters – Backslash ( \ ) – Indicates special characters be output Esc a p e De sc rip tio n se q ue nc e \n Newline. Position the screen cursor at the beginning of the next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. \\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example, System.out.println( "\"in quotes\"" ); displays "in quotes" Fig. 2.5 So m e c o m m o n e sc a p e se q ue nc e s. 2003 Prentice Hall, Inc. All rights reserved. 21 2.4 Displaying Text with printf • System.out.printf method – displaying formated data in Java SE 5.0 – same output in figure 2çwith printf System.out.printf(“%s\n%s\n”, “Welcome to”,”Java programming”); – Line 9 displays “Welcome to ” with cursor remaining on printed line – Line 10 displays “Java Programming! ” on same line with cursor on next line • The method has three arguments – comma seperated list 2003 Prentice Hall, Inc. All rights reserved. 22 2.4 Displaying Text with printf • Line 9-10 one statement – can be split into more then one line – ends with ; – can not be splitted • identifiers or • strings • first argumet: – format string • fixed text • format specifiers • format specifiers – begins with a % followed by a character • s for strings • d for integers 2003 Prentice Hall, Inc. All rights reserved. f: float lf:double 23 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Fig. 2.6: Welcome4.java // Printing multiple lines with printf. public class Welcome4 { // main method begins execution of Java application public static void main( String args[] ) { System.out.printf( “%s\n%s\n “, “Welcome to”,"Java Programming!" ); } // end method main } // end class Welcome4 output of program Welcome to Java Programming! 2003 Prentice Hall, Inc. All rights reserved. 24 3.9 Displaying Text in a Dialog Box • Display – Most Java applications use windows or a dialog box • We have used command window – Class JOptionPane allows us to use dialog boxes • Packages – Set of predefined classes for us to use – Groups of related classes called packages • Group of all packages known as Java class library or Java applications programming interface (Java API) – JOptionPane is in the javax.swing package • Package has classes for using Graphical User Interfaces (GUIs) 2003 Prentice Hall, Inc. All rights reserved. 25 3.9 Displaying Text in a Dialog Box • Upcoming program – – – – Application that uses dialog boxes Explanation will come afterwards Demonstrate another way to display output Packages, methods and GUI 2003 Prentice Hall, Inc. All rights reserved. 26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 1// // Fig. 2.6: Welcome4.java Fig. 2.6: Welcome4.java // Printing multiple lines in a dialog box. 2 // Printing multiple lines in a dialog box 3// import javax.swing.JOptionPane; // import class JOptionPane Java packages 4import javax.swing.JOptionPane; // program uses JOptionPane 5 public class Welcome4 { public class Welcome4 { 6 public static void main( String args] ) // main method begins execution of Java application 7 { public static void main( String args[] ) 8 { JOptionPane.showMessageDialog( JOptionPane.showMessageDialog( 9 null, "Welcome\nto\nJava\nProgramming!" ); null, "Welcome\nto\nJava\nProgramming!" ); 10 11 12 System.exit( 0 ); } } // end method main } // end class Welcome4 // terminate the program Outline Welcome4.java 1. import declaration 2. Class Welcome4 2.1 main 2.2 showMessageDial og 2.3 System.exit Program Output 2003 Prentice Hall, Inc. All rights reserved. 27 1 // Fig. 3.17 Dialog1.java 2 // Printing multiple lines in a dialog box. 3 4 // Java packages 5 import javax.swing.JOptionPane; // program uses JOptionPane 6 7 public class Dialog1 { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 JOptionPane.showMessageDialog( 13 null, "Welcome\nto\nJava\nProgramming!" ); 14 15 } // end method main 16 17 } // end class Dialog1 2003 Prentice Hall, Inc. All rights reserved. 28 3.9 Displaying Text in a Dialog Box – Lines 1-2: comments as before 4 // Java packages – Two groups of packages in Java API – Core packages • Begin with java • Included with Java 2 Software Development Kit – Extension packages • Begin with javax • New Java packages 5 import javax.swing.JOptionPane; // program uses OptionPane – import declarations • Used by compiler to identify and locate classes used in Java programs • Tells compiler to load class JOptionPane from javax.swing package 2003 Prentice Hall, Inc. All rights reserved. 29 3.9 Displaying Text in a Dialog Box – Lines 6-11: Blank line, begin class Welcome4 and main 12 13 JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); – Call method showMessageDialog of class JOptionPane • Requires two arguments • Multiple arguments separated by commas (,) • For now, first argument always null • Second argument is string to display – showMessageDialog is a static method of class JOptionPane • static methods called using class name, dot (.) then method name 2003 Prentice Hall, Inc. All rights reserved. 30 3.9 Displaying Text in a Dialog Box – All statements end with ; • A single statement can span multiple lines • Cannot split statement in middle of identifier or string – Executing lines 12 and 13 displays the dialog box • Automatically includes an OK button – Hides or dismisses dialog box • Title bar has string Message 2003 Prentice Hall, Inc. All rights reserved. 31 3.9 Displaying Text in a Dialog Box – Class System part of package java.lang • No import declaration needed • java.lang automatically imported in every Java program – Lines 17-19: Braces to end Welcome4 and main 2003 Prentice Hall, Inc. All rights reserved. 32 2.5 Another Java Application: Adding Integers • Upcoming program – Use input dialogs to input two values from user – Use message dialog to display sum of the two values 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 2.9: Addition.java // Addition program that displays the sum of two numbers. // Java packages import javax.swing.JOptionPane; Outline Addition.java // program uses JOptionPane 1. import public class Addition { name and // main method begins executionDeclare of Javavariables: application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user int number1; int number2; int sum; type. // first number to add Input first integer // second number to add as a String, // sum to offirstNumber. number1 and number2 2.1 Declare variables (name and type) assign // read in first number from user as a String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); 2. class Addition 3. showInputDialog 4. parseInt 5. Add numbers, put result in sum Convert strings to integers. // convert numbers from type StringAdd, to type placeint result number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // add numbers sum = number1 + number2; in sum. 2003 Prentice Hall, Inc. All rights reserved. 34 33 34 35 36 37 38 39 40 41 // display result JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); Outline } // end method main } // end class Addition Program output 2003 Prentice Hall, Inc. All rights reserved. 35 import javax.swing.JOptionPane; // program uses JOptionPane public class Addition { // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user int number1; int number2; int sum; // first number to add // second number to add // sum of number1 and number2 // read in first number from user as a String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); 2003 Prentice Hall, Inc. All rights reserved. 36 number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // add numbers sum = number1 + number2; // display result JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); } // end method main } // end class Addition 2003 Prentice Hall, Inc. All rights reserved. 37 2.5 5 Another Java Application: Adding Integers import javax.swing.JOptionPane; // program uses JOptionPane – Location of JOptionPane for use in the program 7 public class Addition { – Begins public class Addition • Recall that file name must be Addition.java – Lines 10-11: main 12 13 String firstNumber; String secondNumber; // first string entered by user // second string entered by user – Declaration • firstNumber and secondNumber are variables 2003 Prentice Hall, Inc. All rights reserved. 38 2.5 12 13 Another Java Application: Adding Integers String firstNumber; String secondNumber; // first string entered by user // second string entered by user – Variables • Location in memory that stores a value – Declare with name and type before use • firstNumber and secondNumber are of type String (package java.lang) – Hold strings • Variable name: any valid identifier • Declarations end with semicolons ; String firstNumber, secondNumber; – Can declare multiple variables of the same type at a time – Use comma separated list – Can add comments to describe purpose of variables 2003 Prentice Hall, Inc. All rights reserved. 39 2.5 15 16 17 Another Java Application: Adding Integers int number1; int number2; int sum; // first number to add // second number to add // sum of number1 and number2 – Declares variables number1, number2, and sum of type int • int holds integer values (whole numbers): i.e., 0, -4, 97 • Types float and double can hold decimal numbers • Type char can hold a single character: i.e., x, $, \n, 7 • Primitive types - more in Chapter 4 2003 Prentice Hall, Inc. All rights reserved. 40 2.5 20 Another Java Application: Adding Integers firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); – Reads String from the user, representing the first number to be added • Method JOptionPane.showInputDialog displays the following: • Message called a prompt - directs user to perform an action • Argument appears as prompt text • If wrong type of data entered (non-integer) or click Cancel, error occurs 2003 Prentice Hall, Inc. All rights reserved. 41 2.5 20 Another Java Application: Adding Integers firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); – Result of call to showInputDialog given to firstNumber using assignment operator = • Assignment statement • = binary operator - takes two operands – Expression on right evaluated and assigned to variable on left • Read as: firstNumber gets value of JOptionPane.showInputDialog( "Enter first integer" ) 2003 Prentice Hall, Inc. All rights reserved. 42 2.5 23 24 Another Java Application: Adding Integers secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); – Similar to previous statement • Assigns variable secondNumber to second integer input 27 28 number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); – Method Integer.parseInt • Converts String argument into an integer (type int) – Class Integer in java.lang • Integer returned by Integer.parseInt is assigned to variable number1 (line 27) – Remember that number1 was declared as type int • Line 28 similar 2003 Prentice Hall, Inc. All rights reserved. 43 2.5 31 Another Java Application: Adding Integers sum = number1 + number2; – Assignment statement • Calculates sum of number1 and number2 (right hand side) • Uses assignment operator = to assign result to variable sum • Read as: sum gets the value of number1 + number2 • number1 and number2 are operands 2003 Prentice Hall, Inc. All rights reserved. 44 2.5 34 35 Another Java Application: Adding Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); – Use showMessageDialog to display results – "The sum is " + sum • Uses the operator + to "add" the string literal "The sum is" and sum • Concatenation of a String and another type – Results in a new string • If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117" • Note the space in "The sum is " 2003 Prentice Hall, Inc. All rights reserved. 45 2.5 34 35 Another Java Application: Adding Integers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); – Different version of showMessageDialog • • • • • Requires four arguments (instead of two as before) First argument: null for now Second: string to display Third: string in title bar Fourth: type of message dialog with icon – Line 35 no icon: JOptionPane.PLAIN_MESSAGE 2003 Prentice Hall, Inc. All rights reserved. 46 2.5 Another Java Application: Adding Integers Messa g e d ia lo g typ e Ic o n Desc rip tio n JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error to the user. JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational message to the user. The user can simply dismiss the dialog. JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a potential problem. JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button. JOptionPane.PLAIN_MESSAGE Displays a dialog that simply contains a message, with no icon. Fig. 2.12 JOptionPane c o nsta nts fo r m essa g e d ia lo g s. 2003 Prentice Hall, Inc. All rights reserved. no icon 47 2.5 Another Java Application: Adding Integers • Upcoming program – Use Scanner class to input two values from the console 2003 Prentice Hall, Inc. All rights reserved. 48 1 2 3 // Fig. 2.7: Addition.java // Addition program that displays the sum of two numbers. import java.util.Scanner; // program uses class Scanner 4 5 public class Addition 6 { 7 // main method begins execution of Java application 8 public static void main( String args[] ) 9 { 10 // criate Scanner to optain input ftom comment window 11 Scanner input = new Scanner(System.in); 12 13 int number1; // first number to add 14 int number2; // second number to add 15 int sum; // sum of two numbers 16 17 System.out.print(“Enter first integer:”); 18 number1 = input.nextInt(); //read first number 2003 Prentice Hall, Inc. All rights reserved. 49 19 20 21 22 23 24 25 26 27 28 System.out.print(“Enter second integer:”); number2 = input.nextInt(); //read first number sum = number1 + number2 System.out.pritf(“Sum is %d\n”, sum); } } // end of main // end of calss Addition The programs output: Enter first integer 45 Enter second integer 72 Sum is 117 2003 Prentice Hall, Inc. All rights reserved. 50 2.5 Another Java Application: Adding Integers inport java.util.Scanner; • line 3 inport decleration – help the compiler to locate a class used in this program – program uses predefined Scanner class in the java.util package • if the inport decleration is not used – Scanner class should be used like that • java.util.Scanner – Example: • Scanner input = new Scanner(System.in); – Should be replaced with • java.util.Scanner input = new java.util.Scanner(System.in); 2003 Prentice Hall, Inc. All rights reserved. 51 2.5 Another Java Application: Adding Integers Scanner input = new Scanner(System.in); • line 11 variable decleration statement – variable name input – varaible type Scanner • Names are identifiers • Scanner – enables to read data (numbers, strings) – sources: • file on a disk • user from keyboard • before using a Scanner type variable – criate it and – specify the source of data 2003 Prentice Hall, Inc. All rights reserved. 52 2.5 Another Java Application: Adding Integers • in line 11 Scanner variable input should be initialized • the expression – new Scanner(System.in) – criates a Scanner objcet that reads data typed by the user from the keyboard • System.out: standard output objcet – display characters in the command window • Syste.in: standard input objcet – enables users to enter input from keyboard 2003 Prentice Hall, Inc. All rights reserved. 53 2.5 Another Java Application: Adding Integers number1 = input.nextInt(); • line 18 Scanner object input’s nextInt method – to obtain an integer from the user at the keyboard – if the user types an non ingeger value at the keyboard • the program terminates – logic runtime error – nextInt method return an intger variable – input by the user – by the assignment opperator • assigned to int variable number1 2003 Prentice Hall, Inc. All rights reserved. 54 2.5 Another Java Application: Adding Integers • Note that – nextInt method is called with the input object a Scanner type objcet - general format – objcet name.method name • In the previous example – JOptionPane’s showInputDialog method is called with the class name – in general – class name.method name – thess are static method which are used by class names – non-static mehods are used with objcets criated from classes 2003 Prentice Hall, Inc. All rights reserved. 55 2.6 Memory Concepts • Variables – Every variable has a name, a type, a size and a value • Name corresponds to location in memory – When new value is placed into a variable, replaces (and destroys) previous value – Reading variables from memory does not change them 2003 Prentice Hall, Inc. All rights reserved. 56 2.6 Memory Concepts • Visual Representation – Sum = 0; number1 = 1; number2 = 2; sum 0 – Sum = number1 + number2; after execution of statement sum 2003 Prentice Hall, Inc. All rights reserved. 3 57 2.7 Arithmetic • Arithmetic calculations used in most programs – Usage • * for multiplication • / for division • +, • No operator for exponentiation (more in Chapter 5) – Integer division truncates remainder 7 / 5 evaluates to 1 – Remainder operator % returns the remainder 7 % 5 evaluates to 2 2003 Prentice Hall, Inc. All rights reserved. 58 Casting • int i=5,j=2; • What is i / j • : 5 / 2 = 2 integer division – Both nominator and denominator are integers • • • • • • İf you want to get a decimal number Use casting (float) i / j = 5.0 / 2 = 2.5 (double) i / j = 5.0 / 2 =2.5 or i / (double)j = 5/ 2.0 =2.5 The original values of i or j does not change they temporarily promoted to a (double float) in evaluationg the expression 2003 Prentice Hall, Inc. All rights reserved. 59 2.7 Operator(s) * / % + Fig. 2.12 Operation(s) Multiplication Division Remainder Addition Subtraction Arithmetic Order of evaluation (precedence) Evaluated first. If there are several of this type of operator, they are evaluated from left to right. Evaluated next. If there are several of this type of operator, they are evaluated from left to right. Precedence of arithmetic operators. 2003 Prentice Hall, Inc. All rights reserved. 60 4.11 Compound Assignment Operators • Assignment Operators – Abbreviate assignment expressions – Any statement of form • variable = variable operator expression; – Can be written as • variable operator= expression; – e.g., addition assignment operator += •c = c + 3 – can be written as • c += 3 2003 Prentice Hall, Inc. All rights reserved. 61 Assig nm ent Sa m p le Exp la na tion op era tor exp ression Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 -= d -= 4 d = d - 4 *= e *= 5 e = e * 5 /= f /= 3 f = f / 3 %= g %= 9 g = g % 9 Fig. 4.12 Arithm etic a ssig nm ent op era to rs. 2003 Prentice Hall, Inc. All rights reserved. Assig ns 10 to c 1 to d 20 to e 2 to f 3 to g 62 4.12 Increment and Decrement Operators • Unary increment operator (++) – Increment variable’s value by 1 • Unary decrement operator (--) – Decrement variable’s value by 1 • Preincrement / predecrement operator • Post-increment / post-decrement operator 2003 Prentice Hall, Inc. All rights reserved. 63 Op era tor Ca lled ++ preincrement ++ postincrement -- predecrement -- postdecrement Fig. 4.13 The inc rem ent 2003 Prentice Hall, Inc. All rights reserved. Sa m p le exp ression ++a Exp la na tion Increment a by 1, then use the new value of a in the expression in which a resides. a++ Use the current value of a in the expression in which a resides, then increment a by 1. --b Decrement b by 1, then use the new value of b in the expression in which b resides. b-Use the current value of b in the expression in which b resides, then decrement b by 1. a nd d ec re m ent op era tors. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 64 // Fig. 4.14: Increment.java // Preincrementing and postincrementing operators. public class Increment { Outline Line 13 postincrements c public static void main( String args[] ) { int c; // demonstrate postincrement c = 5; // System.out.println( c ); // System.out.println( c++ ); // System.out.println( c ); // System.out.println(); assign 5 to c print 5 Line 21 preincrements print 5 then postincrement print 6 Increment.java Line 13 postincrement Line 21 preincrement c // skip a line // demonstrate preincrement c = 5; // System.out.println( c ); // System.out.println( ++c ); // System.out.println( c ); // assign 5 to c print 5 preincrement then print 6 print 6 } // end main } // end class Increment 5 5 6 5 6 6 2003 Prentice Hall, Inc. All rights reserved. 65 Op era tors Assoc ia tivity Typ e ++ -right to left unary postfix ++ -- + (type) right to left unary * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 4.15 Prec ed enc e a nd a ssoc ia tivity of the op era tors d isc ussed so fa r. 2003 Prentice Hall, Inc. All rights reserved. 66 4.13 Primitive Types • Primitive types – “building blocks” for more complicated types • Java is strongly typed – All variables in a Java program must have a type • Java primitive types – portable across computer platforms that support Java 2003 Prentice Hall, Inc. All rights reserved. 67 Typ e boolean Size in b its char 16 byte 8 short 16 int 32 long 64 float 32 double 64 Fig. 4.16 The Ja va Va lues true or false Sta nd a rd [Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.] '\u0000' to '\uFFFF' (ISO Unicode character set) (0 to 65535) –128 to +127 (–27 to 27 – 1) –32,768 to +32,767 (–215 to 215 – 1) –2,147,483,648 to +2,147,483,647 (–231 to 231 – 1) –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (–263 to 263 – 1) Negative range: (IEEE 754 floating point) –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38 Negative range: (IEEE 754 floating point) –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308 p rim itive typ es. 2003 Prentice Hall, Inc. All rights reserved. 68 Boolean Variables • A primitive variable in java – either true or false • Decleration – – – – • • • boolean b1,b2; // declaring two boolean variables boolean b3= true;// declaring and initilizing b1 = 2<1; /* 2<1 is a logical expression whose value is false right side of expression is false it is assigned to b1 so b1 is false */ 2003 Prentice Hall, Inc. All rights reserved. 69 • • • • • • • • • • • b2 = b1 && b3; /* b1 is false b3 is true so b2 is false */ System.out.println(“b1 is ”+b1); System.out.println(“b2 && b3 is ”+(b2 && b3)); System.out.printf(“b2 && b3 is %b\n”, (b2 && b3)); if(b1) System.out.println(“b1 is true”); else System.out.println(“b1 is false”); 2003 Prentice Hall, Inc. All rights reserved. 70 • The output is: b1 is false b2 && b3 is false b2 && b3 is false b1 is false 2003 Prentice Hall, Inc. All rights reserved. 71 2.8 Decision Making: Equality and Relational Operators • if control statement – Simple version in this section, more detail later – If a condition is true, then the body of the if statement executed – Control always resumes after the if structure – Conditions for if statements can be formed using equality or relational operators (next slide) if ( condition ) statement executed if condition true • No semicolon needed after condition – Else conditional task not performed 2003 Prentice Hall, Inc. All rights reserved. 72 • condition should be a logical expression not an aritmetic expression as in C • Example: – int i =1; if(i-1) System.out.printf(“true”); else System.out.printf(“false”); Syntax error in java as – int i =1; – boolean b = i-1==0; if(b) // or if(i-1==0) System.out.printf(“true”); else System.out.printf(“false”); 2003 Prentice Hall, Inc. All rights reserved. 73 2.8 Decision Making: Equality and Relational Operators Sta nd a rd a lg eb ra ic Ja va eq ua lity Exa m p le eq ua lity o r or rela tio na l of Ja va rela tiona l o p era tor op era tor c ond itio n Equality operators == x == y = != x != y Relational operators > x > y > < x < y < >= x >= y <= x <= y Fig. 2.19 Eq ua lity a nd rela tiona l o p era to rs. Mea ning o f Ja va c ond ition x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y • Upcoming program uses if statements – Discussion afterwards 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 2.20: Comparison.java // Compare integers using if statements, relational operators // and equality operators. // Java packages import javax.swing.JOptionPane; public class Comparison { Outline Comparison.java 1. import // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user String result; // a string containing the output int number1; int number2; 74 // first number to compare // second number to compare 2. Class Comparison 2.1 main 2.2 Declarations // read first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); 2.3 Input data (showInputDialo g) // read second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer:" ); 2.4 parseInt // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // initialize result to empty String result = ""; 2.5 Initialize result 2003 Prentice Hall, Inc. All rights reserved. 75 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 Outline if ( number1 == number2 ) result = result + number1 + " == " + number2; if ( number1 != number2 ) result = result + number1 + " != " + number2; Test for equality, createComparison.java new string, assign to result. if ( number1 < number2 ) result = result + "\n" + number1 + " < " + number2; if ( number1 > number2 ) result = result + "\n" + number1 + " > " + number2; if ( number1 <= number2 ) result = result + "\n" + number1 + " <= " + number2; 3. if statements 4. showMessageDialo g if ( number1 >= number2 ) result = result + "\n" + number1 + " >= " + number2; // Display results JOptionPane.showMessageDialog( null, result, "Comparison Results", JOptionPane.INFORMATION_MESSAGE ); } // end method main } // end class Comparison Notice use of JOptionPane.INFORMATION_MESSAGE 2003 Prentice Hall, Inc. All rights reserved. 76 Outline Program Output 2003 Prentice Hall, Inc. All rights reserved. 77 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // Fig. 2.20: Comparison.java // Compare integers using if statements, relational operators // and equality operators. // Java packages import javax.swing.JOptionPane; public class Comparison { // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user String result; // a string containing the output int number1; int number2; 2003 Prentice Hall, Inc. All rights reserved. // first number to compare // second number to compare 78 20 21 22 23 24 25 26 27 28 29 30 31 32 // read first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); // read second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer:" ); // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // initialize result to empty String result = ""; 2003 Prentice Hall, Inc. All rights reserved. 79 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 if ( number1 == number2 ) result = result + number1 + " == " + number2; if ( number1 != number2 ) result = result + number1 + " != " + number2; if ( number1 < number2 ) result = result + "\n" + number1 + " < " + number2; if ( number1 > number2 ) result = result + "\n" + number1 + " > " + number2; if ( number1 <= number2 ) result = result + "\n" + number1 + " <= " + number2; if ( number1 >= number2 ) result = result + "\n" + number1 + " >= " + number2; 2003 Prentice Hall, Inc. All rights reserved. 80 52 53 // Display results JOptionPane.showMessageDialog( null, result, "Comparison Results", 54 JOptionPane.INFORMATION_MESSAGE ); 55 56 57 58 } // end method main 59 60 } // end class Comparison 2003 Prentice Hall, Inc. All rights reserved. 81 2.8 Decision Making: Equality and Relational Operators – Lines 1-12: Comments, import JOptionPane, begin class Comparison and main – Lines 13-18: declare variables • Can use comma-separated lists instead: 13 14 15 String firstNumber, secondNumber, result; – Lines 21-30: obtain user-input numbers and parses input string into integer variables 2003 Prentice Hall, Inc. All rights reserved. 82 2.8 32 Decision Making: Equality and Relational Operators result = ""; – Initialize result with empty string 34 35 if ( number1 == number2 ) result = result + number1 + " == " + number2; – if statement to test for equality using (==) • If variables equal (condition true) – result concatenated using + operator – result = result + other strings – Right side evaluated first, new string assigned to result • If variables not equal, statement skipped 2003 Prentice Hall, Inc. All rights reserved. 83 2.8 Decision Making: Equality and Relational Operators – Lines 37-50: other if statements testing for less than, more than, etc. • If number1 = 123 and number2 = 123 – Line 34 evaluates true (if number1 = = number 2) • Because number1 equals number2 – Line 40 evaluates false (if number1 < number 2) • Because number1 is not less than number2 – Line 49 evaluates true (if number1 >= number2) • Because number1 is greater than or equal to number2 – Lines 53-54: result displayed in a dialog box using showMessageDialog 2003 Prentice Hall, Inc. All rights reserved. 84 2.8 Decision Making: Equality and Relational Operators • Precedence of operators – All operators except for = (assignment) associates from left to right • For example: x = y = z is evaluated x = (y = z) Op era tors Assoc ia tivity Typ e * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 2.21 Prec ed enc e a nd a ssoc ia tivity of the op era tors d isc ussed so fa r. 2003 Prentice Hall, Inc. All rights reserved. 85 4.5 if Single-Selection Statement • Single-entry/single-exit control structure • Perform action only when condition is true • Action/decision programming model 2003 Prentice Hall, Inc. All rights reserved. 86 [grade >= 60] print “Passed” [grade < 60] Fig 4.3 if single-selections statement activity diagram. 2003 Prentice Hall, Inc. All rights reserved. 87 4.6 if…else Selection Statement • Perform action only when condition is true • Perform different specified action when condition is false • Conditional operator (?:) • Nested if…else selection structures 2003 Prentice Hall, Inc. All rights reserved. 88 [grade < 60] print “Failed” [grade >= 60] print “Passed” Fig 4.4 if…else double-selections statement activity diagram. 2003 Prentice Hall, Inc. All rights reserved. 89 5.8 Logical Operators • Logical operators – Allows for forming more complex conditions – Combines simple conditions • Java logical operators – – – – – – && & || | ^ ! (conditional AND) (boolean logical AND) (conditional OR) (boolean logical inclusive OR) (boolean logical exclusive OR) (logical NOT) 2003 Prentice Hall, Inc. All rights reserved. 90 expression1 && expression2 false false false false true false true false false true true true Fig. 5.15 && (conditional AND) operator truth table. expression1 expression2 expression1 || expression2 false false false false true true true false true true true true Fig. 5.16 || (conditional OR) operator truth table. expression1 expression2 2003 Prentice Hall, Inc. All rights reserved. 91 expression1 ^ expression2 false false false false true true true false true true true false Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table. expression1 expression2 expression !expression false true true false Fig. 5.18 ! (logical negation, or logical NOT) operator truth table. 2003 Prentice Hall, Inc. All rights reserved. 92 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 Outline // Fig. 5.19: LogicalOperators.java // Logical operators. import javax.swing.*; LogicalOperator s.java public class LogicalOperators public static void main( String args[] ) { // create JTextArea to display results JTextArea outputArea = new JTextArea( 17, 20 ); Lines 16-20 Lines 23-27 // attach JTextArea to a JScrollPane so user can scroll results JScrollPane scroller = new JScrollPane( outputArea ); Conditional AND truth table // create truth table for && (conditional AND) operator String output = "Logical AND (&&)" + "\nfalse && false: " + ( false && false ) + "\nfalse && true: " + ( false && true ) + "\ntrue && false: " + ( true && false ) + "\ntrue && true: " + ( true && true ); Conditional OR truth table // create truth table for || (conditional OR) operator output += "\n\nLogical OR (||)" + "\nfalse || false: " + ( false || false ) + "\nfalse || true: " + ( false || true ) + "\ntrue || false: " + ( true || false ) + "\ntrue || true: " + ( true || true ); 2003 Prentice Hall, Inc. All rights reserved. 93 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // create truth table for & (boolean logical AND) operator output += "\n\nBoolean logical AND (&)" + "\nfalse & false: " + ( false & false ) + "\nfalse & true: " + ( false & true ) + "\ntrue & false: " + ( true & false ) + Boolean logical "\ntrue & true: " + ( true & true ); Outline AND LogicalOperator s.java truth table Lines // create truth table for | (boolean logical inclusive OR) operator output += "\n\nBoolean logical inclusive OR (|)" + "\nfalse | false: " + ( false | false ) + Lines "\nfalse | true: " + ( false | true ) + "\ntrue | false: " + ( true | false ) + Boolean logical inclusive Lines "\ntrue | true: " + ( true | true ); 30-34 37-41 44-48 OR truth table // create truth table for ^ (boolean logical exclusive OR) operator Lines output += "\n\nBoolean logical exclusive OR (^)" + "\nfalse ^ false: " + ( false ^ false ) + "\nfalse ^ true: " + ( false ^ true ) + "\ntrue ^ false: " + ( true ^ false ) + Boolean logical exclusive "\ntrue ^ true: " + ( true ^ true ); 51-53 OR truth table // create truth table for ! (logical negation) operator output += "\n\nLogical NOT (!)" + "\n!false: " + ( !false ) + "\n!true: " + ( !true ); Logical NOT truth outputArea.setText( output ); table // place results in JTextArea 2003 Prentice Hall, Inc. All rights reserved. 57 58 59 60 61 62 63 64 JOptionPane.showMessageDialog( null, scroller, "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main 94 Outline LogicalOperator s.java } // end class LogicalOperators 2003 Prentice Hall, Inc. All rights reserved. 95 Operators Associativity Type ++ -right to left unary postfix ++ -- + ! right to left unary (type) * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right conditional AND || left to right conditional OR ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 5.20 Precedence/associativity of the operators discussed so far. 2003 Prentice Hall, Inc. All rights reserved. 96 What is the output int i =1; boolean b1 = ++i == i++; boolean b2 = i++ == ++i; System.out.printf(“%d%b%b”,i,b1,b2); ---------------String s1 = 1 + 2 + “what is this”; String s2 = “what is this” + 1 + 2; System.out.printf(“%s\n%s”,s1,s2); ---------------------String s3 = “”+1 + 2 + “what is this”; String s4 = “what is this” + (1 + 2); System.out.printf(“%s\n%s”,s3,s4); 2003 Prentice Hall, Inc. All rights reserved. 97 What is the output ---------------int i =1; System.out.printf(“%d %d %d”,++i,i,i++); System.out.printf(“%d %d %d”, i++,i,++i); ---------------------int i =1; System.out.printf(“%d %d %d”,++i,i,i++); System.out.printf(“%d %d %d”, i++,i,++i); 2003 Prentice Hall, Inc. All rights reserved. 98 Exercise • A user intends to withdraw money from a ATM machine by entering the amount she needs • The ATM machine contains a set of notes e.g.: – 100 TL, 50 TL, 20 TL... – For the time beeing assume that there is no availability problem for any of these notes – ATM first pays 100 TLs as much as possible then pays 50 TLs and so on • e.g.: the user demands 328 – Available notes are 100,50,20,10 – ATM pays 3 100s , 1 20 but the 8 TL can not be paid • e.g.: the user demands 483 – Available notes are 100,50,20,10 – ATM pays 4 100s , 1 50 , 1 20, 1 10 but the 3 TL can not be paid 2003 Prentice Hall, Inc. All rights reserved. 99 • Write a program obtaining the amout of money from the user and outputing how it is paid with availabe note in the ATM. The program should also give the amout of money that can not be paid. • Externsion: • You can extend the problem to TL and kurushes with say 2 digits • Availabel notes are say 100,50,20,10,5,1 • Available coints are 50,25,10,5 2003 Prentice Hall, Inc. All rights reserved. 100 • • • • e.g.: how to pay 37.86 TL 1: 20 + 1: 10 + 1: 5 + 2: 1 notes 1: 50 + 1: 25 + 1: 10 coins 1 krush can not be paid 2003 Prentice Hall, Inc. All rights reserved. 101 Exercise • Leap year problem • Given a year determine whether it is a leap year or not • i. A year is a leap year if it is divided by four – 2004, 2000, 1900 are but – 2005, 2001 not • ii. in addition it can not be divided by 100 – 2004 is but – 2000 is not as 2000 mode 100 = 0 • iii. in addition it is divided by 400 – 2000 is as 2000 mde 400 = 0 but – 1900 is not, as 1900 mode 100 =0 by B and 1900 mode 400 =300 not zero 2003 Prentice Hall, Inc. All rights reserved. 102 2000 1900 C year mode 400=0 B year mode 100 = 0 2004 2003 Prentice Hall, Inc. All rights reserved. A. Year mode 4 = 0 103 • i can be codes as • İf (year % 4 == 0) • System.out.print(year +“ is a leap year”); • ii can be coded as • if (year % 4 == 0 && year % 100 !=0 ) • System.out.print(year +“ is a leap year”); • Solve iii yourself • Solve the same problem both i ii and iii without using logical oppertators (and or not) 2003 Prentice Hall, Inc. All rights reserved. 104 • For case ii • year b1 b2 b1&&b2 year % 4 ==0 year % 100 !=0 ---------------------------------------------------------2008 true true true 2000 true false false 2003 Prentice Hall, Inc. All rights reserved. 105 • We are going to use this in our coming examples – To calculste difference between days – How many days you live? – To calculate punishments as a function of number of days between due date and today 2003 Prentice Hall, Inc. All rights reserved. 106 Exercise • Progressive taxation • Given the yearly income of a person the amout of income tax is progressively increases. Say – – – – For the first 10,000 TL - no income Between 10,000 and 20,000 – 5% Between 20,000 and 50,000 - 10% After 50,000 – 20% • E.g.: if income is 15,000 – Tax = 0.05*(15,000-10,000) = 250 • E.g.: if income is 35,000 – Tax = 0.05*(20,000-10,000) + 0.1*(35,000-20,000)=2000 2003 Prentice Hall, Inc. All rights reserved. 107 • Write program taking yearly income and calculating and printing the income tax due of a person – For the time being the tax rates and slices are fixed and assigned in the program • i – using the if else structure • ii – using only simple if sturcture without using else part 2003 Prentice Hall, Inc. All rights reserved.