General Features of Java Programming Language Variables and
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements
The Basic Demo Program public class Basics. Demo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++) { sum += current; } System. out. println("Sum = " + sum); } }
The Count Class import java. io. *; public class Count { public static void count. Chars(Reader in) throws IOException { int count = 0; while (in. read() != -1) count++; System. out. println("Counted " + count + " chars. "); } } Go Back: 6, 8, 17
Running the count. Chars • import java. io. *; public class Count { //. . . count. Chars method omitted. . . public static void main(String[] args) throws Exception { if (args. length >= 1) count. Chars(new File. Reader(args[0])); else System. err. println("Usage: Count filename"); } }
Variables and Data Types Variables: Entities that act or are acted upon Two Variables in Count: count and in
Variable Declaration • Variable Declaration: – Type of the variable – Name of the variable • The location of the variable declaration determines its scope.
Data Type • Java is static-typed: All variables must have a type and have to be declared before use. • A variable's data type determines its value and operation • Two categories of data types in Java – primitive data type: byte, short, int, long, float. . – reference data type: class, interface, array count is ? Primitive in is ? Reference
Primitive and Reference Data Type Point p 1, p 2; p 1 = new Point(); p 2 = p 1; int x; x = 5; x: 5 Primitive Data Type p 1: p 2: x: 0 y: 0 Reference Data Type
Primitive Data Types • • byte short int long float double char boolean 8 -bit 16 -bit 32 -bit 64 -bit 32 -bit floating point 64 -bit floating point 16 -bit Unicode true/false
Variable Names • Java refers to a variable's value by its name. • General Rule – Must be Legal Java identifier – Must not be a keyword or a boolean literal – Must not be the same name as another variable in the same scope • Convention: – Variable names begin with a lowercase letter • is. Empty, is. Visible, count, in – Class names begin with an uppercase letter • Count
Reserved Words (Keywords) abstract boolean break byte case catch char class const* continue default do double else extends finally float for goto* if implements import instanceof interface long native new package private throw protected throws public transient return try short void static volatile super while switch synchronized this Don't worry about what all these words mean or do, but be aware that you cannot use them for other purposes like variable names.
Variable Scope • The block of code within which the variable is accessible and determines when the variable is created and destroyed. • The location of the variable declaration within your program establishes its scope • Variable Scope: – – Member variable Local variable Method parameter Exception-handler parameter
Variable Scope
Variable Initialization • Local variables and member variables – can be initialized with an assignment statement when they're declared. – The data type of both sides of the assignment statement must match. • int count = 0; • Method parameters and exception-handler parameters – cannot be initialized in the same way as local/member vars – The value for a parameter is set by the caller.
Final Variables • The value of a final variable cannot change after it has been initialized. • You can view final variables as constants. • Declaration and Initialization – final int a. Final. Var = 0; – final int blankfinal; . . . blankfinal = 0;
Literals (I) • To represent the primitive types • Integer – Decimal Value – Hexadecimal Value: 0 x. . . – Octal Value: 0. . . (0 x 1 f = 31) (076=62) • Floating Point – 3. 1415 – 6. 1 D 2 – 3. 4 F 3 (64 -bit Double; Default) (32 -bit Float)
Literals (II) • Characters – '. . . ‘ e. g. ‘a’ – 't', 'n' (Escape Sequence) • Strings – ". . . . “ e. g. “Hello World!” – String Class (Not based on a primitive data type)
Operators perform some function on operands. An operator also returns a value.
Operators (I) • Arithmetic Operators – Binary: +, -, *, /, % – Unary: +, -, op++, ++op, op--, --op (i>5) ? j=1 : j=2 • Relational Operators – >, >=, <, <=, ==, != (return true and false) • Conditional Operators – &&(AND), ||(OR), !(NOT), &(AND), |(OR) – expression ? op 1 : op 2 • Bitwise Operators – >>, <<, >>>, &, |, ^, ~ if (i>5) j=1; else j=2;
Operators (II) • Assignment Operators –= – += – -=, *=, /=, %=, &=, !=, ^=, <<=, >>>= op 1 += op 2 op 1 = op 1 + op 2 s += 2 s=s+2
Expressions Perform the work of a Java Program Perform the computation Return the result of the computation
Expression • An expression is a series of variables, operators, and method calls that evaluates to a single value. – count ++ – in. read() != -1 • Precedence – Precedence Table – Use (. . . ) • Equal precedence – Assignment: Right to Left (a = b =c) – Other Binary Operators: Left to Right
Expressions and operators • An expression is a program fragment that evaluates to a single value – double d = v + 9 * get. Salary() % PI; • Arithmetic operators – additive +, -, ++, -– multiplicative *, / % (mod operator) • Relational operators – equality == (NB) – inequality != – greater than and less than >, >=, <, <=
Control Flow Statement
If Statements • if (boolean) { /*. . . */ } else if (boolean) { /*. . . */ } Statement Block else { /*. . . */ } • The expression in the test must return a boolean value – Zero('') can't be used to mean false, or non-zero(". . . ") to mean true
Example if (income < 20000){ System. out. println (“poor”); } else if (income < 40000){ System. out. println (“not so poor”); } else if (income < 60000){ System. out. println (“rich”); } else { System. out. println (“ very rich”); }
Loops • while (boolean expression) { /*. . . */ } • do { /*. . . */ } while (boolean expression) • for (expression; boolean. Expression; expression) { /*. . . */ }
Example // count from 1 to 10 int i = 1; while (i<=10) { System. out. println (i); i= i+ 1; }
Example // count from 1 to 10 int i = 1; do { System. out. println (i) i= i+ 1; } while (i< 10);
The for statement • The for statement has the following syntax: Reserved word The initialisation part is executed once before the loop begins The statement is executed until the condition becomes false for (initialisation; condition; increment) statement; The increment part is executed at the end of each iteration
Example // count from 1 to 10 for (int i = 0; i < 10; i++) System. out. println (i);
Secret! A for Loop can always be converted to a while loop i = 0; while (i < 10) { System. out. println(i); i++; } for(i = 0; i < 10; i++) i++ { System. out. println(i); } This will help you understand the sequence of operations of a for loop
Switch • switch (expression) { case Constant 1: /*. . . */ break; case Constant 2: /*. . . */ break; . . default: /*. . . */ break; }
Multiple Selections via switch Note the "optional" default case at the end of the switch statement. It is technically optional only in terms of syntax. switch (number) { case 1: This might System. out. println ("One"); work without break; the default case 2: case, but System. out. println ("Two"); would be break; poor case 3: technique System. out. println ("Three"); break; default: System. out. println("Not 1, 2, or 3"); break; // Needed? ? ? } // switch For safety and good programming practice, always include a 'default' case.
How many days? if (month == 4 || month == 6 || month == 9 || month == 11) numdays = 30; else if (month == 2) { numdays = 28; if (leap) numdays = 29; } else numdays = 31;
switch { case (month) Switch 4: 6: 9: 11: numdays = 30; break; case 2: numdays = 28; if(leap) numdays = 29; break; default: /* Good idea? */ numdays = 31; }
- Slides: 36