# Chapter 2 Primitive Data Types and Operations

Size: px
Start display at page:

Transcription

3 area = radius*radius* ; System.out.println("The area is + area + " for radius "+radius); Declaring Variables Variables are used for representing data of a certain type. To use a variable, you declare it by telling the compiler the name of the variable as well as what type of data it represents. This is called variable declaration. Declaring a variable tells the compiler to allocate appropriate memory space for the variable based on its data type. The following are examples of variable declarations: 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; If variables are of the same type, they can be declared together using short-hand form: Datatype var1, var2,, varn; variables are separated by commas 2.5 Assignment Statements and Assignments Expressions After a variable is declared, you can assign a value to it by using an assignment statement. The syntax for assignment statement is: variable = expression; x = 1; // Assign 1 to x; Thus 1 = x is wrong radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; x = 5 * (3 / 2) + 3 * 2; // Assign the value of the expression to x; x = y + 1; // Assign the addition of y and 1 to x; The variable can also be used in the expression. x = x + 1; // the result of x + 1 is assigned to x; To assign a value to a variable, the variable name must be on the left of the assignment operator. 1 = x would be wrong. In Java, an assignment statement can also be treated as an expression that evaluates to the value being assigned to the variable on the left-hand side of the assignment operator. For this reason, an assignment statement is also known as an assignment expression, and the symbol = is referred to as the assignment operator. System.out.println(x = 1); which is equivalent to

4 x = 1; System.out.println(x); The following statment is also correct: i = j = k = 1; which is equivalent to k = 1; j = k; i = j; Declaring and Initializing Variables in One Step You can declare a variable and initialize it in one step. int x = 1; This is equivalent to the next two statements: int x; x = 1; // shorthand form to declare and initialize vars of same type int i = 1, j = 2; Tip: A variable must be declared before it can be assigned a value. 2.6 Constants The value of a variable may change during the execution of the program, but a constant represents permanent data that never change. The syntax for declaring a constant: final datatype CONSTANTNAME = VALUE; final double PI = ; // Declare a constant final int SIZE = 3; A constant must be declared and initialized before it can be used. You cannot change a constant s value once it is declared. By convention, constants are named in uppercase. // ComputeArea.Java: compute the area of a circle Comment public class ComputeArea // Class Name { public static void main(string[] args) // Main Method signature { final double PI = ; // declare a constant double radius = 20; // assign a radius // Compute area double area = radius * radius * PI; // Expression // Display results

5 System.out.println("The area for the circle of radius " + radius + " is " + area); Note: There are three benefits of using constants: o You don t have to repeatedly type the same value. o The value can be changed in a single location. o The program is easy to read. 2.7 Numerical Data Types and Operations Every data type has a range of values. The compiler allocates memory space to store each variable or constant according to its data type. Java has six numeric types: four for integers and two for floating-point numbers. Name Storage Size Range byte 8 bits -2 7 (-128) to (127) short 16 bits (-32768) to (32767) int 32 bits ( ) to ( ) long 64 bits to float 32 bits 6 7 significant digits of accuracy double 64 bits significant digits of accuracy Numerical Operators +, -, *, /, and % 5/2 yields an integer /2 yields a double value % 2 yields 1 (the remainder of the division.) Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose you know January 1, 2005 is Saturday, you can find that the day for February 1, 2005 is Tuesday using the following expression: Saturday is the 6 th day in a week (6 + 31) % 7 is 2 January has 31 days A week has 7 days The 2 nd day in a week is Tuesday A unary operator has only one operand. A binary operator has two operands. NOTE Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,

6 System.out.println( ); displays , not 0.5, and System.out.println( ); displays , not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result Numeric Literals A literal is a constant value that appears directly in a program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long l = ; double d = 5.0; 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 ( ) to ( ). To denote an integer literal of the long type, append it with the letter L or l (lowercase L). For example, the following code display the decimal value for hexadecimal number FFFF. System.out.println(0xFFFF); 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. The double type values are more accurate than float type values.

7 Scientific Notations Floating-point literals can also be specified in scientific notation; for example, e+2, same as e2, is equivalent to , and e-2 is equivalent to E (or e) represents an exponent and it can be either in lowercase or uppercase Arithmetic Expressions For example, the arithmetic expression 3 + 4x 10( y 5)( a + b + c) x + 9( + ) 5 x x y can be translated into a Java expression as: (3 + 4 * x)/5 10 * (y - 5)*(a + b + c)/x + 9 *(4 / x + (9 + x)/y) Operators contained within pairs of parentheses are evaluated first. Parentheses can be nested, in which case the expression in the inner parentheses is evaluated first. Multiplication, division, and remainder operators are applied next. Order of operation is applied from left to right. Addition and subtraction are applied last Shortcut Operators Table 2.2 Shortcut Operators Operator Example Equivalent += i+=8 i = i+8 -= f-=8.0 f = f-8.0 *= i*=8 i = i*8 /= i/=8 i = i/8 %= i%=8 i = i%8 There are two more shortcut operators for incrementing and decrementing a variable by 1. These two operators are ++, and --. They can be used in prefix or suffix notations. suffix prefix suffix prefix x++; // Same as x = x + 1; ++x; // Same as x = x + 1; x ; // Same as x = x - 1; x; // Same as x = x - 1; Table 2.3 Increment and Decrement Operators

8 Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. int i = 10; Same effect as int newnum = 10 * i++; int newnum = 10 * i; i = i + 1; int i = 10; Same effect as int newnum = 10 * (++i); i = i + 1; int newnum = 10 * i; Ex: double x = 1.0; double y = 5.0; double z = x-- + (++y); After execution, y = 6.0, z = 7.0, and x = 0.0; Using increment and decrement operators make expressions short; 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. Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--; 3 + 4; // Correct prior to Java 2, but wrong in Java Numeric Type Conversions Consider the following statements: byte i = 100; long k = i*3+4; double d = i*3.1+k/2;

9 Are these statements correct? When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. Thus the result of 1 / 2 is 0, and the result of 1.0 / 2 is 0.5. Type Casting is an operation that converts a value of one data type into a value of another data type. Casting a variable of a type with a small range to variable with a larger range is known as widening a type. Widening a type can be performed automatically without explicit casting. Casting a variable of a type with a large range to variable with a smaller range is known as narrowing a type. Narrowing a type must be performed explicitly. Caution: Casting is necessary if you are assigning a value to a variable of a smaller type range. A compilation error will occur if casting is not used in situations of this kind. Be careful when using casting. Lost information might lead to inaccurate results. float f = (float) 10.1; int i = (int) f; double d = 4.5; int i =(int)d; // d is not changed System.out.println("d " + d + " i " + i); // answer is d 4.5 i 4 Implicit casting double d = 3; // type widening Explicit casting int i = (int)3.0; // type narrowing What is wrong? int x = 5 / 2.0; // loss of precision int i = 1; byte b = i; // Error because explicit casting is required 2.9 Character Data Type and Operations The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks.

10 char letter = 'A'; // Assigns A to char variable letter (ASCII) char numchar = '4'; // Assigns numeric character 4 to numchar (ASCII) Caution: A string literal must be enclosed in quotation marks. A character literal is a single chaaracter enclosed in single quotation marks. So A is a string, and A is a character Unicode and ASCII code Java uses 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 (See the Unicdoe Web sit at for more information.) Unicode takes two bytes, precoded by \u, expressed in four hexdecimal digits that run from \u0000 to \uffff. For example, the coffee is translated into Chinese using two characters. The Unicode of these two characters are \u5496\u5561. char letter = '\u0041'; (Unicode 16-bit encoding scheme) char numchar = '\u0034'; (Unicode) Unicode can represent 65,536 characters, since FFFF in hexdecimal is Most computer ASCII (American Standard Code for Information Interchange), a 7-bit encoding scheme for reprsenting all uppercase and lowcase letter, digits, puctuation marks, and control characters. Unicode includes ASCII code with \u0000 to \u007f corresponding to 128 ASCII characters. (See Appendix B). 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);

11 2.9.2 Escape Sequences for Special Characters Description Escape Sequence Unicode Backspace \b \u0008 Tab \t \u0009 Linefeed \n \u000a Carriage return \r \u000d Backslash \\ \u005c Single Quote \' \u0027 Double Quote \" \u0022 Suppose you want to print the quoted message show below: He said Java is fun Here is how to write the statement: System.out.println( He said \ Java is fun\ ); Casting between char and Numeric Types A char can be cast into any numeric type, and vice versa. Implicit casting can be used if the result of a casting fits into the target variable. Otherwise expicit casting must be used. All numeric operation can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. If the other operand is a string, the character is concatenated with the string. int i = 'a'; // Same as int i = (int)'a'; // (int) a is 97 char c = 99; // Same as char c = (char)99; int i = '1' + '2';// (int) 1 is 49 and (int) 2 is 50 System.out.println("i is " + i); int j = 1 + 'a'; // (int) a is 97 System.out.println("j is " + 98); System.out.println(j + " is the Unicode for character " + (char) j); System.out.println("Chapter " + 2); Output is: i is 99 j is is the Unicode for character b Chapter 2

12 2.10 The Boolean Data Type and Operations 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. System.out.println(1 < 2); // Displays true boolean b = (1 > 2); System.out.println("b is " + b); // Displays b is false TABLE 2.5 Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to!= not equal to TABLE 2.6 Boolean Operators Operator Name Description! not logical negation && and logical conjunction or logical disjunction ^ exclusive or logical exclusion && (and) (1 < x) && (x < 100) (or) (lightson) (isdaytime)! (not)!(isstopped) TABLE 2.7 Truth Table for Operator! p!p true false false true TABLE 2.8 Truth Table for Operator && p1 p2 p1 && p2 false false false false true false true false false true true true Example!(1 > 2) is true, because (1 > 2) is false.!(1 > 0) is false, because (1 > 0) is true. Example (2 > 3) && (5 > 5) is false, because either (2 > 3) and (5 > 5) is false. (3 > 2) && (5 > 5) is false, because (5 > 5) is false. (3 > 2 && (5>= 5) is true, b/c (3 > 2) and (5 >= 5) are both true.

13 TABLE 2.9 Truth Table for Operator p1 p2 p1 p2 false false false false true true true false true true true true Example (2 > 3) (5 > 5) is false, because (2 > 3) and (5 > 5) are both false. (3 > 2) (5 > 5) is true, because (3 > 2) is true. TABLE 2.10 Truth Table for Operator ^ p1 p2 p1 ^ p2 false false false false true true true false true true true false Example (2 > 3) ^ (5 > 1) is true, because (2 > 3) is false and (5 > 1) is true. (3 > 2) ^ (5 > 1) is false, because both (3 > 2) and (5 > 1) are true. Examples int num = 2; System.out.println("Is " + num + " divisible by 2 and 3? " + ((num % 2 == 0) && (num % 3 == 0))); System.out.println("Is " + num + " divisible by 2 or 3? " + ((num % 2 == 0) (num % 3 == 0))); System.out.println("Is " + num + " divisible by 2 or 3, but not both? " + ((num % 2 == 0) ^ (num % 3 == 0))); Is 2 divisible by 2 and 3? false Is 2 divisible by 2 or 3? true Is 2 divisible by 2 or 3, but not both? true Unconditional vs. Conditional Boolean Operators &&: conditional (short-circuit) AND operator &: unconditional AND operator : conditional (short-circuit) OR operator : unconditional OR operator exp1 && exp2 (1 < x) && (x < 100) (1 < x) & (x < 100) If x is 1, what is x after this expression? (x > 1) & (x++ < 10) x = 2 (1 > x) && (1 > x++) x = 1 How about

14 (1 == x) (10 > x++)? x = 2 (1 == x) (10 > x++)? x = 1 Tip: Avoid using the & and. For example: (x!= 0) & (100 / x < 10)? runtime error if x is 0 Note: The & and operators can also apply to bitwise operations. See Appendix G Note: A Boolean value, however, cannot be cast into a value of other types, nor can a value of other types be cast into a Boolean value. Note: true and false are literals, just like a number such as 10, so they are not keywords, but you cannot use them as identifiers, just as you cannot use 10 as an identifier Operator Precedence & Associativity How to evaluate? * 4 > 5 * (4 + 3) - 1 The precedence rule defines precedence for operators as shown below. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative. For example: a b + c d is equivalent to ((a b) + c) d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) Operator Precedence Chart (Table 2.11) var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting! (Not) *, /, % (Multiplication, division, and modulus) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==,!= (Equality) & (Unconditional AND) ^ (Exclusive OR) (Unconditional OR) && (Conditional AND) Short-circuit AND (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)

15 Example Applying the operator precedence and associativity rule, the expression * 4 > 5 * (4 + 3) - 1 is evaluated as follows: * 4 > 5 * (4 + 3) * 4 > 5 * > 5 * > > > 34 false (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) subtraction (6) greater than 2.12 Operand Evaluation Order The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1. int a = 0; int x = a + (++a); But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1. int a = 0; int x = ++a + a; The order for evaluating operands takes precedence over the operator precedence rule. (++a) has higher precedence than (+), but since it is a left-hand operand of the addition (+), it is evaluated before any part of its right hand operand. Rule of Evaluating an Expression: o Rule 1: Evaluate whatever sub-expressions you can possibly evaluate from left to right. o Rule 2: The operators are applied according to their precedence, as shown in Table 2.11.

16 o Rule 3: The associativity rule applies for two operators next to each other with the same precedence. Applying the rule, the expression * 4 > 5 * (4 + 3) - 1 is evaluated as follows: * 4 > 5 * (4 + 3) > 5 * (4 + 3) > 5 * (4 + 3) > 5 * > > 34 false (1) 4 * 4 is the first sub-expression that can be evaluated from left. (2) is evaluated now. (3) is now the leftmost subexpression that should be evaluated. (4) 5 * 7 is evaluated now. (5) 35 1 is evaluated now. (6) 19 > 34 is evaluated now 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 Chapter 6, Classes and Objects. 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. String Concatenation The plus sign (+) is the concatenation operator if one of the operands is a string. If one of the operands is a non-string (e.g. a number), the non-string value is converted into a string and concatenated with the other string. // Three strings are concatenated String message = "Welcome " + "to " + "Java"; message += and Java is fun ; // message = Welcome to Java and Java is fun // 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

17 i = 1; j = 3; System.out.println("i + j is " + i + j); i + j is 13 System.out.println("i + j is " + (i + j)); i + j is Getting Input from Input Dialog Boxes String string = JOptionPane.showInputDialog( null, Prompt Message, Dialog Title, JOptionPane.QUESTION_MESSAGE)); 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. Note: 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.showMessageDialog(x); where x is a string for the prompting message Converting String to Numbers Converting Strings to Integers

18 The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns 123. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseint method in the Integer class as follows: int intvalue = Integer.parseInt(intString); where intstring is a numeric string such as 123. Converting Strings to Doubles To convert a string into a double value, you can use the static parsedouble method in the Double class as follows: double doublevalue = Double.parseDouble(doubleString); where doublestring is a numeric string such as Example Page 55: This program first prompts the user to enter a year as an int value and checks if it is a leap year, it then prompts you to enter a double value and checks if it is positive. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. ((year % 4 == 0) && (year % 100!= 0)) (year % 400 == 0) // InputDialogDemo.java: Entering input from input dialog boxes import javax.swing.joptionpane; public class InputDialogDemo { public static void main(string args[]) { // Prompt the user to enter a year String yearstring = JOptionPane.showInputDialog(null, "Enter a year:", "Example 2.2 Input (int)", JOptionPane.QUESTION_MESSAGE); // Convert the string into an int value int year = Integer.parseInt(yearString); // Check if the year is a leap year boolean isleapyear = ((year % 4 == 0) && (year % 100!= 0)) (year % 400 == 0); // Display the result in a message dialog box JOptionPane.showMessageDialog(null, year + " is a leap year? " + isleapyear, "Example 2.2 Output (int)", JOptionPane.INFORMATION_MESSAGE); // Prompt the user to enter a double value String doublestring = JOptionPane.showInputDialog(null, "Enter a double value:", "Example 2.2 Input (double)",

19 JOptionPane.QUESTION_MESSAGE); // Convert the string into a double value double doublevalue = Double.parseDouble(doubleString); // Check if the number is positive JOptionPane.showMessageDialog(null, doublevalue + " is positive? " + (doublevalue > 0), "Example 2.2 Output (double)", JOptionPane.INFORMATION_MESSAGE); System.exit(0); 2.17 Formatting Output (JDK 1.5 Feature) Use the new JDK 1.5 printf statement. System.out.printf(format, item); 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. TABLE 2.12 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 %e a number in standard scientific notation e+01 %s a string "Java is cool" int count = 5; double amount = 45.56; System.out.printf("count is %2d %4.2f", count, amount); displays count is Items must match the specifiers in order, on number, and in exact type. By default, a floating-point value is displayed with 6 digits after the decimal points Programming Style and Documentation Programming Style deals with what programs look like. Documentation is the body of explanatory remarks and comments pertaining to a program.

21 Next-line style public class Test { public static void main(string[] args) { System.out.println("Block Styles"); public class Test { public static void main(string[] args) { System.out.println("Block Styles"); End-of-line style 2.19 Programming Errors Syntax Errors Compilation Error Errors that occur duing compilation are called syntax errors or compilation errors. Syntax errors result from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace without a corresponding closing brace. These errors are easily detected, because the compiler tells you where they are and the reasons for them. public class ShowSyntaxErrors { public static void main(string[] args) { i = 30; System.out.println(i+4); Runtime Errors Runtime errors are erros that cause a program to terminate abnormally. Runtime errors occur while an application is running where the environment detects an operation that is impossible to carry out. For instance, an input error occurs when the user enters an unexpected input value that the program can t handle. To prevent input errors, the program should prompt the user to enter the correct type of values. Another example of a run time error is division by zero. public class ShowRuntimeErrors { public static void main(string[] args) { int i = 1 / 0; Logic Errors Logic errors occur when a program doesn t perform the way it was intended to.

22 For example, the program doesn t have syntax or runtime errors, but it does not print the correct result. // ShowLogicErrors.java: The program contains a logic error import javax.swing.joptionpane; public class ShowLogicErrors { public static void main(string[] args) { // Add number1 to number2 int number1 = 3; int number2 = 3; number2 += number1 + number2; System.out.println("number2 is " + number2); 2.20 Debugging Finding logic errors bugs is challenging and the process of finding and correcting errors is called debugging. You can hand-trace the program or you can insert print statements in order to show the values of the variables or the execution flow of the program. For a large, complex program, the most effective approach for debugging is to use a debugger utility.

### Chapter 2 Primitive Data Types and Operations

Chapter 2 Primitive Data Types and Operations 2.1 Introduction You will be introduced to Java primitive data types and related subjects, such as variables constants, data types, operators, and expressions.

### Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 Primitive Data Types and Operations Prerequisites for Part I Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs,

### Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Part I 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical

### Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 ELEMENTARY PROGRAMMING Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Objectives To write Java programs to perform simple

### Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

### Chapter 2 Elementary Programming

Chapter 2 Elementary Programming 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems

### JAVA Programming Concepts

JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa Programming is the art of Problem Solving

### Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Chapter 2 Elementary Programming Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems

### Chapter 3 Selection Statements

Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are

### CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

LIANMC03v3_0132221586.QXD 5/15/06 7:41 PM Page 67 CCHAPTER HAPTER 3 1 SELECTION STATEMENTS Objectives To declare boolean type and write Boolean expressions ( 3.2). To distinguish between conditional and

Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

### Datatypes, Variables, and Operations

Datatypes, Variables, and Operations 1 Primitive Type Classification 2 Numerical Data Types Name Range Storage Size byte 2 7 to 2 7 1 (-128 to 127) 8-bit signed short 2 15 to 2 15 1 (-32768 to 32767) 16-bit

### CEN 414 Java Programming

CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

### Chapter 2 Elementary Programming

Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input

### Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Chapter 2 Elementary Programming 1 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems

### Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Chapter 2: Elementary Programming CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations In the preceding chapter, you learned how to

### Basics of Java Programming

Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

### CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

### Chapter 2. Elementary Programming

Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

### Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter p 1 Introduction to Computers, p, Programs, g, and Java Chapter 2 Primitive Data Types and Operations Chapter

### 4 WORKING WITH DATA TYPES AND OPERATIONS

WORKING WITH NUMERIC VALUES 27 4 WORKING WITH DATA TYPES AND OPERATIONS WORKING WITH NUMERIC VALUES This application will declare and display numeric values. To declare and display an integer value in

### Full file at

Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

### Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

### CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java California State University, Los Angeles Computer Science Department Lecture V: Mathematical Functions, Characters, and Strings Introduction How would you estimate

### 4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

### Zheng-Liang Lu Java Programming 45 / 79

1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

### Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Motivations If you assigned a negative value for radius

### Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

### Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

### Chapter 2: Data and Expressions

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 2: Data and Expressions CS 121 1 / 51 Chapter 1 Terminology Review

### Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

### Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

### CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

### Full file at

Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

### Program Fundamentals

Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

### Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #4

### 3. Java - Language Constructs I

Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

### Chapter 2: Using Data

Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

### Chapter 3: Operators, Expressions and Type Conversion

101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

### CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

### JAVA Programming Fundamentals

Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

### Information Science 1

Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

### Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

### UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . \$, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

### CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

### Reserved Words and Identifiers

1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

### Computer System and programming in C

1 Basic Data Types Integral Types Integers are stored in various sizes. They can be signed or unsigned. Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign

### Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 3: Selections and Conditionals CS1: Java Programming Colorado State University Motivations If you assigned a negative value for radius in Listing 2.2, ComputeAreaWithConsoleInput.java, the program

### Important Java terminology

1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as

### Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

### Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

### Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Elementary Programming CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Variables In a program, the variables store data Primitive type variables store single pieces

### Chapter 2: Using Data

Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

### Elementary Programming

Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

### Java Programming Fundamentals. Visit for more.

Chapter 4: Java Programming Fundamentals Informatics Practices Class XI (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)

### Information Science 1

Topics covered Information Science 1 Terms and concepts from Week 8 Simple calculations Documenting programs Simple Calcula,ons Expressions Arithmetic operators and arithmetic operator precedence Mixed-type

### Chapter 6 Primitive types

Chapter 6 Primitive types Lesson page 6-1. Primitive types Question 1. There are an infinite number of integers, so it would be too ineffient to have a type integer that would contain all of them. Question

### These are reserved words of the C language. For example int, float, if, else, for, while etc.

Tokens in C Keywords These are reserved words of the C language. For example int, float, if, else, for, while etc. Identifiers An Identifier is a sequence of letters and digits, but must start with a letter.

### false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 44

### Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

### CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical

### Chapter 2: Data and Expressions

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

### Chapter 2: Data and Expressions

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

### Chapter 02: Using Data

True / False 1. A variable can hold more than one value at a time. ANSWER: False REFERENCES: 54 2. The int data type is the most commonly used integer type. ANSWER: True REFERENCES: 64 3. Multiplication,

### Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

### Expanded Guidelines on Programming Style and Documentation

Page 1 of 5 Expanded Guidelines on Programming Style and Documentation Introduction Introduction to Java Programming, 5E Y. Daniel Liang liang@armstrong.edu Programming style deals with the appearance

### Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 02 Data Types and Statements MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Topics Covered Statements Variables Constants Data Types

### Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

### Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

### Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1 Topics 1. Expressions 2. Operator precedence 3. Shorthand operators 4. Data/Type Conversion 1/15/19 CSE 1321 MODULE 2 2 Expressions

### 12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

### 2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

### 3chapter C ONTROL S TATEMENTS. Objectives

3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (

### A variable is a name for a location in memory A variable must be declared

Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

### Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

### Course PJL. Arithmetic Operations

Outline Oman College of Management and Technology Course 503200 PJL Handout 5 Arithmetic Operations CS/MIS Department 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers.

### Getting started with Java

Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

### Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 4 Mathematical Functions, Characters, and Strings Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose you need to estimate

### Eng. Mohammed S. Abdualal

Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 3 Selections

### Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

### Chapter 2. Lexical Elements & Operators

Chapter 2. Lexical Elements & Operators Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr The C System

### Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

### DATA TYPES AND EXPRESSIONS

DATA TYPES AND EXPRESSIONS Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical

### Full file at

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) 25 % 1 is. 1) A) 2 B) 1 C) 0 D) 4 E) 3 2) Which of the following expressions will yield 0.5? (choose

### CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

### Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

### 1 Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

### Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

### Chapter 2 Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

### BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

### Supplement D: Expanded Guidelines on Programming Style and Documentation

Page 1 of 5 Introduction Supplement D: Expanded Guidelines on Programming Style and Documentation For Introduction to Java Programming Y. Daniel Liang mailto:liang@armstrong.edu Programming style deals

### Java Primer 1: Types, Classes and Operators

Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

### Programming with Java

Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

### Selections. CSE 114, Computer Science 1 Stony Brook University

Selections CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation If you assigned a negative value for radius in ComputeArea.java, then you don't want the

### Prof. Navrati Saxena TA: Rochak Sachan

JAVA Prof. Navrati Saxena TA: Rochak Sachan Operators Operator Arithmetic Relational Logical Bitwise 1. Arithmetic Operators are used in mathematical expressions. S.N. 0 Operator Result 1. + Addition 6.

### C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

### Chapter 2: Using Data

Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time