0% found this document useful (0 votes)
62 views20 pages

Java Basics

The document discusses various operators in Java programming including assignment, arithmetic, unary, equality, relational, conditional, type comparison, and bitwise operators. The simple assignment operator "=" assigns a value to a variable. Common arithmetic operators perform basic math operations. Unary operators operate on a single operand like increment/decrement. Equality and relational operators compare values. Conditional operators like "&&" and "?:" are used to evaluate boolean conditions. The "instanceof" operator compares an object to a specified type. Bitwise operators perform operations on bits of integral values.

Uploaded by

Linndowws
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
62 views20 pages

Java Basics

The document discusses various operators in Java programming including assignment, arithmetic, unary, equality, relational, conditional, type comparison, and bitwise operators. The simple assignment operator "=" assigns a value to a variable. Common arithmetic operators perform basic math operations. Unary operators operate on a single operand like increment/decrement. Equality and relational operators compare values. Conditional operators like "&&" and "?:" are used to evaluate boolean conditions. The "instanceof" operator compares an object to a specified type. Bitwise operators perform operations on bits of integral values.

Uploaded by

Linndowws
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Basic Programming JAVA

Assignment, Arithmetic, and Unary Operators

The Simple Assignment Operator


One of the most common operators that you'll encounter is the simple assignment operator "="
it assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;

This operator can also be used on objects to assign object references.

The Arithmetic Operators


The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their counterparts in
basic mathematics. The only symbol that might look new to you is "%", which divides one operand
by another and returns the remainder as its result.
Operator
+
*
/
%

Description
Additive operator (also used for String concatenation)
Subtraction operator
Multiplication operator
Division operator
Remainder operator

class ArithmeticDemo {
public static void main (String[] args) {
int result = 1 + 2;
// result is now 3
System.out.println("1 + 2 = " + result);
int original_result = result;
result = result - 1;
// result is now 2
System.out.println(original_result + " - 1 = " + result);
original_result = result;
result = result * 2;
// result is now 4
System.out.println(original_result + " * 2 = " + result);
original_result = result;
result = result / 2;
// result is now 2
System.out.println(original_result + " / 2 = " + result);

original_result = result;
result = result + 8;
// result is now 10
System.out.println(original_result + " + 8 = " + result);
original_result = result;
result = result % 7;
// result is now 3
System.out.println(original_result + " % 7 = " + result);
}

You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}

By the end of this program, the variable thirdString contains "This is a concatenated string.",
which gets printed to standard output.

The Unary Operators


The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value of a
boolean.
Operator

Description
Unary plus operator; indicates positive value (numbers are positive without this,
+
however)
Unary minus operator; negates an expression
++
Increment operator; increments a value by 1
-Decrement operator; decrements a value by 1
!
Logical complement operator; inverts the value of a boolean
The following program, UnaryDemo tests the unary operators:
class UnaryDemo {
public static void main(String[] args) {
int result = +1;
// result is now 1
System.out.println(result);
result--;
// result is now 0

System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);

boolean success = false;


// false
System.out.println(success);
// true
System.out.println(!success);

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.
The code result++; and ++result; will both end in result being incremented by one. The
only difference is that the prefix version (++result) evaluates to the incremented value, whereas
the postfix version (result++) evaluates to the original value. If you are just performing a simple
increment/decrement, it doesn't really matter which version you choose. But if you use this operator
in part of a larger expression, the one that you choose may make a significant difference.
The following program illustrates the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}

Equality, Relational, and Conditional Operators

The Equality and Relational Operators


The equality and relational operators determine if one operand is greater than, less than, equal to, or
not equal to another operand. The majority of these operators will probably look familiar to you as
well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
==
!=
>
>=
<
<=

equal to
not equal to
greater than
greater than or equal to
less than
less than or equal to

The following program, ComparisonDemo, tests the comparison operators:


class ComparisonDemo {

public static void main(String[] args){


int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}

Output:
value1 != value2
value1 < value2
value1 <= value2

The Conditional Operators


The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the
second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR

The following program, ConditionalDemo1, tests these operators:


class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;

if((value1 == 1) && (value2 ==


System.out.println("value1
if((value1 == 1) || (value2 ==
System.out.println("value1
}

2))
is 1 AND value2 is 2");
1))
is 1 OR value2 is 1");

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else
statement. This operator is also known as the ternary operator because it uses three operands. In the
following example, this operator should be read as: "If someCondition is true, assign the
value of value1 to result. Otherwise, assign the value of value2 to result."
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator
instead of an if-then-else statement if it makes your code more readable; for example, when
the expressions are compact and without side-effects (such as assignments).

The Type Comparison Operator instanceof


The instanceof operator compares an object to a specified type. You can use it to test if an
object is an instance of a class, an instance of a subclass, or an instance of a class that implements a
particular interface.
The following program, InstanceofDemo, defines a parent class (named Parent), a simple
interface (named MyInterface), and a child class (named Child) that inherits from the parent
and implements the interface.
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));

System.out.println("obj2 instanceof MyInterface: "


+ (obj2 instanceof MyInterface));
}

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

Output:
obj1
obj1
obj1
obj2
obj2
obj2

instanceof
instanceof
instanceof
instanceof
instanceof
instanceof

Parent: true
Child: false
MyInterface: false
Parent: true
Child: true
MyInterface: true

When using the instanceof operator, keep in mind that null is not an instance of anything.

Bitwise and Bit Shift Operators


The Java programming language also provides operators that perform bitwise and bit shift
operations on integral types. The operators discussed in this section are less commonly used.
Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the
integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits;
applying this operator to a value whose bit pattern is "00000000" would change its pattern to
"11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the
number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>"
shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign
extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to
standard output.
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);
}
}

Summary of Operators

Simple Assignment Operator


=

Simple assignment operator

Arithmetic Operators
+
*
/
%

Additive operator (also used for String concatenation)


Subtraction operator
Multiplication operator
Division operator
Remainder operator

Unary Operators
+
without
++
-!

Unary plus operator; indicates positive value (numbers are positive


this, however)
Unary minus operator; negates an expression
Increment operator; increments a value by 1
Decrement operator; decrements a value by 1
Logical complement operator; inverts the value of a boolean

Equality and Relational Operators


==
!=
>
>=
<
<=

Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to

Conditional Operators
&&
||
?:

Conditional-AND
Conditional-OR
Ternary (shorthand for if-then-else statement)

Type Comparison Operator


instanceof

Compares an object to a specified type

Bitwise and Bit Shift Operators


~
<<
>>
>>>
&
^
|

Unary bitwise complement


Signed left shift
Signed right shift
Unsigned right shift
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR

Expressions, Statements, and Blocks


Now that you understand variables and operators, it's time to learn about expressions, statements,
and blocks. Operators may be used in building expressions, which compute values; expressions are
the core components of statements; statements may be grouped into blocks.

Expressions
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language, that evaluates to a single value.
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the
expression. The expression cadence = 0 returns an int because the assignment operator
returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As
you can see from the other expressions, an expression can return other types of values as well, such
as boolean or String.
The Java programming language allows you to construct compound expressions from various
smaller expressions as long as the data type required by one part of the expression matches the data
type of the other. Here's an example of a compound expression:
1 * 2 * 3

In this particular example, the order in which the expression is evaluated is unimportant because the
result of multiplication is independent of order; the outcome is always the same, no matter in which
order you apply the multiplications. However, this is not true of all expressions. For example, the
following expression gives different results, depending on whether you perform the addition or the
division operation first:
x + y / 100

// ambiguous

You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ).
For example, to make the previous expression unambiguous, you could write the following:
(x + y) / 100

// unambiguous, recommended

If you don't explicitly indicate the order for the operations to be performed, the order is determined
by the precedence assigned to the operators in use within the expression.

Operators that have a higher precedence get evaluated first. For example, the division operator has a
higher precedence than does the addition operator. Therefore, the following two statements are
equivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended

When writing compound expressions, be explicit and indicate with parentheses which operators
should be evaluated first. This practice makes code easier to read and to maintain.

Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete
unit of execution. The following types of expressions can be made into a statement by terminating
the expression with a semicolon (;).

Assignment expressions
Any use of ++ or -Method invocations
Object creation expressions

Such statements are called expression statements. Examples of expression statements:


// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();

In addition to expression statements, there are two other kinds of statements: declaration statements
and control flow statements. A declaration statement declares a variable. You've seen many
examples of declaration statements already:
// declaration statement
double aValue = 8933.234;

Finally, control flow statements regulate the order in which statements get executed.
Blocks
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is
allowed.
class BlockDemo {
public static void main(String[] args) { boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}

The if-then Statement


The if-then statement is the most basic of all the control flow statements. It tells your program
to execute a certain section of code only if a particular test evaluates to true. For example, the
Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already
in motion. One possible implementation of the applyBrakes method could be as follows:
void applyBrakes() {
// the "if" clause: bicycle must be moving
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end
of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains
only one statement:
void applyBrakes() {
// same as above, but without braces
if (isMoving)
currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code
more brittle. If a second statement is later added to the "then" clause, a common mistake would be
forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just
get the wrong results.

The if-then-else Statement


The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false. You could use an if-then-else statement in the applyBrakes method
to take some action if the brakes are applied when the bicycle is not in motion. In this case, the
action is to simply print an error message stating that the bicycle has already stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}

The following program assigns a grade based on the value of a test score: an A for a score of 90% or
above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;

char grade;

if (testscore >= 90) {


grade = 'A';
} else if (testscore >= 80)
grade = 'B';
} else if (testscore >= 70)
grade = 'C';
} else if (testscore >= 60)
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade =

{
{
{

" + grade);

The output from the program is:


Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the
compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the
appropriate statements are executed (grade = 'C';) and the remaining conditions are not
evaluated
The switch Statement

Unlike if-then and if-then-else statements, the switch statement can have a number of
possible execution paths. A switch works with the byte, short, char, and int primitive data
types. It also works with enumerated types, the String class, and a few special classes that wrap
certain primitive types: Character, Byte, Short, and Integer.
The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value of month, using
the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString
break;
case 2: monthString
break;
case 3: monthString
break;
case 4: monthString
break;
case 5: monthString
break;
case 6: monthString
break;
case 7: monthString
break;
case 8: monthString
break;

= "January";
= "February";
= "March";
= "April";
= "May";
= "June";
= "July";
= "August";

case 9:
case 10:
case 11:
case 12:
default:

monthString
break;
monthString
break;
monthString
break;
monthString
break;
monthString
break;

= "September";
= "October";
= "November";
= "December";
= "Invalid month";

}
System.out.println(monthString);
}

In this case, August is printed to standard output.


The body of a switch statement is known as a switch block. A statement in the switch block can
be labeled with one or more case or default labels. The switch statement evaluates its
expression, then executes all statements that follow the matching case label.
You could also display the name of the month with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on

Deciding whether to use if-then-else statements or a switch statement is based on


readability and the expression that the statement is testing. An if-then-else statement can test
expressions based on ranges of values or conditions, whereas a switch statement tests expressions
based only on a single integer, enumerated value, or String object.
Another point of interest is the break statement. Each break statement terminates the enclosing
switch statement. Control flow continues with the first statement following the switch block.
The break statements are necessary because without them, statements in switch blocks fall
through: All statements after the matching case label are executed in sequence, regardless of the
expression of subsequent case labels, until a break statement is encountered. The program
SwitchDemoFallThrough shows statements in a switch block that fall through. The
program displays the month corresponding to the integer month and the months that follow in the
year:
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths =
new java.util.ArrayList<String>();
int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");

case
case
case
case
case
case
case
case
case
case

3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

futureMonths.add("March");
futureMonths.add("April");
futureMonths.add("May");
futureMonths.add("June");
futureMonths.add("July");
futureMonths.add("August");
futureMonths.add("September");
futureMonths.add("October");
futureMonths.add("November");
futureMonths.add("December");
break;
default: break;
}

if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
} else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}

This is the output from the code:


August
September
October
November
December

Technically, the final break is not required because flow falls out of the switch statement. Using
a break is recommended so that modifying the code is easier and less error prone. The default
section handles all values that are not explicitly handled by one of the case sections.
The following code example shows how a statement can have multiple case labels. The code
example calculates the number of days in a particular month:
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;

else

numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}

This is the output from the code:


Number of Days = 29

Using Strings in switch Statements


In Java SE 7 and later, you can use a String object in the switch statement's expression. The
following code example, StringSwitchDemo, displays the number of the month based on the
value of the String named month:
public class StringSwitchDemo {
public static int getMonthNumber(String month) {
int monthNumber = 0;
if (month == null) {
return monthNumber;
}
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;

break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}
}

return monthNumber;

public static void main(String[] args) {


String month = "August";
int returnedMonthNumber =
StringSwitchDemo.getMonthNumber(month);

if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {
System.out.println(returnedMonthNumber);
}

The output from this code is 8.


The String in the switch expression is compared with the expressions associated with each
case label as if the String.equals method were being used. In order for the
StringSwitchDemo example to accept any month regardless of case, month is converted to
lowercase (with the toLowerCase method), and all the strings associated with the case labels
are in lowercase.
Note: This example checks if the expression in the switch statement is null. Ensure that the
expression in any switch statement is not null to prevent a NullPointerException from
being thrown.

Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an
array is established when the array is created. After creation, its length is fixed.

An array of 10 elements.

Each item in an array is called an element, and each element is accessed by its numerical index. As
shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would
therefore be accessed at index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in the array,
and prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index
+ anArray[0]);
System.out.println("Element at index
+ anArray[1]);
System.out.println("Element at index
+ anArray[2]);
System.out.println("Element at index
+ anArray[3]);
System.out.println("Element at index
+ anArray[4]);
System.out.println("Element at index
+ anArray[5]);
System.out.println("Element at index
+ anArray[6]);
System.out.println("Element at index
+ anArray[7]);
System.out.println("Element at index
+ anArray[8]);
System.out.println("Element at index
+ anArray[9]);
}

The output from this program is:


Element
Element
Element
Element
Element
Element

at
at
at
at
at
at

index
index
index
index
index
index

0:
1:
2:
3:
4:
5:

100
200
300
400
500
600

0: "
1: "
2: "
3: "
4: "
5: "
6: "
7: "
8: "
9: "

Element
Element
Element
Element

at
at
at
at

index
index
index
index

6:
7:
8:
9:

700
800
900
1000

In a real-world programming situation, you would probably use one of the supported looping
constructs to iterate through each element of the array, rather than write each line individually as in
the preceding example. However, the example clearly illustrates the array syntax.

Declaring a Variable to Refer to an Array


The preceding program declares an array (named anArray) with the following line of code:
// declares an array of integers
int[] anArray;

Like declarations for variables of other types, an array declaration has two components: the array's
type and the array's name. An array's type is written as type[], where type is the data type of the
contained elements; the brackets are special symbols indicating that this variable holds an array. The
size of the array is not part of its type (which is why the brackets are empty). An array's name can
be anything you want, provided that it follows the rules and conventions. As with variables of other
types, the declaration does not actually create an array; it simply tells the compiler that this variable
will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];

However, convention discourages this form; the brackets identify the array type and should appear
with the type designation.

Creating, Initializing, and Accessing an Array


One way to create an array is with the new operator. The next statement in the ArrayDemo
program allocates an array with enough memory for 10 integer elements and assigns the array to the
anArray variable.
// create an array of integers
anArray = new int[10];

If this statement is missing, then the compiler prints an error like the following, and compilation
fails:
ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

Each array element is accessed by its numerical index:


System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray
100, 200,
400, 500,
700, 800,
};

= {
300,
600,
900, 1000

Here the length of the array is determined by the number of values provided between braces and
separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two or
more sets of brackets, such as String[][] names. Each element, therefore, must be accessed
by a corresponding number of index values.
In the Java programming language, a multidimensional array is an array whose components are
themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are
allowed to vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}

The output from this program is:


Mr. Smith
Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The following
code prints the array's size to standard output:
System.out.println(anArray.length);

Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one
array into another:
public static void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int
arguments specify the starting position in the source array, the starting position in the destination
array, and the number of array elements to copy.
The following program, ArrayCopyDemo, declares an array of char elements, spelling the word
"decaffeinated." It uses the System.arraycopy method to copy a subsequence of array
components into a second 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));

The output from this program is:


caffein

Array Manipulations
Arrays are a powerful and useful concept used in programming. Java SE provides methods to
perform some of the most common manipulations related to arrays. For instance, the
ArrayCopyDemo example uses the arraycopy method of the System class instead of
manually iterating through the elements of the source array and placing each one into the
destination array. This is performed behind the scenes, enabling the developer to use just one line of
code to call the method.
For your convenience, Java SE provides several methods for performing array manipulations
(common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class.
For instance, the previous example can be modified to use the copyOfRange method of the
java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference
is that using the copyOfRange method does not require you to create the destination array before
calling the method, because the destination array is returned by the method:
class ArrayCopyOfDemo {
public static void main(String[] args) {
char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd'};

char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);


}

System.out.println(new String(copyTo));

As you can see, the output from this program is the same (caffein), although it requires fewer
lines of code. Note that the second parameter of the copyOfRange method is the initial index of
the range to be copied, inclusively, while the third parameter is the final index of the range to be
copied, exclusively. In this example, the range to be copied does not include the array element at
index 9 (which contains the character a).
Some other useful operations provided by methods in the java.util.Arrays class, are:
Searching an array for a specific value to get the index at which it is placed (the
binarySearch method).
Comparing two arrays to determine if they are equal or not (the equals method).
Filling an array to place a specific value at each index (the fill method).
Sorting an array into ascending order. This can be done either sequentially, using the sort
method, or concurrently, using the parallelSort method introduced in Java SE 8.
Parallel sorting of large arrays on multiprocessor systems is faster than sequential array
sorting.

You might also like