Arrays & Operators In Java
What is an Array
• An array is a block of consecutive memory
locations of the same data type.
• Individual locations are called array’s elements.
• Sometimes when we say “array’s element” we
mean the value stored in that element.
1.39 1.69 1 .74 0 .0 An array of doubles
Declaration of an Array
• There are two ways to declare an array:
anyType arrName [ ];
or
anyType [ ] arrName;
The difference becomes significant
only when several variables are
declared in one statement:
only when several variables are
declared in one statement:
int [ ] a, b; // both a, b are arrays
int a [ ], b; // a is an array, b is not
Initialization (cont’d)
• An array can be declared an initialized in one
statement:
int scores [ ] = new int [10] ; // length 10
private double gasPrices [ ] = { 1.49, 1.69, 1.74 };
String words [ ] = new String [10000];
String cities [ ] = {"Atlanta", "Boston", "Cincinnati" };
Array’s Length
• The length of an array is determined when that
array is created.
• The length is either given explicitly or comes from
the length of the {…} initialization list.
• The length of an array arrName is referred to in
the code as arrName.length.
• length appears like a public field (not a method) in
an array object.
Two-Dimensional Arrays
• 2-D arrays are used to represent tables,
matrices, game boards, images, etc.
• An element of a 2-D array is addressed
using a pair of indices, “row” and “column.”
For example:
board [ r ] [ c ] = 'x';
2-D Arrays: Declaration
// 2-D array of char with 5 rows, 7 cols:
char letterGrid [ ] [ ] = new char [5][7];
// 2-D array of Color with 1024 rows, 768 cols:
Color image [ ] [ ] = new Color [1024][768];
// 2-D array of double with 2 rows and 3 cols:
double sample [ ] [ ] ={ { 0.0, 0.1, 0.2 },{ 1.0, 1.1, 1.2 } };
Operators in Java
Operators in Java
• Arithmetic operators: + , - , * , / , %
• Increment and decrement operators: ++,--
• Relational Operators : <, >, <=, >=, !=, ==
• Bitwise Operators: <<, >>, &, |, ^, ~
• Logical Operators: &&, ||, !
• Assignment Operators : =
• Conditional or ternary operator: (condition) ? (if part)
: (else part)
No comments:
Post a Comment