Chapter 2 Java Fundamentals contd Outline o o

  • Slides: 59
Download presentation
Chapter 2: Java Fundamentals cont’d

Chapter 2: Java Fundamentals cont’d

Outline o o o o 2. 1 The Parts of a Java Program 2.

Outline o o o o 2. 1 The Parts of a Java Program 2. 2 The print and println Methods, and the Java Standard Class Library 2. 3 Variables and Literals 2. 4 Primitive Data Types 2. 5 Arithmetic Operators 2. 6 Combined Assignment Operators 2. 7 Conversion Between Primitive Types 2. 8 Creating Named Constants with final 2. 9 The String Class 2. 10 Scope 2. 11 Comments 2. 12 Programming Style 2. 13 Reading Keyboard Input 2. 14 Dialog Boxes 2. 15 Common Errors to Avoid

The % operator o o Returns the remainder of the division Examples; n n

The % operator o o Returns the remainder of the division Examples; n n n 4%5 is 4 30%6 is 0 22%7 is 1 3205%100 is 5 3205%10 is 5

Exercise Write the following in a Java file: double amount = 137/5; System. out.

Exercise Write the following in a Java file: double amount = 137/5; System. out. println(“Amount is : “ + amount ); amount = 137. 0/5; System. out. println(“Amount is : “ + amount ); o

Integer Division o o Dividing an integer by an integer gives an integer the

Integer Division o o Dividing an integer by an integer gives an integer the remainder is ignored Examples: n n 5/4 is 1 17/3 is 5

Operator Precedence o o o What is the result of: Polynomial = 1+2*3+ 6/2

Operator Precedence o o o What is the result of: Polynomial = 1+2*3+ 6/2 -2; Is it ? n n n (1+2)*3 + 6/(2 -2) 1+(2*3) +(6/2)-2 (1+2)*3 + (6/2)-2

Precedence Rules o o o Always evaluate * , / and % before +

Precedence Rules o o o Always evaluate * , / and % before + and – Always negate before any calculations *, / and % have same precedence + and – have same precedence If equal precedence then evaluate from left to right except for negations where we evaluate from right to left

Precedence examples o Polynomial = 1+2*3+ 6/2 – 2; n o o Polynomial has

Precedence examples o Polynomial = 1+2*3+ 6/2 – 2; n o o Polynomial has the value of 1+6+3 -2=8 Polynomial = – 1 + 5 – 2; // 2 Polynomial = –(– 3) + –(– 5); //8

Grouping with parentheses o o You can use parentheses to force the evaluation of

Grouping with parentheses o o You can use parentheses to force the evaluation of a formula Examples: n n n x * ( y + z*z ) instead of x*y + z*z x * ( y * ( z + 165 ) + 85 ) – 65 Average = (a +b +c ) /3;

The Math class o o value = Math. pow( x, y); // now value

The Math class o o value = Math. pow( x, y); // now value holds x to the power of y value = Math. sqrt( x); //now value holds the square root of x

Combined Assignment Operators += x += 1; x = x + 1; –= x

Combined Assignment Operators += x += 1; x = x + 1; –= x –= 1; x = x – 1; *= x *= 1; x = x * 1; /= x /= 1; x = x / 1; %= x %= 1; x = x % 1;

Operator Precedence o o o What is the result of: Polynomial = 1+2*3+ 6/2

Operator Precedence o o o What is the result of: Polynomial = 1+2*3+ 6/2 -2; Is it ? n n n (1+2)*3 + 6/(2 -2) 1+(2*3) +(6/2)-2 (1+2)*3 + (6/2)-2

Precedence Rules o o o Always evaluate * , / and % before +

Precedence Rules o o o Always evaluate * , / and % before + and – Always negate before any calculations *, / and % have same precedence + and – have same precedence If equal precedence then evaluate from left to right except for negations where we evaluate from right to left

Precedence examples o Polynomial = 1+2*3+ 6/2 – 2; n o o Polynomial has

Precedence examples o Polynomial = 1+2*3+ 6/2 – 2; n o o Polynomial has the value of 1+6+3 -2=8 Polynomial = – 1 + 5 – 2; // 2 Polynomial = –(– 3) + –(– 5); //8

Grouping with parentheses o o You can use parentheses to force the evaluation of

Grouping with parentheses o o You can use parentheses to force the evaluation of a formula Examples: n n n x * ( y + z*z ) instead of x*y + z*z x * ( y * ( z + 165 ) + 85 ) – 65 Average = (a +b +c ) /3;

The Math class o o value = Math. pow( x, y); // now value

The Math class o o value = Math. pow( x, y); // now value holds x to the power of y value = Math. sqrt( x); //now value holds the square root of x

Combined Assignment Operators += x += 1; x = x + 1; –= x

Combined Assignment Operators += x += 1; x = x + 1; –= x –= 1; x = x – 1; *= x *= 1; x = x * 1; /= x /= 1; x = x / 1; %= x %= 1; x = x % 1;

2. 7 Conversion between Primitive Data Types o o o Before a value is

2. 7 Conversion between Primitive Data Types o o o Before a value is stored in a variable, Java checks the Data Type of the value and the variable If the data types are compatible then Java performs the conversion automatically No Error If the data types are not compatible then Java issues an error.

2. 7 Conversion between Primitive Data Types o o A widening conversion is the

2. 7 Conversion between Primitive Data Types o o A widening conversion is the conversion of a small value to a larger one A narrowing conversion is the conversion of a large value to a smaller one double largest float long int short byte smallest

Widening conversion o Example 1: n n n o double x; int y =

Widening conversion o Example 1: n n n o double x; int y = 10; x = y; Example 2: n n n int x; short y =2; x= y;

Narrowing Conversion o o We have to perform casting i. e. the name of

Narrowing Conversion o o We have to perform casting i. e. the name of the smaller data type is put in parentheses in front of the value Example: n n n int number; double pi = 3. 14; number = (int) pi;

Cast operator o o Used to convert from one primitive data type to another

Cast operator o o Used to convert from one primitive data type to another Must be used for narrowing conversions

Example: int pies = 10, people = 4; double pies. Person; o o pies.

Example: int pies = 10, people = 4; double pies. Person; o o pies. Person = pies /people; (double)(10/4) = (double)(2) = 2. 0 pies. Person =(double) pies/people; because it is an integer division pies. Person =pies/(double) people; 10/4 = 2 because it is an integer division 10. 0/4 = 2. 5 because one of the numbers pies. Person=(double)(pies/people); is a double 10/4. 0 = 2. 5 because people is double

Mixed Integer Operations o o The result of an arithmetic operation that involves only

Mixed Integer Operations o o The result of an arithmetic operation that involves only byte, short, or int variables is always an int even if both variables are of data type short or byte Example: n n n short x =5, y =7; short z = x+y; // this statement gives an error short z = (short) ( x+y ); //correct

Mixed Integer Operations o o o If one of the operator’s operands is a

Mixed Integer Operations o o o If one of the operator’s operands is a double then the result of the operation is a double If one of the operator’s operands is a float then the result of the operation is a float If one of the operator’s operands is a long then the result of the operation is a long

Creating named constants with final o o A named constant is a variable whose

Creating named constants with final o o A named constant is a variable whose value is read-only and cannot be changed To create a named constant add the word final to declaration An initialization value is required when declaring a constant Example: n final double INTEREST_RATE = 0. 069;

More about named constants o o o When naming a constant, the variable name

More about named constants o o o When naming a constant, the variable name should be written in all uppercase characters. Math. PI is a constant that holds the value of pi ( i. e. 3. 14159 …) Math. PI is already declared and initialized so it ready to use. Example: double area = Math. PI * radius ;

The String class o o o A String literal is any text enclosed in

The String class o o o A String literal is any text enclosed in quotations A String is the Data. Type of a variable that can store String literals Example of a String variable: n n String name = “CS 0007”; System. out. println( name );

The String class o To determine how many letters are stored in a String

The String class o To determine how many letters are stored in a String variable (name) use name. length(); n n n Example: String mycourse = “CS 0007”; int number = mycourse. length();

String methods o char. At(index) n n n index is an integer and specifies

String methods o char. At(index) n n n index is an integer and specifies the character position in the String This method returns the character at the specified position Example: o o o char letter; String my. Text = “This is my Text”; letter = my. Text. char. At(8);

String methods my. Text. length returns 15 because there are 15 characters Th i

String methods my. Text. length returns 15 because there are 15 characters Th i s 0 1 2 3 4 5 6 7 my 8 Tex t 9 1 1 1 0 1 2 3 4 my. Text. char. At(8) returns m because m is the letter at position 8

String methods o to. Lower. Case() n n n This method returns a new

String methods o to. Lower. Case() n n n This method returns a new String that has all of the characters of the original String but in lowercase Example: String big. Name = “I am BIG!!”; String small. Name = big. Name. to. Lower. Case(); // now small. Name holds “i am big!!”

String methods o to. Upper. Case() n n n Same as to. Lower. Case()

String methods o to. Upper. Case() n n n Same as to. Lower. Case() but it converts all the characters to uppercase Example: String small. Name = “I am Big!!”; String big. Name = small. Name. to. Upper. Case(); // now big. Name holds “I AM BIG!!”

Example: String message = "Java is Great Fun!"; String upper = message. to. Upper.

Example: String message = "Java is Great Fun!"; String upper = message. to. Upper. Case(); String lower = message. to. Lower. Case(); char letter = message. char. At(2); int string. Size = message. length(); System. out. println(message); System. out. println(upper); System. out. println(lower); System. out. println(letter); System. out. println(string. Size);

Scope o The variable scope is the part of the program that has access

Scope o The variable scope is the part of the program that has access to it public class Scope { public static void main(String[] args) { System. out. println(value); // ERROR! int value = 100; } }

Scope public class Scope { public static void main(String[] args){ int number = 100;

Scope public class Scope { public static void main(String[] args){ int number = 100; System. out. println(number); int number = 200; //ERROR } }

Comments o Java provides three methods for commenting code. // Single line comment. Anything

Comments o Java provides three methods for commenting code. // Single line comment. Anything after the // on the line will be ignored by the compiler. /* … */ Block comment. Everything beginning with /* and ending with the first */ will be ignored by the compiler. This comment type cannot be nested. /** … */ Javadoc comment. This is a special version of the previous block comment that allows comments to be documented by the javadoc utility program. Everything beginning with the /** and ending with the first */ will be ignored by the compiler. This comment type cannot be nested.

Programming Style o o Although Java has a strict syntax, whitespace characters are ignored

Programming Style o o Although Java has a strict syntax, whitespace characters are ignored by the compiler. The Java whitespace characters are: n n n space tab newline carriage return form feed

Programming Style public class Compact {public static void main(String[] args){int shares=220; double average. Price=14.

Programming Style public class Compact {public static void main(String[] args){int shares=220; double average. Price=14. 67; System. out. println("There were "+shares+" shares sold at $"+average. Price+ " per share. "); }} Compiles !!!

Indentation o o o Programs should use proper indentation. Each block of code should

Indentation o o o Programs should use proper indentation. Each block of code should be indented a few spaces from its surrounding block. Two to four spaces are sufficient

Programming Style /** This example is much more readable than Compact. java. */ public

Programming Style /** This example is much more readable than Compact. java. */ public class Readable { public static void main(String[] args) { int shares = 220; double average. Price = 14. 67; System. out. println("There were " + shares + " shares sold at $" + average. Price + " per share. "); } }

Dialog Boxes o o o A dialog box is a small graphical window that

Dialog Boxes o o o A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes can be displayed using the JOption. Pane class. Two of the dialog boxes are: n n Message Dialog - a dialog box that displays a message. Input Dialog - a dialog box that prompts the user for input.

Using the import Statement o o The JOption. Pane class is not automatically available

Using the import Statement o o The JOption. Pane class is not automatically available to your Java programs. The following statement must be before the program’s class header: import javax. swing. JOption. Pane; o This statement tells the compiler where to find the JOption. Pane class.

Dialog Boxes The JOption. Pane class provides static methods to display each type of

Dialog Boxes The JOption. Pane class provides static methods to display each type of dialog box.

Message Dialogs o JOption. Pane. show. Message. Dialog method is used to display a

Message Dialogs o JOption. Pane. show. Message. Dialog method is used to display a message dialog. JOption. Pane. show. Message. Dialog(null, "Hello World"); o The second argument is the message that is to be displayed.

Input Dialogs o o An input dialog is a quick and simple way to

Input Dialogs o o An input dialog is a quick and simple way to ask the user to enter data. The dialog displays a text field, an Ok button and a Cancel button. If Ok is pressed, the dialog returns the user’s input. If Cancel is pressed, the dialog returns null.

Input Dialogs String name; name = JOption. Pane. show. Input. Dialog( "Enter your name.

Input Dialogs String name; name = JOption. Pane. show. Input. Dialog( "Enter your name. "); o o o The argument passed to the method is the message to display. If the user clicks on the OK button, name references the string entered by the user. If the user clicks on the Cancel button, name references null.

Names. Dialog. java import javax. swing. JOption. Pane; public class Names. Dialog { public

Names. Dialog. java import javax. swing. JOption. Pane; public class Names. Dialog { public static void main(String[] args) { String first. Name; // The user's first name String middle. Name; // The user's middle name String last. Name; // The user's last name // Get the user's first name first. Name = JOption. Pane. show. Input. Dialog("What is " + "your first name? ");

Names. Dialog. java // Get the user's middle name. middle. Name = JOption. Pane.

Names. Dialog. java // Get the user's middle name. middle. Name = JOption. Pane. show. Input. Dialog( "What is " + "your middle name? "); // Get the user's last name. last. Name = JOption. Pane. show. Input. Dialog("What is " + "your last name? ");

Example // Display a greeting JOption. Pane. show. Message. Dialog(null, "Hello " + first.

Example // Display a greeting JOption. Pane. show. Message. Dialog(null, "Hello " + first. Name + " " +middle. Name + " " + last. Name); System. exit(0); } }

The System. exit() Method o o o A program that uses JOption. Pane does

The System. exit() Method o o o A program that uses JOption. Pane does not automatically stop executing when the end of the main method is reached. Java generates a thread, which is a process running in the computer, when a JOption. Pane is created. If the System. exit method is not called, this thread continues to execute.

The System. exit() Method o The System. exit method requires an integer argument. System.

The System. exit() Method o The System. exit method requires an integer argument. System. exit(0); o o This argument is an exit code that is passed back to the operating system. This code is usually ignored, however, it can be used outside the program: n n to indicate whether the program ended successfully or as the result of a failure. The value 0 traditionally indicates that the program ended successfully.

Converting a String to a Number o o The JOption. Pane’s show. Input. Dialog

Converting a String to a Number o o The JOption. Pane’s show. Input. Dialog method always returns the user's input as a String containing a number, such as “ 127. 89, can be converted to a numeric data type.

The Parse Methods o o Parse methods convert strings to numeric data types They

The Parse Methods o o Parse methods convert strings to numeric data types They are: n Byte. parse. Byte n Integer. parse. Int n Short. parse. Short n Long. parse. Long n Float. parse. Float n Double. parse. Double

The Parse Methods- Examples o o o byte b. Var = Byte. parse. Byte("1");

The Parse Methods- Examples o o o byte b. Var = Byte. parse. Byte("1"); int i. Var = Integer. parse. Int("2599"); short s. Var = Short. parse. Short("10"); long l. Var = Long. parse. Long("15908"); float f. Var = Float. parse. Float("12. 3"); double d. Var = Double. parse. Double("7945. 6");

Payroll. Dialog. java import javax. swing. JOption. Pane; public class Payroll. Dialog { public

Payroll. Dialog. java import javax. swing. JOption. Pane; public class Payroll. Dialog { public static void main(String[] args) { String input. String; // For reading input String name; // The user's name int hours; // The number of hours worked double pay. Rate; // The user's hourly pay rate double gross. Pay; // The user's gross pay

Payroll. Dialog. java // Get the user's name = JOption. Pane. show. Input. Dialog("What

Payroll. Dialog. java // Get the user's name = JOption. Pane. show. Input. Dialog("What is " + "your name? "); // Get the hours worked. input. String = JOption. Pane. show. Input. Dialog( "How many hours” + “ did you work this week? "); // Convert the input to an int. hours = Integer. parse. Int(input. String);

Payroll. Dialog. java // Get the hourly pay rate. input. String = JOption. Pane.

Payroll. Dialog. java // Get the hourly pay rate. input. String = JOption. Pane. show. Input. Dialog("What is” + " your hourly pay rate? "); // Convert the input to a double. pay. Rate = Double. parse. Double(input. String); // Calculate the gross pay. gross. Pay = hours * pay. Rate;

Payroll. Dialog. java // Display the results. JOption. Pane. show. Message. Dialog(null, "Hello "

Payroll. Dialog. java // Display the results. JOption. Pane. show. Message. Dialog(null, "Hello " + name + ". Your gross pay is $" + gross. Pay); // End the program. System. exit(0); } }