02slide_2007 - Chapter 2 Primitive Data Types and...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 2 Primitive Data Types and Operations EE3206/EE5805 Java Programming & Application 1 Objectives To write programs to perform simple calculations. To To use identifiers to name variables, constants, methods, and To classes. To use variables to store data. To To program with assignment statements and assignment To expressions. To use constants to store permanent data. To To declare Java primitive data types: byte, short, int, long, float, To double, and char. To use Java operators to write expressions. To To represent a string using the String type. To To obtain input using the JOptionPane input dialog boxes. To To obtain input from console. To To become familiar with Java documentation, programming To style, and naming conventions. To distinguish syntax errors, runtime errors, and logic errors. To To debug logic errors with debugger utilities. To EE3206/EE5805 Java Programming & Application 2 Identifiers An identifier is a sequence of characters that An consist of letters, digits, underscores (_), and dollar signs ($). An identifier cannot start with a digit. An An identifier cannot be a reserved word. An An identifier cannot be true, false or null. An true false null An identifier can be of any length. An Legal identifiers Legal • _2numberOfRow, $person, anyNumberOfLetter Illegal identifiers Illegal • 2numberOfRow, public EE3206/EE5805 Java Programming & Application 3 8 Primitive Data Types float is good for 7 significant digits of accuracy double is good for 15 significant digits accuracy •Java also provides more high level data types (reference types) for more complicated software model, i.e. class •The wrapper is the object replacement for the primitive data type. It encapsulates the data together with some methods. EE3206/EE5805 Java Programming & Application 4 Declare and Initialize Variables Declaration: datatype varName; datatype Assignment: varName = value; varName Initialization: datatype varName = value; datatype Examples: int x; x = 1; double d = 1.4; char ch1, ch2; // declare x to be an integer variable // assign 1 to x; // initialize d to 1.4 // declare ch1 and ch2 as a character EE3206/EE5805 Java Programming & Application 5 Constants General Format: General final datatype CONSTANTNAME = VALUE; Example: Example: final double PI = 3.14159; final int SIZE = 3; The keyword final The final to modify a class will be discussed can also be used or method. This in later chapters. 6 EE3206/EE5805 Java Programming & Application Numeric Operators Name + * / % Meaning Addition Subtraction Multiplication Division Remainder Example 34 + 1 34.0 – 0.1 300 * 30 1.0 / 2.0 20 % 3 Result 35 33.9 9000 0.5 2 Calculations involving floating-point numbers are approximated Calculations because these numbers are not stored with complete accuracy. • • System.out.println(1.0 - 0.9); displays 0.09999999999999998, not 0.1. EE3206/EE5805 Java Programming & Application 7 Calculations with integers yield a precise integer result. Calculations Literals A literal is a constant value that appears directly in the program. literal To denote an integer literal of the long type, append it with the To letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one). By default, a floating-point literal is treated as a double type By value. For example, 5.0 is considered a double value, not a float value. To make a number a float by appending the letter f or F, and To make a number a double by appending the letter d or D. Floating-point literals can also be specified in scientific notation with Floating E as an exponent. E can be either in lowercase or uppercase. int i = 34; int long x = 1000000L; double d = 5.0D; Byte b = 1000; float f = 100.2f float s = 1.2345e-2 EE3206/EE5805 Java Programming & Application // compilation error // 0.012345 8 Combinative Operators Shortcut Assignment Operators Operator += -= *= /= %= Example i += 8 f -= 8.0 i *= 8 i /= 8 i %= 8 Equivalent i=i+8 f = f - 8.0 i=i*8 i=i/8 i=i%8 Increment and Decrement Operators Operator ++var var++ --var var-Name preincrement postincrement predecrement postdecrement Description The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. The expression (var++) evaluates to the original value in var and increments var by 1. The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. The expression (var--) evaluates to the original value in var and decrements var by 1. EE3206/EE5805 Java Programming & Application 9 Increment and Decrement Operators int i = 10; int newNum = 10 * i++; Same effect as int newNum = 10 * i i = i + 1; int i = 10; int newNum = 10 * (++i); Same effect as i = i + 1; int newNum = 10 * i; Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. EE3206/EE5805 Java Programming & Application 10 10 Type Widening When performing a binary operation involving two operands of When different types, Java automatically converts/promotes the operand of smaller range to the type of larger range. This is done automatically and hence it is called implicit casting. This implicit Conversion of int or long value to float or double, may result in Conversion int long float double loss of precision. The result may lose some of the least significant bits of the value. byte b = 5; int i = b + 1000; double d = 1000; // byte to int // int to double, lossy range increases byte, short, int, long, float, double EE3206/EE5805 Java Programming & Application 11 11 Type Narrowing Sometimes operands are converted from larger range to a Sometimes type of smaller range. This leads to truncation of some least significant bits and errors. Programmers have to force casting of variables explicitly, Programmers hence it is called explicit casting. int i int i float int x = = f = (int)3.0; (int)3.9; = 2.3; 5 / 2.0; // // // // type narrowing Fraction part is truncated error, why? error, why? Both 2.3 and 2.0 are literals of double type EE3206/EE5805 Java Programming & Application 12 12 Character Data Type Java characters use Unicode, a 16-bit encoding scheme Unicode char letter = 'A'; char numChar = '4'; char letter = '\u0041'; char numChar = '\u0034'; //ASCII //ASCII //Unicode 0041 //four hexadecimal digits In Java, characters can be manipulated as numbers. This is done by performing arithmetic operations on the unicode of the character. char ch = 'a'; System.out.println(++ch); int i = ‘1’ + ‘1’; char a = 48; // printing letter b // 49+49 = 98 // unicode of ‘0’ is 48 13 13 EE3206/EE5805 Java Programming & Application Escape Sequences for Special Characters Description Backspace Tab Linefeed Escape Sequence \b \t \n Unicode \u0008 \u0009 \u000A \u000D \u005C \u0027 \u0022 Carriage return \r Backslash Single Quote Double Quote \\ \' \" EE3206/EE5805 Java Programming & Application 14 14 ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f EE3206/EE5805 Java Programming & Application 15 15 The String Type •In contrast to C where string is represented by a character array, Java uses the type String to store a string. String to • The String type is not a primitive type. It is known as a reference type or a class. reference class •String can be concatenated with other types String message = "Welcome"; // “Welcome” is a string literal // 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'; // s becomes SupplementB EE3206/EE5805 Java Programming & Application 16 16 Getting Input Similar to showMessageDialogue(), JOptionPane provides another Similar method showInputDialogue() to get input. String s = JOptionPane.showInputDialog(null, x, y, JOptionPane.QUESTION_MESSAGE)); or String s = JOptionPane.showInputDialog(x); where x is a string for the prompting message, and y is a string for the title of the input dialog box. EE3206/EE5805 Java Programming & Application 17 17 Converting Strings to Other Types The input returned from the input dialog box is a string. If you The enter a numeric value such as 123, it returns a string of “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into a number value, you can use the To static method from the corresponding wrapper class: // e.g. intString is a numeric string “123” int intValue = Integer.parseInt(intString); // e.g. floatString is a numeric string “123.21” float floatValue =Float.parseFloat(floatString); // e.g. doubleString is a numeric string “123.21” double doubleValue =Double.parseDouble(doubleString); EE3206/EE5805 Java Programming & Application 18 18 Getting Input Using Scanner •Alternatively, you may get input from console by 2 steps 1. Create a Scanner object Scanner scanner = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, System.out.print("Enter a double value: "); Scanner scanner = new Scanner(System.in); double d = scanner.nextDouble(); TestScanner EE3206/EE5805 Java Programming & Application 19 19 Programming Style and Documentation Appropriate Comments Appropriate Naming Conventions Naming Proper Indentation and Spacing Lines Proper Block Layout Block EE3206/EE5805 Java Programming & Application 20 20 Appropriate Comments Include a summary at the beginning of the Include program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. For our coursework, include your name, student For ID, class section, instructor, date, and a brief description at the beginning of the program. EE3206/EE5805 Java Programming & Application 21 21 Naming Conventions Choose meaningful and descriptive names. Choose Variable and Method names (Lower Camel Case) Variable • Start with lowercase and capitalize every first letter of each subsequent word. • radius, outerArea, computeArea, getLocalPoint. Class names (Upper Camel Case) Class • Capitalize the first letter of each word in the name. • GameScreen, ControllerButton Constants Constants • Capitalize all letters in constants, and use underscores to connect words. • PI, MAX_VALUE EE3206/EE5805 Java Programming & Application 22 22 Proper Indentation, Spacing and Block Layout Indentation Indentation Spacing Spacing • Indent two spaces. • Use blank line to separate segments of the code. Block Layout Block • Use end-of-line style for braces. Next-line style public class Test { public static void main(String args) { System.out.println("Block Styles"); } } End-of-line style public class Test { public static void main(String args) { System.out.println("Block Styles"); } } 23 23 EE3206/EE5805 Java Programming & Application Programming Errors Syntax Errors Syntax • Detected by the compiler Runtime Errors Runtime • Causes the program to abort during execution Logic Errors Logic • Produces incorrect result EE3206/EE5805 Java Programming & Application 24 24 Syntax Errors and Runtime Errors public class ShowSyntaxErrors { public static void main(String args) { i = 30; System.out.println(i + 4); } } public class ShowRuntimeErrors { public static void main(String args) { int i = 1 / 0; } } EE3206/EE5805 Java Programming & Application 25 25 Logic Errors public class ShowLogicErrors { // Determine if a number is between 1 and 100 inclusively public static void main(String args) { // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, "Please enter an integer:", "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); int number = Integer.parseInt(input); // Display the result System.out.println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.exit(0); } } EE3206/EE5805 Java Programming & Application 26 26 Debugging with Debugger Logic errors are called bugs. The process of finding Logic bugs and correcting errors is called debugging. A debugger utility can help you effectively find out debugger and correct bugs. You can use a debugger to • • • • • • Execute a single statement at a time Trace into or stepping over a method or loop Set breakpoints Display variables Display call stack Modify variables You will exercise these tools during the tutorial class. You EE3206/EE5805 Java Programming & Application 27 27 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online