slide1.2_2009 - Module 1.2 Module 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: Module 1.2 Module Primitive Data Types and Operations Primitive EE3206/EE5805 Java Programming & Applications 1 Intended Learning Outcomes To recognize the form of identifiers. To program with variables and constants. To identify Java primitive data types and operators. To represent a string using the String type. To obtain input using the JOptionPane input dialog boxes and from console. To become familiar with Java documentation, programming style, and naming conventions. To distinguish types of error and identify the use of debugger utilities. EE3206/EE5805 Java Programming & Applications 2 Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). letters digits underscores (_), dollar ($). An identifier cannot start with a digit. An identifier cannot be a reserved word. An identifier cannot be true, false or null. true false or null An identifier can be of any length. An Legal identifiers Legal • _2numberOfRow, $person, anyNumberOfLetter _2numberOfRow, anyNumberOfLetter Illegal identifiers Illegal • 2numberOfRow, public EE3206/EE5805 Java Programming & Applications 3 8 Primitive Data Types •Each primitive type has a wrapper type that not only stores value but also provides operations on the data unit. •The wrapper is an OO counterpart for the primitive data type. EE3206/EE5805 Java Programming & Applications 4 Declare and Initialize Variables Declaration: Declaration: datatype varName; datatype Assignment: Assignment: varName = value; varName Initialization: Initialization: datatype varName = value; datatype Examples: int x; x; x = 1; 1; double d = 1.4; char ch1, ch2; char // 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 & Applications 5 Constants General Format: General final datatype CONSTANTNAME = VALUE; final datatype Example: Example: final double PI = 3.14159; final final int SIZE = 3; int The keyword final can also be used to modify a class or method. This will be discussed later. EE3206/EE5805 Java Programming & Applications 6 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 point because these numbers are not stored with complete accuracy. • • System.out.println(1.0 - 0.9); System.out.println(1.0 displays 0.09999999999999998, not 0.1. displays Calculations with integers yield a precise integer result. EE3206/EE5805 Java Programming & Applications 7 Literals A literal is a constant value that appears directly in the program. literal is To denote an integer literal of the long type, append it with the To letter L. By default, a floating-point literal is treated as a double type By point value. For example, 5.0 is considered a double value, not a float value. value. To make a number a float by appending the letter F, and make and a number a double by appending the letter D. Floating-point literals can also be specified in scientific notation with Floating E as an exponent. as The letter can be either in lowercase or uppercase. int i = 34; int long x = 1000000L; double d = 5.0D; // OK // OK // OK byte b = 1000; float f = 100.2; double s = 1.2345E-2; // error // error // OK, 0.012345 EE3206/EE5805 Java Programming & Applications 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. 9 EE3206/EE5805 Java Programming & Applications 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 like this one: int k = ++i + i. EE3206/EE5805 Java Programming & Applications 10 10 Type Widening and Narrowing When performing a binary operation involving two operands of different When ferent types, Java automatically converts/promotes the operand of smaller range types, er to the type of larger range. to This is done automatically and hence it is called implicit casting. implicit byte b = 1; int i = b + 1000; double d = 1000; // initialize // byte to int // int to double, lossy Sometimes operands are converted from larger range to a type of smaller range. This leads to truncation of some least significant bits and errors. range. Programmers have to force casting of variables explicitly, hence iit is called t Programmers explicit casting. ex 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? 11 11 EE3206/EE5805 Java Programming & Applications Character Data Type Java characters use Unicode, a 16-bit encoding scheme Java Unicode char letter = 'A'; char char numChar = '4'; numChar '4'; char letter = '\u0041'; u0041'; char numChar = '\u0034'; char numChar u0034'; //ASCII: Dec=65 Hex=41 //ASCII: Dec=52 Hex=34 //ASCII: //Unicode 0041 //Unicode //four hexadecimal digits //four In Java, characters can be manipulated as numbers. This is done In by performing arithmetic operations on the unicode of the unicode of character. character. char ch = 'a'; char ch System.out.println(++ch); int i = ‘1’ + ‘1’; char a = 48; // // // // printing letter b 49+49 = 98 unicode of ‘0’ is 48 unicode of 12 12 EE3206/EE5805 Java Programming & Applications 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 & Applications 13 13 ASCII Character Set ASCII Character Set is a subset of the Unicode from \u0000 to \u007f EE3206/EE5805 Java Programming & Applications 14 14 The String Type The •In contrast to C where string is represented by a character array, y, Java uses the type String to store a string. to • The String type is not a primitive type. It is known as a The reference type or a class. reference or 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 // // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB String SupplementB EE3206/EE5805 Java Programming & Applications 15 15 Using JOptionPane to Get Input Using JOptionPane JOptionPane also provides another method to get input. It takes a string argument for the prompting message. For example, String s = JOptionPane.showInputDialog(“Type Something”); The input returned from the input dialog box is a string. If you 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 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 & Applications 16 16 Using Scanner to Get Input •Alternatively, you may get input from console by 2 steps 1. Create a Scanner object (the counterpart of scanf() in C language) Scanner scanner = new Scanner(System.in); 2. Use these 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 & Applications 17 17 Programming Style and Programming Documentation Documentation Programming styles and conventions are often overlooked by beginners. Not obeying conventions does not harm the correctness of your code. However, they are important for keeping a program structural, readable and maintainable. They are the keys for being a serious and successful programmer. programmer. • • • • Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Layout EE3206/EE5805 Java Programming & Applications 18 18 Appropriate Comments Include a summary at the beginning of the class or method to explain Include lain what the program does, its key features, its supporting data structures, what uctures, and any unique techniques it uses. For our coursework, include your name, student ID, class section, date For date and a brief description at the beginning of the program. Which one is better? EE3206/EE5805 Java Programming & Applications 19 19 Naming Conventions Java usually does not use abbreviation for naming, which often becomes a source of confusion in C language. You should choose meaningful and descriptive names. should Variable and Method names (Lower Camel Case) • Start with lowercase and capitalize every first letter of each Start subsequent word. subsequent • radius, outerArea, computeArea, getLocalPoint. radius, outerArea getLocalPoint Class names (Upper Camel Case) Class • Capitalize the first letter of each word in the name. Capitalize • GameScreen, ControllerButton ControllerButton Constants Constants • Capitalize all letters in constants, and use underscores to Capitalize connect words. • PI, MAX_VALUE EE3206/EE5805 Java Programming & Applications 20 20 Proper Indentation, Spacing and Proper Block Layout Block Indentation Indentation • • • Indent two spaces. Use blank line to separate segments of the code. Use end-of-line style for braces. Next-line style Spacing Block Layout Block 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"); } } EE3206/EE5805 Java Programming & Applications 21 21 Programming Errors Syntax Errors Syntax • Detected by the compiler Runtime Errors Runtime • Causes the program to abort during Causes execution execution Logic Errors Logic • Produces incorrect result EE3206/EE5805 Java Programming & Applications 22 22 Syntax Errors and Runtime Errors public class ShowSyntaxErrors { public ShowSyntaxErrors public static void main(String args) { public args i = 30; System.out.println(i + 4); } } public class ShowRuntimeErrors { public ShowRuntimeErrors public static void main(String args) { public args int i = 1 / 0; } } EE3206/EE5805 Java Programming & Applications 23 23 Logic Errors public class ShowLogicErrors { public ShowLogicErrors // Determine if a number is between 1 and 100 inclusively // inclusively public static void main(String args) { public args // Prompt the user to enter a number String input = JOptionPane.showInputDialog(null, String JOptionPane.showInputDialog(null "Please enter an integer:", "Please "ShowLogicErrors", JOptionPane.QUESTION_MESSAGE); ", JOptionPane.QUESTION_MESSAGE int number = Integer.parseInt(input); number Integer.parseInt(input // Display the result System.out.println("The number is between 1 and 100, " + number "inclusively? " + ((1 < number) && (number < 100))); number) System.exit(0); } } EE3206/EE5805 Java Programming & Applications 24 24 Debugging with Debugger Logic errors are called bugs. The process of finding bugs The and correcting errors is called debugging. A debugger utility can help you effectively find out and correct bugs. You can use a debugger to and • • • • • • 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 Most popular IDEs (e.g. NetBeans) come with a IDEs (e.g. debugger. EE3206/EE5805 Java Programming & Applications 25 25 ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online