Chapter 2 Introduction to Java Applications Dr. Hikmat Jaber Computer Science Department 1 Printing a Line of Text /* This is a first program in Java Programming Language. The program prints a line of text on the output console. */ /** Java application should have at least one class */ public class LineOfText { // main method begins execution of Java application public static void main(String[] args) { System.out.println("Java is a powerful programming language"); } } 2 Comments Three types of comments in Java. Line comment: A line comment is preceded by two slashes (//) in a line. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple lines. javadoc comment: javadoc comments begin with /** and end with */. They are used for documenting classes, data, and methods. They can be extracted into an HTML file using JDK's javadoc command. 3 Literals A literal is a constant value (text or number) that appears directly in the program. For example, 34, "Enter your name", 'H', and 5.0 are literals. 4 String Literals A string literal is a constant text value enclosed between double quotation marks. Examples: "Enter your name " "The value of x is " 5 Number Literals A number literal is a constant numeric value. Examples: 34 -230 71.55 3509567 6 Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one). 7 Floating-Point Literals Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number. 8 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters System.out.printf("\u0065"); System.out.printf("%s%s","\u0065", "\u00F2"); 9 Escape Sequences Description Escape Sequence Backspace \b Tab \t Linefeed \n Carriage return \r Backslash \\ Single Quote \' Double Quote \" 10 Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. – An identifier cannot be a reserved word such as if, else, void, int, double, class, return, etc. An identifier cannot be true, false, or null. An identifier can be of any length. 11 Variables A variable is an identifier that its value may change. Examples: mark1, employee_Address, studentID, $age bookName, _length Declaring variables format : datatype variableName; 12 Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; 13 Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; 14 Declaring and Initializing in One Step int x = 1; double d = 1.4; 15 Constants A constant is an identifier that its value never changes. Declaring constants Format : final datatype CONSTANTNAME = VALUE; Examples: final double PI = 3.14159; final int SIZE = 3; 16 Primitive Data Types Numerical Data Types Name Range Storage Size byte –27 (-128) to 27–1 (127) 8-bit signed short –215 (-32768) to 215–1 (32767) 16-bit signed int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed long –263 to 263–1 (i.e., -9223372036854775808 to 9223372036854775807) 64-bit signed float Negative range: -3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38 32-bit IEEE 754 double Negative range: -1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308 64-bit IEEE 754 17 The boolean Data Type Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. Examples: boolean answer = true; boolean b = (1 > 2); 18 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) Four hexadecimal digits. char letter = '\u0041'; (Unicode) char numChar = '\u0034'; (Unicode) NOTE: The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; System.out.println(++ch); 19 The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library just like the System class and JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in “Objects and Classes.” For the time being, you just need to know how to declare a String variable, how to assign a string to the variable, and how to concatenate strings. 20 String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB 21 Memory Concepts Variable name corresponds to a memory location. Every variable has a name, a type, a size and a value. Example: int number number = 72 type size = 4 bytes 72 number name value 22 Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign (%). 23 Frequently-Used Specifiers Specifier Output Example %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" int count = 5; items double amount = 45.56; System.out.printf("count is %d and amount is %f", count, amount); display count is 5 and amount is 45.560000 24 Displaying Text in a Message Dialog Box you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.” 25 The showMessageDialog Method JOptionPane.showMessageDialog(null, "Welcome to Java!", "Display Message", JOptionPane.INFORMATION_MESSAGE); 26 Two Ways to Invoke the Method There are several ways to use the showMessageDialog method. For the time being, all you need to know are two ways to invoke it. One is to use a statement as shown in the example: JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE); where x is a string for the text to be displayed, and y is a string for the title of the message dialog box. The other is to use a statement like this: JOptionPane.showMessageDialog(null, x); where x is a string for the text to be displayed. 27 Introducing Programming with an Example This program computes the area of the circle. 28 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; allocate memory for radius radius no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 29 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; memory radius no value area no value allocate memory for area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 30 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; assign 20 to radius radius area 20 no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 31 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; memory radius area 20 1256.636 // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; compute area and assign it to variable area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 32 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; memory radius area 20 1256.636 // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; print a message to the console // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 33 Input Data This note provides two ways of obtaining input. 1. 2. Using the Scanner class (console input) Using JOptionPane input dialogs 34 Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDou ble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, d ou ble, or boolean valu e. For exam ple, System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextDouble(); ComputeAreaWithConsoleInput 35 Compute Area of a Rectangle using Console Input import java.util.Scanner; public class AreaRectangle { public static void main(String[] args) { int length, width, area; Scanner input = new Scanner (System.in); System.out.print("Enter the length: "); length = input.nextInt(); System.out.print("Enter the width: "); width = input.nextInt(); area = length*width; System.out.println("Length="+length+ " Width="+width+ " Area="+area); } } 36 JOptionPane Input Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input"); 37 Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE); 38 Compute Area of a Rectangle using Dialog Boxes Input import javax.swing.JOptionPane; public class AreaRectangle { public static void main(String[] args) { int length, width, area; String string; string = JOptionPane.showInputDialog(null, "Enter the length: ", "Input", JOptionPane.INFORMATION_MESSAGE); length = Integer.parseInt(string); string = JOptionPane.showInputDialog(null, "Enter the width: ", "Input", JOptionPane.INFORMATION_MESSAGE); width = Integer.parseInt(string); area = length*width; JOptionPane.showMessageDialog(null, "Area = "+area, "Display Area", JOptionPane.INFORMATION_MESSAGE); } } 39 Two Ways to Invoke the Method There are several ways to use the showInputDialog method. For the time being, you only need to know two ways to invoke it. One is to use a statement as shown in the example: String string = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE); where x is a string for the prompting message, and y is a string for the title of the input dialog box. The other is to use a statement like this: JOptionPane.showInputDialog(x); where x is a string for the prompting message. 40
© Copyright 2024