Download Basic Data types, Arrays, Operators and Precedence, Control

Document related concepts
no text concepts found
Transcript
Deen Dayal Upadhyaya College
Department of Computer Science
Workshop on Java J2SE
Basic Data types, Arrays,
Operators and Precedence,
Control Statements
Ankit Rajpal
Assistant Professor
Dept. of Computer Science
DDUC
Primitive Data Types
Primitive data Types
The eight primitive data types supported by the Java programming
language are:
i. byte—1-byte integer
ii. short—2-byte integer
iii. int – the default declaration – 4-byte integer
iv. long—8-byte integer
v. float—a 4-byte floating point number
vi. double—an 8-byte floating point number
vii.boolean—The boolean data type has only two possible values:
true and false.
viii.char—The char data type is a single 16-bit Unicode character.
Java programming language also provides special support for
character strings via the java.lang.String class.
Primitive Sizes and Ranges
PRIMITIVE
SIZE IN BITS
RANGE
byte
8
-128 to 127
short
16
-32768 to 32767
int
32
-231 to 231-1 (Signed)
0
to 232-1 (Unsigned in JAVA SE 8 or later)
long
64
-263 to 263-1 (Signed)
0
to 264-1 (Unsigned in JAVA SE 8 or later)
float
32
32-bit IEEE 754 floating point Standard
double
64
64-bit IEEE 754 floating point Standard
char
16
It has a minimum value of '\u0000' (or 0) and a
maximum value of '\uffff' (or 65,535 inclusive)
boolean
8
True or false
string
16 bits per char
Not applicable
Default Values of Data Types
Data Type
Default Value (for fields)
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
'\u0000'
String (or any object)
null
boolean
false
Note: Accessing an uninitialized local variable will result in a compile-time error.
Using Java Operators
Assignment Operator (=)
lvalue = rvalue;
w = 10;
x = w;
z = (x - 2)/(2 + 2);
• Take the value of the rvalue and store it
in the lvalue.
• The rvalue is any constant, variable or
expression.
• The lvalue is named variable.
Mathematical Operators
•
•
•
•
•
Addition
Subtraction
Multiplication
Division
Modulus
+
*
/
%
Simple Arithmetic
public class Example
{
public static void main(String[] args)
{
int j, k, p, q, r, s, t;
j = 5;
k = 2;
p = j + k;
q = j - k;
r = j * k;
s = j / k;
t = j % k;
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("r = " + r);
System.out.println("s = " + s);
System.out.println("t = " + t);
}
}
>
p
q
r
s
t
>
java Example
= 7
= 3
= 10
= 2
= 1
Simple Arithmetic
class Arithmetic
{
public static void main(String [] args)
{
byte i=10;
byte j=9;
i=(j+i);
System.out.println(i);
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to byte
at Arithmetic.main(Arithmetic.java:8)
Shorthand Operators
+=, -=, *=, /=, %=
Common
a = a +
a = a a = a *
a = a /
a = a %
b;
b;
b;
b;
b;
Shorthand
a +=
a -=
a *=
a /=
a %=
b;
b;
b;
b;
b;
Shorthand Operators
public class Example {
public static void main(String[] args) {
int j, p, q, r, s, t;
j = 5;
p = 1; q = 2; r = 3; s = 4; t = 5;
p += j;
q -= j;
r *= j;
s /= j;
t %= j;
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("r = " + r);
System.out.println("s = " + s);
System.out.println("t = " + t);
}
}
> java Example
p = 6
q = -3
r = 15
s = 0
t = 0
>
Simple Arithmetic
class Arithmetic
{
public static void main(String [] args)
{
byte i=10;
byte j=9;
i+=j;
System.out.println(i);
}
}
19
Shorthand Increment and
Decrement ++ and -Common
a = a + 1;
a = a - 1;
Shorthand
a++; or ++a;
a--; or --a;
Increment and Decrement
public class Example {
public static void main(String[] args) {
int j, p, q, r, s;
j = 5;
p = ++j; // j = j + 1; p = j;
System.out.println("p = " + p);
q = j++; // q = j;
j = j + 1;
System.out.println("q = " + q);
System.out.println("j = " + j);
r = --j; // j = j -1;
r = j;
System.out.println("r = " + r);
s = j--; // s = j;
j = j - 1;
System.out.println("s = " + s);
}
}
> java example
p = 6
q = 6
j = 7
r = 6
s = 6
>
Relational Operators
> < >= <= == !=
Primitives
• Greater Than
• Less Than
• Greater Than or Equal
• Less Than or Equal
Primitives or Object References
• Equal (Equivalent)
• Not Equal
>
<
>=
<=
==
!=
The Result is Always true or false
Relational Operator Examples
public class Example
{
public static void main(String[] args)
{
int p =2; int q = 2; int r = 3;
System.out.println("p
System.out.println("p
System.out.println("p
System.out.println("p
< r " + (p < r));
> r " + (p > r));
== q " + (p == q));
!= q " + (p != q));
}
}
>
p
p
p
p
>
java Example
< r true
> r false
== q true
!= q false
Logical Operators (boolean)
&& || !
• Logical AND
&&
• Logical OR
||
• Logical NOT
!
Logical Operators
•
Boolean expressions can also use the following logical operators:
!
&&
||
Logical NOT
Logical AND
Logical OR
•
They all take boolean operands and produce boolean results
•
Logical NOT is a unary operator (it operates on one operand)
•
Logical AND and logical OR are binary operators (each operates on two
operands)
Logical Operators
• Expressions that use logical operators can
form complex conditions
if (total < MAX + 5 && !found)
System.out.println ("Processing…");
• All logical operators have lower precedence than
the relational operators
• Logical NOT has higher precedence than logical
AND and logical OR
Logical (&&) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("f
System.out.println("f
System.out.println("t
System.out.println("t
&&
&&
&&
&&
f
t
f
t
"
"
"
"
+
+
+
+
(f
(f
(t
(t
&&
&&
&&
&&
f));
t));
f));
t));
}
}
>
f
f
t
t
>
java
&& f
&& t
&& f
&& t
Example
false
false
false
true
Logical (||) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("f
System.out.println("f
System.out.println("t
System.out.println("t
||
||
||
||
f
t
f
t
"
"
"
"
+
+
+
+
(f
(f
(t
(t
||
||
||
||
f));
t));
f));
t));
}
}
>
f
f
t
t
>
java
|| f
|| t
|| f
|| t
Example
false
true
true
true
Logical (!) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("!f " + !f);
System.out.println("!t " + !t);
}
}
> java Example
!f true
!t false
>
Logical Operator Examples
Short Circuiting with &&
public class Example {
public static void main(String[] args) {
boolean b;
int j, k;
j = 0; k = 0;
b = ( j++ == k ) && ( j == ++k );
System.out.println("b, j, k " + b + ", " + j + ", " + k);
}
}
j = 0; k = 0;
b = ( j++ != k ) && ( j == ++k );
System.out.println("b, j, k " + b + ", " + j + ", " + k);
> java Example
b, j, k true 1, 1
b, j, k false 1, 0
>
Logical Operator Examples
Short Circuiting with ||
public class Example {
public static void main(String[] args) {
boolean b;
int j, k;
j = 0; k = 0;
b = ( j++ == k ) || ( j == ++k );
System.out.println("b, j, k " + b + ", " + j + ", " + k);
}
}
j = 0; k = 0;
b = ( j++ != k ) || ( j == ++k );
System.out.println("b, j, k " + b + ", " + j + ", " + k);
> java Example
b, j, k true 1, 0
b, j, k true 1, 1
>
Manipulating Bits: Bitwise Operators
Logical Operators (Bit Level)
& | ^ ~
•
•
•
•
AND
OR
XOR
NOT
&
|
^
~
Logical Operators (Bit Level)
& | ^ ~
int a = 10; // 00001010 = 10
int b = 12; // 00001100 = 12
&
AND
|
OR
^
XOR
~
NOT
a
00000000000000000000000000001010
b
00000000000000000000000000001100
a & b 00000000000000000000000000001000
10
12
8
a
b
a | b
00000000000000000000000000001010
00000000000000000000000000001100
00000000000000000000000000001110
10
12
14
a
b
a ^ b
00000000000000000000000000001010
00000000000000000000000000001100
00000000000000000000000000000110
10
12
6
a
~a
00000000000000000000000000001010
11111111111111111111111111110101
10
-11
Logical (bit) Operator Examples
public class Example {
public static void main(String[] args) {
int a = 10;
// 00001010 = 10
int b = 12;
// 00001100 = 12
int and, or, xor, na;
and = a & b;
// 00001000 = 8
or = a | b;
// 00001110 = 14
xor = a ^ b;
// 00000110 = 6
na = ~a;
// 11110101 = -11
System.out.println("and " + and);
System.out.println("or " + or);
System.out.println("xor " + xor);
System.out.println("na " + na);
}
}
> java Example
and 8
or 14
xor 6
na -11
>
Shift Operators (Bit Level)
<< >> >>>
• Shift Left
<<
Fill with Zeros
• Shift Right
>>
Based on Sign
• Shift Right
>>>
Fill with Zeros
Shift Operators << >>
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4
<<
Left
>>
Right
a
a << 2
00000000000000000000000000000011
00000000000000000000000000001100
3
12
b
b << 2
11111111111111111111111111111100
11111111111111111111111111110000
-4
-16
a
a >> 2
00000000000000000000000000000011
00000000000000000000000000000000
3
0
b
b >> 2
11111111111111111111111111111100
11111111111111111111111111111111
-4
-1
Shift Operator >>>
int a = 3; // ...00000011 = 3
int b = -4; // ...11111100 = -4
>>>
Right 0
a
00000000000000000000000000000011
a >>> 2 00000000000000000000000000000000
3
0
b
11111111111111111111111111111100
b >>> 2 00111111111111111111111111111111
-4
+big
Shift Operator Examples
public class Example {
public static void main(String[] args) {
int a = 3;
// ...00000011 = 3
int b = -4;
// ...11111100 = -4
System.out.println("a<<2 = " + (a<<2));
System.out.println("b<<2 = " + (b<<2));
System.out.println("a>>2 = " + (a>>2));
System.out.println("b>>2 = " + (b>>2));
System.out.println("a>>>2 = " + (a>>>2));
System.out.println("b>>>2 = " + (b>>>2));
}
}
> java Example
a<<2 = 12
b<<2 = -16
a>>2 = 0
b>>2 = -1
a>>>2 = 0
b>>>2 = 1073741823
>
Shift Operator >>> and
Automatic Arithmetic Promotion
byte a = 3;
byte b = -4;
byte c;
c = (byte) a
c = (byte) b
>>>
Right
Fill 0
// 00000011 = 3
// 11111100 = -4
>>> 2
>>> 2
a
00000011
a >>> 2
00000000000000000000000000000000
c = (byte)
00000000
3
0
0
b
11111100
-4
b >>> 2
00111111111111111111111111111111 1073741823
c = (byte) Much to big for byte
11111111
-1
Bitmask
• Is Monday Chosen?
• Are Monday and Thursday
Chosen?
• Are all days except Sunday is
Chosen?
Days Picker
How to build this
application?
Bitmask
ENCODING
Days Picker
Day
Binary
Decimal
Monday
00000001 1
Tuesday
00000010 2
Wednesday
00000100 4
Thursday
00001000 8
Friday
0 0 0 1 0 0 0 0 16
Saturday
0 0 1 0 0 0 0 0 32
Sunday
0 1 0 0 0 0 0 0 64
Bitmask
Code
int Selection=0;
final int Monday=1;
final int Tuesday=2;
final int Wednesday=4;
Days Picker
final int Thursday=8;
final int Friday=16;
final int Saturday=32;
final int Sunday=64;
Bitwise OR (|)
1. Selection=Selection | Monday
2. Selection=Selection | Thursday
Bitmask
i. Is Monday Chosen?
ii. Are Monday and Thursday
Chosen?
iii. Are all days except Sunday is
Chosen?
How to test?????
Use Bitwise AND (&)
Days Picker
If, Selection=00110110
Then, (Selection & Monday)=false;
Because: Selection & Monday
Selection00110110
Monday& 00000001
00000000
Bitwise Tricks
• check if an integer is a power of 2.
– If x & ( x – 1) is zero then the number is a power of
2.
– x & (x - 1) Returns number x with the lowest bit set
off
• The expression (1 << n) is equivalent to 2
raised to the power of n.
• Exchanging values with xor
– x = x ^ y; y = x ^ y; x = x ^ y;
Operator Precedence
Conditional Statements
• A conditional statement lets us choose which statement
will be executed next
• Therefore they
statements
are
sometimes
called
selection
• Conditional statements give us the power to make basic
decisions
• The Java conditional statements are the:
– if statement
– if-else statement
– switch statement
The if Statement
• The if statement has the following syntax:
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
if ( condition )
statement;
If condition is true: statement is executed.
If condition is false: statement is skipped.
Logic of an if statement
condition
evaluated
true
statement
false
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
• If the condition is true, statement1 is executed; if the
condition is false, statement2 is executed
• One or the other will be executed, but not both
Logic of an if-else statement
condition
evaluated
true
false
statement1
statement2
Block Statements
• In an if-else statement, the if portion, or the
else portion, or both, could be block statements
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
else
{
System.out.println ("Total: " + total);
current = total*2;
}
The Conditional Operator
• Java has a conditional operator that uses a boolean
condition to determine which of two expressions is
evaluated
• Syntax:
condition
express_2
?
express_1
:
• If the condition is true, express_1 is evaluated;
• if the condition is false express_2 is evaluated;
• The value of the entire conditional operator is the value
of the selected expression
Ternary Operator
?:
Any expression that evaluates
to a boolean value.
boolean_expression ? expression_1 : expression_2
If true this expression is
evaluated and becomes the
value entire expression.
If false this expression is
evaluated and becomes the
value entire expression.
Ternary ( ? : ) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("t?true:false
System.out.println("t?1:2 "+(t ?
System.out.println("f?true:false
System.out.println("f?1:2 "+(f ?
"+(t ? true : false ));
1 : 2 ));
"+(f ? true : false ));
1 : 2 ));
}
}
> java Example
t?true:false true
t?1:2 1
f?true:false false
f?1:2 2
>
The switch Statement
• The general syntax of a switch statement is:
switch
and
case
are
reserved
words
switch ( expression )
{
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
If expression
matches value2,
control jumps
to here
The switch Statement
• An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
The switch Statement
• The expression of a switch statement must
result into byte, short, int, char,enum
or String class only.
• It cannot be a boolean value or a floating
point value (float or double)
• You cannot perform relational checks with a
switch statement
The switch Statement
class StringSwitch
{
public static void main(String args[])
{
String str = "two";
switch(str)
{
case "one":System.out.println("one");
break;
case "two": System.out.println("two");
break;
case "three":System.out.println("three");
break;
default: System.out.println("no match");
break;
}
}
}
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled
by boolean expressions
• Java has three kinds of repetition statements:
– the while loop
– the do loop
– the for loop
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
• If the condition is true, the statement is
executed
• Then the condition is evaluated again, and if it is
still true, the statement is executed again
• The statement is executed repeatedly until the
condition becomes false
Logic of a while Loop
condition
evaluated
true
statement
false
The while Statement
• An example of a while statement:
int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}
• If the condition of a while loop is false initially, the
statement is never executed
• Therefore, the body of a while loop will execute
zero or more times
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200
The do-while Statement
• A do statement has the following syntax:
do
{
statement;
}
while ( condition );
• The statement is executed once initially, and then
the condition is evaluated
• The statement is executed repeatedly until the
condition becomes false
Logic of a do-while Loop
statement
true
condition
evaluated
false
The do-while Statement
• An example of a do loop:
int count = 0;
do
{
count++;
System.out.println (count);
} while (count < 5);
• The body of a do loop executes at least once.
Comparing while and do-while
The while Loop
The do Loop
statement
condition
evaluated
true
statement
true
false
condition
evaluated
false
The for Statement
• A for statement has the following syntax:
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
for ( initialization ; condition ; increment )
statement;
The increment portion is executed at
the end of each iteration
Logic of a for loop
initialization
condition
evaluated
true
statement
increment
false
Unlabeled Break Statement
labeled Break Statement
Unlabeled Continue Statement
labeled Continue Statement
ARRAYS
An array is a group of like-typed variables that are referred to by a common
name.
• Each element is accessed by its numerical index.
• Numbering begins with 0. The 9th element would be accessed at index 8.
We can create an array by:
 Declaring an array reference variable to store the address of an array object.
 Creating an array object using the new operator and assigning the address of
the array to the array reference variable.
ARRAYS
double[ ] dailySales;
The brackets after the key word double indicate that the
variable is an array reference variable which :
– can hold the address of an array of values of type double.
dailySales = new double[7];
The operand of the new operator is the data type of the
individual array elements .
A bracketed value that is the array size declarator
– number of elements in the array.
– must be an integer expression with a value greater than zero.
70
ARRAYS
• It is possible to declare an array reference variable and
create the array object it references in a single statement.
Here is an example:
double[ ] dailySales = new double[7];
71
ARRAYS
The statement below creates a reference variable named
dailySales and an array object that can store seven values of
type double as illustrated below:
double[ ] dailySales = new double[7];
dailySales address
1st value
2nd value
3rd value
4th value
5th value
6th value
7th value
72
ARRAYS
ArrayDemo.java
The output from this program is:
Element
Element
Element
Element
Element
Element
Element
Element
Element
Element
at index 0: 100
at index 1: 200
at index 2: 300
at index 3: 400
at index 4: 500
at index 5: 600
at index 6: 700
at index 7: 800
at index 8: 900
at index 9: 1000
USE Of Named Constants
The statements below define a named constant called
MAX_STUDENTS and an array with room for one hundred
elements of type int that is referenced by a variable named
testScores.
final int MAX_STUDENTS = 100;
int [ ] testScores = new int [MAX_STUDENTS];
74
JAVA Performs Bounds Checking
• Java does its bounds checking at runtime.
• The compiler does not display an error message when
it processes a statement that uses an invalid subscript.
• Instead, Java throws an exception and terminates the
program when a statement is executed that uses a
subscript outside the array bounds.
75
Array Initialization
• Like other variables, you may give array elements an initial value
when creating the array.
Example:
The statement below declares a reference variable named
temperatures, creates an array object with room for exactly tens
values of type double, and initializes the array to contain the
values specified in the initialization list.
double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99,111.5};
76
Array Initialization
• A series comma-separated values inside braces is an initialization
list.
• The values specified are stored in the array in the order in which
they appear.
• Java determines the size of the array from the number of
elements in the initialization list.
double[ ] temperatures = {98.6, 112.3, 99.5, 96, 96.7, 32, 39, 18.1, 99, 111.5};
temperatures
address
98.6
[0]
112.3
[1]
99.5
[2]
96.0
[3]
96.7
[4]
32.0
[5]
39.0
[6]
18.1
[7]
99.0
[8]
111.5
[9]
77
Array Initialization
• By default, Java initializes the array elements of a numeric
array with the value 0.
int[ ] attendance = new int[5] ;
attendance
address
0
[0]
0
[1]
0
[2]
0
[3]
0
[4]
78
Array Length
• Each array object has an attribute/field named length. This
attribute contains the number of elements in the array.
For example, in the segment below the variable named
size is assigned the value 5, since the array referenced by
values has 5 elements.
int size;
int[ ] values = {13, 21, 201, 3, 43};
size = values.length;
Notice, length is an attribute of an array not a method - hence no
parentheses.
79
Array Length
To display the elements of the array referenced by values, we could
write:
int count;
int[ ] values = {13, 21, 201, 3, 43};
Notice, the valid
subscripts are zero
through values.length - 1.
for (count = 0; count < values.length; count++)
{
System.out.println("Value #" + (count + 1) + " in the list of values is "
+ values[count]);
}
80
Reassigning Array Reference
Variables
short[ ] oldValues = {10, 100, 200, 300};
short[ ] newValues = new short[4];
newValues = oldValues;
// Does not make a copy of the contents of the array referenced by oldValues
81
Copying the Contents of One
Array to Another Array
class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
82
Comparing Arrays
The decision in the segment below does not correctly
determine if the contents of the two arrays are the same.
char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};
char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};
boolean equal = false;
if (array1 == array2) // This is a logical error
{
equal = true;
}
83
Comparing Arrays
We are comparing the addresses stored in the reference
variables array1 and array2. The two arrays are not stored in
the same memory location so the conditional expression is
false and the value of equal stays at false.
char[ ] array1 = {'A', 'B', 'C', 'D', 'A'};
char[ ] array2 = {'A', 'B', 'C', 'D', 'A'};
boolean equal = false;
if (array1 == array2) // This is false - the addresses are not equal
{
equal = true;
}
84
Enhanced for /for-each loop
•
•
•
Use it in preference to the standard for loop if applicable because it's much
more readable.
Series of values. It is used to access each successive value in a collection of
values.
Arrays. It's commonly used to iterate over an array.
85
Enhanced for /for-each loop
public class ExtendedForDemo
{
public static void main(String [] args)
{
double[] ar = {1.2, 3.0, 0.8};
double sum = 0.0;
for (double d : ar)
{
sum += d;
}
System.out.println("Sum="+sum);
}
}
86