Chapter 2 Java Fundamentals 1 Contents 1. The Parts of a Java Program 2. The print and println Methods, and the Java API 3. Variables and Literals 4. Primitive Data Types 5. Arithmetic Operators 6. Combined Assignment Operators 7. Conversion between Primitive Types 8. Creating Named Constraints with final 2 Contents 9. The String Class 10.Scope 11.Comments 12.Programming Style 13.Reading Keyboard Input 14.Dialog Box 3 1. The Parts of a Java Program Problem Write a Java program to display a message (Programming is great fun!) on the screen. 4 1. The Parts of a Java Program (Cont’d) Run eclipse Create a new Java project Enter the project name: MyFirstProject Create a new Java class: Enter the class name: Simple This will create a source code file Simple.java Enter the code 5 1. The Parts of a Java Program (Cont’d) 6 1. The Parts of a Java Program (Cont’d) Run the program 7 1. The Parts of a Java Program (Cont’d) Line 1: //This is a simple Java program // : marks the beginning of a comment. The compiler ignores everything from the double-slash to the end of the line. You can type anything you want. Comments help explain what’s going on. 8 1. The Parts of a Java Program (Cont’d) Line 2: A blank line Programmers often insert blank lines in programs to make them easier to read. Line 3: public class Simple This is a class header, and it marks the beginning of a class definition. 9 1. The Parts of a Java Program (Cont’d) A Java program must have at least one class definition. public: public is a Java keyword must be written in all lowercase letters public is an access specifier, and it controls where the class may be accessed from. The public specifier means access to the class is unrestricted (the class is “open to the public”). 10 1. The Parts of a Java Program (Cont’d) class: a Java keyword, must be written in lowercase letter. indicates the beginning of a class definition. Simple: Simple is the class name which is made up by the programmer. Programmer-defined names may be written in lowercase letters, uppercase letters, or a mixture of both. 11 1. The Parts of a Java Program (Cont’d) public class Simple tell the compiler that a public accessible class named Simple is being defined. We can create more than one class in a file, but we may only have one public class per Java file. When a Java file has a public class, the name of the public class must be the same as the name of the file (without the .java extension). Java is a case-sensitive language. Public ≠ public ≠ puBlic ≠ pUblic … 12 1. The Parts of a Java Program (Cont’d) Line 4: { is a left brace, or an opening brace, and is associated with the beginning of the class definition. All programming statements that are parts of class are enclosed in a set of braces. In line 9, we will have the closing brace. Everything between the two braces is the body of the class named Simple. 13 1. The Parts of a Java Program (Cont’d) 14 1. The Parts of a Java Program (Cont’d) Line 5: Name of the method public static void main(String[] args) a method header, the beginning of a method. main is a name of the method. Every Java program must have a method named main. The main method is the starting point of an application. 15 1. The Parts of a Java Program (Cont’d) Line 6: { This opening brace belongs to the main method. Every opening brace must have a accompanying closing brace. We will have a closing brace in line 8 that corresponds with this opening brace. Everything between these braces is the body of the main method. 16 1. The Parts of a Java Program (Cont’d) Line 7: System.out.println("Programming is great fun!"); This line is a statement. It displays a message on the screen. The message, “Programming is great fun!”, is printed without the quotation marks. The group of characters inside the quotation marks is called a string literal. There is a semicolon at the end of this line. Semicolon marks end of a statement in Java. 17 1. The Parts of a Java Program (Cont’d) Not every line of code ends with a semicolon: Comments do not have to end with a semicolon Class headers and method headers do not end with a semicolon. The brace characters, { and }, are not statements, so we do not place a semicolon after them. Lines 8 and 9 contain the closing braces for main method and the class definition. 18 1. The Parts of a Java Program (Cont’d) Java is a case-sensitive language. All Java program must be stored in a file with a name that ends with .java Comments are ignored by the compiler. A .java file may contain many classes, but may only have one public class. If a .java file has a public class, the class must have the same name as the file. 19 1. The Parts of a Java Program (Cont’d) Every Java application program must have a method named main. For every brace, or opening brace, there must be a corresponding right brace, or closing brace. Statements are terminated with semicolons. This does not include comments, class headers, method headers, or braces. 20 2. The print and println Methods, and Java API The print and println methods are used to display text output. are parts of the Java API (Application Programmer Interface). API is a collection of prewritten classes and methods for performing specific operations. The console Standard output: the monitor Standard input: the keyboard 21 2. The print and println Methods, and Java API System.out.println("Programming is great fun!"); Hierarchical Relationship among the System class, the out object, and the print and println methods 22 2. The print and println Methods, and Java API The System class is part of the java API. It has member objects and methods for performing system-level operations, such as sending output to the console. The out object is a member of the System class. It provides methods for sending output to the screen. The print and println methods are members of the out object. They actually perform the work of writing characters on the screen. We use the period to separate System, out and print or println. The period is pronounced “dot”. 23 2. The print and println Methods, and Java API The value that is to be displayed on the screen is places inside the parentheses. This value is known as an argument. System.out.println(“King Arthur”); The println method is that after it displays its message, it advances the cursor to the beginning of the next line. 24 2. The print and println Methods, and Java API 25 The print Method The print method part of the System.out object. serves a purpose to display output on the screen. does not advance the cursor to the next line after its message is displayed. 26 The print Method 27 The print Method 28 The print Method There are two ways to fix the Unruly program: use println method ? use escape sequences to separate the output into different lines An escape sequence starts with the blackslash character (\), and is followed by one or more control characters. The escape sequence that causes the output cursor to go to the next line is \n \n is called the newline escape sequence. 29 The print Method 30 The print Method 31 Common Escape Sequences See table 2-2 \n \t \b \r \\ \’ \” New line Horizontal Tab backspace Return Backslash Single quote Double quote 32 3. Variables and Literals A variable is a named storage location in the computer’s memory. A literal is a value that is written into the code of a program. 33 3. Variables and Literals (Cont’d) 34 3. Variables and Literals (Cont’d) Line 7: variable’s name int value; data type Variable declaration Variables must be declared before they can be used. A variable declaration tells the compiler the variable’ name the type of data the variable will hold 35 3. Variables and Literals (Cont’d) Line 9: value=5; Assignment statement The equal sign = is an operator that stores the value on its right (5) into the variable named on its left (value). After this line executes, the value variable will contain the value 5. 36 3. Variables and Literals (Cont’d) 37 3. Variables and Literals (Cont’d) Line 11: System.out.println(value); The method println will display the variable’s contents on the console. There are no quotation marks around variable value Compare with System.out.println(“value”); 38 Display Multiple Items with the + Operator The + operator is used with strings: String concatenation operator System.out.println(“This is ” + “one string.”); This is one string. The + operator can be used to concatenate the contents of a variable to a string number = 5; System.out.println(“The value is ” + number); The value is 5 39 Display Multiple Items with the + Operator (Cont’d) A string literal cannot begin on one line and end on another Error System.out.println(“Enter a value that is greater than zero and less than 10.”); Breaking the argument up into smaller string literals, and use the + operator System.out.println(“Enter a value that” + “ is greater than zero and less “ + “than 10.”); 40 Display Multiple Items with the + Operator (Cont’d) 41 Identifiers Identifier A programmer-defined name. Do not use any of the Java keywords for identifiers. Represents some element of a program. Variable names, class names, name of methods, … 42 Identifiers (Cont’d) Should choose names that give an indication of what they are used for, what the purpose is For example Number of ordered items int x; int itemsOrdered; not good 43 Identifiers (Cont’d) There are some rules with all identifiers: The first character must be one of the letters a-z, A-Z, _, $ After the first character, we can use letters a-z, A-Z, digits 0-9, _, $ Uppercase and lowercase characters are distinct. Identifiers cannot include spaces 44 Identifiers (Cont’d) Variable Name Legal or Illegal ? dayOfWeek Legal 3dGraph Illegal june1997 Legal mixture#3 Illegal week day Illegal 45 Identifiers (Cont’d) Variable Names It is standard practice to begin variable names with a lowercase letter Capitalize the first the first letter of each subsequent word. int itemOdered; 46 Identifiers (Cont’d) Class Names It is standard practice to begin variable names with a uppercase letter Capitalize the first letter of each subsequent word. public class PayRoll 47 4. Primitive Data Types Each variable has a data type, which is the type of data that the variable can hold. Selecting the proper type for variables is important amount of memory the way the variable formats and stores data 48 4. Primitive Data Types (Cont’d) Primitive data types for numeric data Integer Data Types FloatingPoint Data Types Data Type Size Range byte 1 byte Integers in the range of -128 to +127 short 2 bytes Integers in the range of -32,768 to +32,767 int 4 bytes Integers in the range of -2,147,483,648 to +2,147,483,647 long 8 bytes Integers in the range of -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 float 4 bytes Floating-point numbers in the range of ±3.4×10-38 to ±3.4×1038 , with 7 digits of accuracy double 8 bytes Floating-point numbers in the range of ±1.7×10-308 to ±1.7×10308 , with 15 digits of accuracy 49 4. Primitive Data Types (Cont’d) General format of a variable declaration DataType VariableName; DataType : name of the data type VariableName : name of the variable Examples: byte inches; int speed; short month; float salesComission; double distances; 50 4. Primitive Data Types (Cont’d) Combining variables of the same data type int length; int width; int area; int length, width, area; 51 Integer Literals Do not embed commas in numeric literals. int number; number = 1,257,649; number = 1257649; //ERROR ! We can force an integer literal to be treated as long 57 57L, 57l be treated as int value be treated as long values 52 Floating-Point Literals Java assumes floating-point literals such as 29.75, 1.76, … to be of double data type. float number; number = 25.5; //Error ! float number; number = 25.5F; number = 25.5f; 53 Scientific and E Notation Floating-point literals can be represented in scientific notation. 47,281.97 4.728197×104 Java uses E notation to represent values in scientific notation. Decimal Notation Scientific Notation E Notation 247.91 2.4791×102 2.4791E2 0.00072 7.2×10-4 7.2E-4 2,900,000 2.9×106 2.9E6 54 The boolean Data Type The boolean data type allows us to create variables that hold one of two possible values: true false Variables of boolean data type are useful for evaluation conditions that are either true or false. 55 The boolean Data Type (Cont’d) 56 The char Data Type The char data type is used to store characters. A variable of the char data type can hold one character at a time. Character literals ‘A’, ‘B’, ‘a’, ‘s’, … Characters are internally represented by numbers (Unicode) ‘A’ : 65 ‘B’: 66 … 57 The char Data Type (Cont’d) Characters and how they are stored in memory 58 The char Data Type (Cont’d) 59 The char Data Type (Cont’d) 60 Variable Assignment and Initialization Variable assignment Using = assignment operator The operand on the left side of the = operator must be a variable. The value in right side of the = operator is assigned to the variable in left side. int unitSold; unitSold = 12; 12 = unitSold; //ERROR ! 61 Variable Assignment and Initialization (Cont’d) Initialization We may also assign values to variables as part of the declaration statement int month = 2, days = 28; int flightNum = 89, travelTime, departure = 10; 62 Variables Hold Only One Value at a Time A variable can hold only one value at a time. When we assign a new value to a variable, the new value replaces the variable’s previous contents. 63 5. Arithmetic Operator There are three types of operators: Unary Requires only a single operand -5 (negative operator) Binary -number Requires two operands Ternary Requires three operands 64 5. Arithmetic Operator (Cont’d) Common operators Operator Meaning Type Example + Addition Binary total = cost + tax; - Subtraction Binary cost = total – tax; * Multiplication Binary tax = cost * rate; / Division Binary salePrice = original / 2; % Modulus Binary remainder = value % 3; 65 Integer Division When both operands of a division statement are integers, the statement will result in integer division. The result of the integer division will be an integer. double parts; double parts; parts = 17 / 3; parts = 17.0 / 3; parts is assigned the value 5.0 parts is assigned the value 5.666666666667 66 Operator Precedence Precedence of arithmetic operators (highest to lowest) - (unary negation) * / % + outcome = 12 + 6 / 3 = 12 + 2 = 14 67 Operator Precedence (Cont’d) Associativity of arithmetic operators Operator Associativity - (unary negation) Right to left */% Left to right +- Left to right Expression Value 5+2*4 10 / 2 – 3 8 + 12 * 2 – 4 4 + 17 % 2 – 1 6–3*2+7–1 68 Grouping with Parentheses To force some operations to be performed before others Expression Value (5 + 2) * 4 10 / (5 – 3) 8 + 12 * (6 – 2) (4 + 17) % 2 – 1 69 The Math class Math class is a member of Java API. The Math.pow method Rising a number to a power result = Math.pow(4.0, 2.0); // 42 The Math.sqrt method accepts a double value as its argument and returns the square root of the value. result = Math.sqrt(9.0); // 9.0 70 6. Combined Assignment Operators The combined assignment operators combine the assignment operator with the arithmetic operators. x += 5; equivalent to x = x + 5; 1. Add 5 to x 2. The resut is then assigned to x 71 6. Combined Assignment Operators (Cont’d) Combined assignment operators Operator Example Usage Equivalent To += x += 5; x = x + 5; -= y -= 2; y = y – 2; *= z *= 10; z = z * 10; /= a /= b; a = a / b; %= c %= 3; c = c % 3; 72 7. Conversion between Primitive Data Types Before a value can be stored in a variable, the value’s data type must be compatible with the variable’s data type. Java performs some conversions between data types automatically, but does not perform any conversion that can result in the loss of data; 73 7. Conversion between Primitive Data Types (Cont’d) int x; double y = 2.5; x = y; //ERROR ! Possible loss precision int x; short y = 2; x = y; // OK 74 7. Conversion between Primitive Data Types (Cont’d) In assignment statements where values of lowerranked data types are stored in variables of hight-ranked data types, Java automatically converts the lower-ranked value to the higherranked type. (widening conversion) Primitive data type ranking double float long int short byte Highest Rank double x; int y = 10; x = y; //widening conversion Lowest Rank 75 Cast Operators A narrowing conversion is the conversion of a value to a lower-ranked type. Narrowing conversions can cause a loss of data, Java does not automatically perform them. The cast operator lets you manually convert a value, even if it is a narrowing conversion. 76 Cast Operators (Cont’d) Cast operators are unary operators that appear as a data type name enclosed in a set of parentheses. int x; double y = 2.5; x = (int)y; // x = 2; cast operator 77 Cast Operators (Cont’d) int pie = 10, people = 4; double piesPerPerson; piesPerPerson = pie / people; 2.0 piesPerPerson = (double)pie / people; piesPerPerson = pie / (double)people; 2.5 2.5 piesPerPerson = (double)(pie / people); 2.0 78 Mixed Integer Operations With arithmetic operations on int, byte, and short variables: Values of the byte or short data types are temporarily converted to int value. The result will always be an int. short x = 10, y = 20, z; z = x + y; //causes an error x + y results an int number 79 Other Mixed Mathematical Expressions 1. If one of an operator’s operands is a double, the value of the other operand will be converted to a double. The result of the expression will be a double. 2. If one of an operator’s operands is a float, the value of the other operand will be converted to a float. The result of the expression will be a float. 3. If one of an operator’s operands is a long, the value of the other operand will be converted to a long. The result of the expression will be a long. 80 8. Creating Named Constants with final The final keyword can be used in a variable declaration to make the variable a named constant. Named constants are initialized with a value, and that value cannot change during the execution of the program 81 8. Creating Named Constants with final (Cont’d) amount = balance * 0.069; Interest rate final double INTEREST_RATE = 0.069; amount = balance * INTEREST_RATE; The Math.PI Named Constant is assigned the value 3.1415926535897323845 is an approximation of the mathematical value pi. area = Math.PI * radius * radius; 82 9. The String Class String literals are enclosed in double quotation marks. “Hello World” “Joe Mahoney” Java does not have a primitive data type for storing strings in memory. The String class Allows you to create objects for holding strings. Has various methods that allow you to work with strings. 83 9. The String Class (Cont’d) Objects are created from classes. Declare a variable of the String class String name; A class type variable does not hold the actual data item. It holds the memory address of the data item. name is a class type variable, holds the memory address of a String object. When a class type variable holds the address of an object, it is said that the variable references the object. Class type variables are known as reference variables. 84 9. The String Class (Cont’d) Creating a String object String name; name = “Joe Mahoney”; String object is created in memory with the value “Joe Mahoney” stored in it. The address of that object is stored in the name variable. 85 9. The String Class (Cont’d) Class type variables String name; name = “Joe Mahoney”; Primitive type variables int number; number = 25; 86 9. The String Class (Cont’d) 87 9. The String Class (Cont’d) String provides numerous methods for working with strings. To call a method means to execute it. ReferenceVariable.method(arguments…) String name; name = “Tony Gaddis”; int stringSize; stringSize = name.length(); length method of String is called 88 A few String class methods charAt(index) index is an int value and specifies a character position in the string. The first character in the string is at position 0. The method return the character at the index position. length() Returns the number of characters in the string. 89 A few String class methods toLowerCase() Returns a new string that is the lowercase equivalent of the string contained in the calling method. toUpperCase() Returns a new string that is the uppercase equivalent of the string contained in the calling method. 90 A few String class methods 91 10. Scope Every variable has a scope. A variable’s scope is the part of the program that has access to the variable. Variables can not be accessed by statements that are outside the scope. Variables that are declared inside a method are called local variables. 92 10. Scope (Cont’d) A local variable’s scope begins at the variable’s declaration and ends at the end of the method in which the variable is declared. 93 10. Scope (Cont’d) We can not have two local variables with the same name in the same scope. 94 11. Comments Comments are notes of explanation. Comments are parts of the program, but the compiler ignores them. They are intended for people who may be reading the source code Documented programs will make your life easier. 95 11. Comments (Cont’d) Three ways to comment in Java Single-line comments Using two forward slashes // Everything from // to the end of the line is ignored. Multi-line comments Multi-line comments start with /* and end with */. Everything between /* and */ is ignored. 96 11. Comments (Cont’d) Documentation Comments Documentation comments can be read and processed by a program named javadoc. The javadoc program reads Java source code files and generates HTML files that document the source code. If the source code files contain any documentation comments, the information in the comments becomes part of the HTML documentation. 97 11. Comments (Cont’d) Any comment that starts with /** and ends with */ is considered a documentation comments. Normally we write a documentation comment before a class header, giving brief description of the class before a method header, giving brief description of the method. Run javadoc javadoc SourceFile.java 98 11. Comments (Cont’d) Generating javadoc in eclipse Project \Generate Javadoc … Enter Javadoc command C:\Program Files\Java\jdk1.6.0_10\bin\javadoc.exe Use standard doclet 99 12. Programming Style Programming Style refers to the way a programmer uses Spaces, Indentations, Blank lines, Punctuations to arrange a program’s source code. This program is syntactically correct and is very difficult to read: 100 12. Programming Style (Cont’d) 101 12. Programming Style (Cont’d) A common programming style is to indent all lines inside a set of braces To handle statements that are too long to fit in one line: Extra spaces are inserted at the beginning of statement’s second, third … lines, which indicate that they are continuations. 102 12. Programming Style (Cont’d) Extra spaces Extra spaces 103 12. Programming Style (Cont’d) Declaration of multiple variables of the same type with a single statement To write each variable name on a separate line with a comment explaining the variable’s purpose. int fahrenheit, centigrade, kelvin; //Fahrenheit temperature //Centigrade temperature //Kelvin temperature 104 13. Reading Keyboard Input System.in is an object Standard input device Is used to read keystrokes Reads input only as byte values Is not very useful because programs normally requires values of other data types Objects of the Scanner class can be used to read input from the keyboard. Reads input from a source such as System.in Provides methods to retrieve the input formatted as primitive values or strings. 105 The Scanner object The Scanner class is not automatically available to Java programs. Using import statement to tell the compiler where in the Java library to find the Scanner class import statement must be placed near the beginning of the file, before any class definition import java.util.Scanner; 106 The Scanner object (Cont’d) Create the Scanner object and connect it to the System.in object. Scanner keyboard; keyboard = new Scanner(System.in); new a Java keyword is used to create an object in memory 107 The Scanner object (Cont’d) This declares a variable named keyboard . The variable can reference an object of the Scanner class. This creates a Scanner object in memory. The object will read input from System.in Scanner keyboard = new Scanner(System.in); The = operator assigns the address of the Scanner object to the keyboard variable. 108 The Scanner object (Cont’d) The Scanner class has methods for reading strings, bytes, integers, long integers, short integers, float and doubles. int number; Scanner keyboard; keyboard = new Scanner(System.in); System.out.println(“Enter an integer:”); number = keyboard.nextInt(); 109 The Scanner object (Cont’d) Some of the Scanner methods byte nextByte(): double nextDouble(): returns input as a double. float nextFloat(): returns input as a byte. returns input as a float. int nextInt(): returns input as an int. 110 The Scanner object (Cont’d) String nextLine(): long nextLong(): returns input as a String. returns input as a long. short nextShort(): returns input as a short. 111 The Scanner object (Cont’d) Problem: User’s gross pay Write a Java program to calculate the gross pay of a user. The program allows user to enter user’s name, hours worked, pay rate, and display the user’s gross pay on the console. 112 User’s gross pay Display “What is your name?”. Input user’s name. → Store in a variable Display “How many hours did you work?”. Input hours. → Store in a variable Display “How much do you get paid per hour?”. Input rate. → Store in a variable Calculate the user’s gross pay and store in a variable Display user’s name and gross pay 113 User’s gross pay 114 User’s gross pay 115 Reading a Character The Scanner class does not have a method for reading a single character. To read a single character using the Scanner class: 1. 2. Use the nextLine method of the Scanner class to read a string from the keyboard. Use the charAt method of the String class to extract the first character of the string. 116 Reading a Character (Cont’d) String input; char answer; //To hold a line of input // To hold a single character Scanner keyboard; keyboard = new Scanner(System.in); System.out.println(“Are you having fun? (Y/N)”); input = keyboard.nextLine(); // Get a line of input answer = input.charAt(0); // Get the first character 117 Mixing Calls to nextLine with calls to Other Scanner Methods When we call one of the Scanner class’s methods to read a primitive value, then call the nextLine method to read a string → The string is not read Because the Scanner class’s methods to read a primitive value left a newline character in the keyboard buffer. 118 Mixing Calls to nextLine with calls to Other Scanner Methods 119 Mixing Calls to nextLine with calls to Other Scanner Methods 120 Mixing Calls to nextLine with calls to Other Scanner Methods To fix the problem Insert the nextLine method to consume, or remove, the newline character that remains in the keyboard buffer. 121 14. Dialog Boxes A dialog box is a small graphical window that displays a message or requests input. The JOptionPane class allows you to quickly display a dialog box Display dialog: To display a message Input dialog: To request input 122 Display Message Dialogs The showMessageDialog method is used to display a message dialog JOptionPane.showMessageDialog(null, “Hello World”); 123 Display Input Dialog The showInputDialog method is used to display an input dialog String name; name = JOptionPane.showInputDialog(“Enter your name”); The name variable will reference the string value entered in the text field. Text field 124 Converting String Input to Numbers Because the showInputDialog method always returns the user’s input as a String, even if the user enters numeric data We must convert the input string to a numeric value if the string represents numeric data. 125 Converting String Input to Numbers (Cont’d) Methods for converting strings to numbers Byte.parseByte Convert a string to a byte byte num; Num = Byte.parseByte(str); Double.parseDouble Convert a string to a double 126 Converting String Input to Numbers (Cont’d) Float.parseFloat Integer.parseInteger Convert a string to an int Long.parseLong Convert a string to a float Convert a string to a long Short.parseShort Convert a string to a short 127 PayrollDialog Write the Payroll program using dialogs to get user’s input and display user’s information. 128 PayrollDialog 129 PayrollDialog 130 131