hello.java program output 1 public class hello { 2 public static void main( string [] args ) 3 { 4...
TRANSCRIPT
Hello.java
Program Output
1 public class Hello { 2 public static void main( String [] args )3 {4 System.out.println( “Hello!" );5 } // end method main6 } // end class Hello
Hello!
A Simple Program: Printing a Line of Text
Chapter 0 – Introduction to Programming
2
Type Size in bits Values Standard boolean 8 true or false
char 16 ’\u0000’ to ’\uFFFF’ (0 to 65535)
(ISO Unicode character set)
byte 8 –128 to +127
short 16 –32,768 to +32,767
int 32 –231 to 231 – 1
long 64 –263 to 263 – 1
float 32 Negative range: –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38
(IEEE 754 floating point)
double 64 Negative range: –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308
(IEEE 754 floating point)
Data Types
3
Identifiers
• Identifiers are names for programming entities such as variables, classes, methods, etc.
• Rules for naming identifiers:1. consists of letters (a-z, A-Z), digits (0-9), underscore
(_)and dollar sign ($)
2. cannot start with a digit
3. cannot be reserved words (see next page)
• Example of Valid Identifiers: – a, aNumber, F101, Sales_2003$123, MyClass
• Example of Invalid Identifiers: – Go#, 3Hands, Star*Mars, final
4
Reserved Words
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
true false null
5
Constants• A constant is an identifier that is similar to a variable except
that its value cannot be changed.
• The compiler will issue an error if you try to change a constant
• In Java, we use the final modifier to declare a constantfinal int MEANING_OF_LIFE = 42;
• Constants:
– give names to otherwise unclear literal values
– facilitate changes to the code• Avoid using literal constants
(e.g. salary = 2*hourly_rate + 60;)should use
salary = OT_FACTOR*hourly_rate + BASIC_RATE;
6
Assignment
• An assignment statement changes the value of a variable
• The assignment operator is the = sign
• You can only assign a value to a variable that is consistent with the variable's declared type
• The expression on the right is evaluated and the result is stored in the variable on the left
• The value that was in total is overwritten
total = 55*salary;
7
Arithmetic Operators
Operator(s) Operation(s) Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are nested,
the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.
*, / and % Multiplication Division Modulus
Evaluated second. If there are several of this type of operator, they are evaluated from left to right.
+ or - Addition Subtraction
Evaluated last. If there are several of this type of operator, they are evaluated from left to right.
Fig. 2.17 Precedence of arithmetic operators.
8
Assignment operator Sample expression Explanation Assigns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g Fig. 4.12 Arithmetic assignment operators.
Arithmetic Operators
9
Operator Called Sample expression Explanation ++ preincrement ++a Increment a by 1, then use
the new value of a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.
Fig. 4.13 The increment and decrement operators.
Arithmetic Operators
10
String Concatenation
• The plus operator (+) is used for arithmetic addition and string concatenation (joining two strings)
• The function to perform depends on the type of the information
e.g. 2 + 35 gives 37 but "2" + "35" gives "235"
• How about 2 + "35" or "2" + 35?
• Ans: "235"
• If both operands are strings, or if one is a string and one is a number, it performs string concatenation
• If both operands are numeric, it adds them
11
Casting
• Casting - convert a type to another explicitly
• To cast, the type is put in parentheses in front of the value being converted
• For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:
result = (float) total / count;
• To avoid loss of accuracy, use
a = (double) 10/3; a = 10/(double) 3;
but NOT a = (double) (10/3);
Note: a=10/3.0 or a=10.0/3 also work
12
Standard algebraic equality or relational operator
J ava equality or relational operator
Example of J ava condition
Meaning of J ava condition
Equality operators = == x == y x is equal to y != x != y x is not equal to y Relational operators > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y
Fig. 2.19 Equality and relational operators.
Equality and Relational Operators
• e.g. a=2; b=4;if (a>b)
System.out.print("hot - ");
System.out.prinln("but not humid");
The output is but not humid.
13
Logical Operators
• Logical operators– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators– && (logical AND)– & (boolean logical AND)– || (logical OR)– | (boolean logical inclusive OR)– ^ (boolean logical exclusive OR)– ! (logical NOT)
14
The if/else Selection Structure
• Perform action (statement1) only when condition is true
• Perform different specified action (statement2) when condition is false
if ( condition )
statement1
else
statement2
15
Conditional Operator
• The conditional operator is similar to an if-else statement, except that it is an expression that returns a value.
• For example: if (num1 > num2)
larger = num1;
else
larger = num2;
is the same aslarger = (num1 > num2) ? num1 : num2;
16
Nested if statements
expression1
statement 3 expression2
statement 2 Statement 1
if (expression 1) if (expression 2) statement 1 else statement 2else statement 3
true
true
false
false
17
The switch Multiple-Selection Structure
• switch structure– Used for multiple selections
• Syntaxexpression must be byte, short, int or char but NOT longswitch ( expression ) {
case label1:
statement(s);
break;
case label2:
statement(s);
break;
default:
statement(s);
}
18
The for Repetition Structurefor ( expression1; expression2; expression3 ) {
statement;
}
can easily be rewritten as:
expression1;while ( expression2 ) { statement; expression3;}
19
The while Repetition Structure
• The structure is:
while ( condition ) { statement1; statement2; statement3; ...
}
Loop Body
20
The do/while Repetition Structure
• do/while structure– Similar to while structure
– Tests loop-continuation after performing body of loop
• i.e., loop body always executes at least once
• Syntaxdo { statements; ... } while ( condition );
21
Nested Loop
• A loop inside the loop body of another loop.
• Example: Print the following pattern using nested for-loop.
public class NestedLoop1 { public static void main( String args[] ) { for ( int i = 1; i <= 7; i++ ) { // print each row for ( int j = 1; j <= 5; j++ ) { System.out.print( j ); } System.out.println(); } }}
Outer Loop
Inner Loop
12345123451234512345123451234512345
22
Arrays
• Consider the declaration int[] c = new int[ 5 ];
- c is the array name– c.length accesses array c’s length (5)– c has 5 elements ( c[0], c[1], … c[4] )– c[1] = 20 assigns integer 20 to the second location of c
• An array of size N is indexed from zero to N-1• We can use initializer list to initialize array
elements asint[] n = { 10, 20, 30, 40, 50 };
The operator new is not needed.
23
Arrays
• Declaring and Allocating arrays– Arrays are objects that occupy memory
– Allocated dynamically with operator new int[] c = new int[ 12 ];
– Equivalent to int[] c; // declare array c = new int[ 12 ]; // allocate array
• We can allocate arrays of objects too
String[] b = new String[ 100 ];
• Bear in mind– All primitive data type variables are allocated automatically.
– All object data type variables (including array) must be created by the programmer (using the new operator) explicitly.
24
Arrays
• Multiple-subscripted arrays– Tables with rows and columns
• Double-subscripted (two-dimensional) array
• Declaring double-subscripted array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };– 1 and 2 initialize b[0][0] and b[0][1]– 3 and 4 initialize b[1][0] and b[1][1]
1 2
3 4
0 1
0
1
25
Arrays
• Allocating multiple-subscripted arrays– Can be allocated dynamically
• 3-by-4 array
int b[][]; b = new int[ 3 ][ 4 ];
• Rows can have different number of columns
int c[][]; c = new int[ 2 ][ ]; // allocate rows c[ 0 ] = new int[ 5 ]; // allocate row 0 c[ 1 ] = new int[ 3 ]; // allocate row 1
b c
26
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row 0
Row 2
Row 1
Column 0 Column 1 Column 2 Column 3
Column subscript (or index)
Row Subscript (or index)
Array name
Fig. 7.14 A double-subscripted array with three rows and four columns.
Arrays
27
Method Definitions
• General format of a method:return-value-type method-name( parameter-list ) { declarations and statements}
• Method can also return values: return expression;
• Parameters must be correct
– When a method starts running, it must have the right number of parameters, and each parameter must be of the required type.
public int square( int y ) { return y * y; }
Access Modifier (discussed later)
28
Type Allowed promotions
double None
float double long float or double int long, float or double char int, long, float or double short int, long, float or double byte short, int, long, float or double boolean None (boolean values are not considered to be numbers in Java)
Fig. 6.5 Allowed promotions for primitive data types.
– Specify how to convert types without data loss
Promotion Rules
29
Scope Rules
• A method can see local variables and parameters that are within it’s scope (inside the box).
• A method can see out of the glass that surrounds it.
• But no outsider can see into the box.