Primitive Data Types: Arrays
Primitive Data Types: Arrays
The Java programming language is statically-typed, which means that all variables must first be
declared before they can be used. This involves stating the variable's type and name, as you've
already seen:
int gear = 1;
Doing so tells your program that a field named "gear" exists, holds numerical data, and has an
initial value of "1". A variable's data type determines the values it may contain, plus the
operations that may be performed on it. In addition to int, the Java programming language
supports seven other primitive data types. A primitive type is predefined by the language and is
named by a reserved keyword. Primitive values do not share state with other primitive values.
The eight primitive data types supported by the Java programming language are:
byte: The byte data type is an 8-bit signed two's complement integer. It has a
minimum value of -128 and a maximum value of 127 (inclusive). The byte data
type can be useful for saving memory in large arrays, where the memory savings
actually matters. They can also be used in place of int where their limits help to
clarify your code; the fact that a variable's range is limited can serve as a form of
documentation.
short: The short data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with
byte, the same guidelines apply: you can use a short to save memory in large
arrays, in situations where the memory savings actually matters.
int: The int data type is a 32-bit signed two's complement integer. It has a
minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
(inclusive). For integral values, this data type is generally the default choice
unless there is a reason (like the above) to choose something else. This data type
will most likely be large enough for the numbers your program will use, but if you
need a wider range of values, use long instead.
long: The long data type is a 64-bit signed two's complement integer. It has a
minimum value of -9,223,372,036,854,775,808 and a maximum value of
9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range
of values wider than those provided by int.
float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its
range of values is beyond the scope of this discussion, but is specified in section
4.2.3 of the Java Language Specification. As with the recommendations for byte
and short, use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. This data type should never be used for precise
values, such as currency. For that, you will need to use the java.math.BigDecimal
class instead. Numbers and Strings covers BigDecimal and other useful classes
provided by the Java platform.
double: The double data type is a double-precision 64-bit IEEE 754 floating
point. Its range of values is beyond the scope of this discussion, but is specified in
section 4.2.3 of the Java Language Specification. For decimal values, this data
type is generally the default choice. As mentioned above, this data type should
never be used for precise values, such as currency.
boolean: The boolean data type has only two possible values: true and false.
Use this data type for simple flags that track true/false conditions. This data type
represents one bit of information, but its "size" isn't something that's precisely
defined.
char: The char data type is a single 16-bit Unicode character. It has a minimum
value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535
inclusive).
In addition to the eight primitive data types listed above, the Java programming language also
provides special support for character strings via the java.lang.String class. Enclosing your
character string within double quotes will automatically create a new String object; for
example, String s = "this is a string";. String objects are immutable, which means that
once created, their values cannot be changed. The String class is not technically a primitive data
type, but considering the special support given to it by the language, you'll probably tend to think
of it as such. You'll learn more about the String class in Simple Data Objects
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but
not initialized will be set to a reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such default values, however, is
generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Local variables are slightly different; the compiler never assigns a default value to an
uninitialized local variable. If you cannot initialize your local variable where it is declared, make
sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable
will result in a compile-time error.
Literals
You may have noticed that the new keyword isn't used when initializing a variable of a primitive
type. Primitive types are special data types built into the language; they are not objects created
from a class. A literal is the source code representation of a fixed value; literals are represented
directly in your code without requiring computation. As shown below, it's possible to assign a
literal to a variable of a primitive type:
The floating point types (float and double) can also be expressed using E or e (for scientific
notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by
convention is omitted).
double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;
Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor
and file system allow it, you can use such characters directly in your code. If not, you can use a
"Unicode escape" such as '\u0108' (capital C with circumflex), or "S\u00ED se\u00F1or" (Sí
Señor in Spanish). Always use 'single quotes' for char literals and "double quotes" for String
literals. Unicode escape sequences may be used elsewhere in a program (such as in field names,
for example), not just in char or String literals.
The Java programming language also supports a few special escape sequences for char and
String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \"
(double quote), \' (single quote), and \\ (backslash).
There's also a special null literal that can be used as a value for any reference type. null may be
assigned to any variable, except variables of primitive types. There's little you can do with a
nullvalue beyond testing for its presence. Therefore, null is often used in programs as a
marker to indicate that some object is unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name
and appending ".class"; for example, String.class. This refers to the object (of type Class)
that represents the type itself.
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. You've seen
an example of arrays already, in the main method of the "Hello World!" application. This section
discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the above 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 it, and
prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
In a real-world programming situation, you'd probably use one of the supported looping
constructs to iterate through each element of the array, rather than write each line individually as
shown above. However, this example clearly illustrates the array syntax. You'll learn about the
various looping constructs (for, while, and do-while) in the Control Flow section.
The above program declares anArray with the following line of code:
int[] anArray; // declares an array of integers
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 square 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 previously discussed in the naming section. 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.
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the square brackets after the array's name:
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 ten integer elements and assigns the array to
the anArray variable.
anArray = new int[10]; // create an array of integers
If this statement were missing, the compiler would print an error like the following, and
compilation would fail:
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; // etc.
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, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using two or
more sets of square brackets, such as String[][] names. Each element, therefore, must be
accessed by a corresponding number of index values.
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}
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 code
System.out.println(anArray.length);
will print the array's size to standard output.
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 arraycopy 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];
caffein
Bitwise Operators
Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand
is shorter than an int, it is promoted to int before doing the operations.
It helps to know how integers are represented in binary. For example the decimal number 3 is
represented as 11 in binary and the decimal number 5 is represented as 101 in binary. Negative
integers are store in two's complement form. For example, -4 is 1111 1111 1111 1111 1111 1111
1111 1100.
left Shifts the bits of n left p positions. Zero bits are shifted into the
n << p 3 <<< 2 12
shift low-order positions.
A common use of the bitwise operators (shifts with ands to extract values and ors to add values)
is to work with multiple values that have been encoded in one int. Bit-fields are another way to
do this. For example, let's say you have the following integer variables: age (range 0-127),
gender (range 0-1), height (range 0-128). These can be packed and unpacked into/from one short
(two-byte integer) like this (or many similar variations).
Some library functions take an int that contains bits, each of which represents a true/false
(boolean) value. This saves a lot of space and can be fast to process. [needs example]
On some older computers it was faster to use shift instead of multiply or divide.
Here's some weird code. It uses xor to exchange two values (x and y). This is translated to Java
from an assembly code program, where there was no available storage for a temporary. Never
use it; this is just a curiosity from the museum of bizarre code.
x = x ^ y;
y = x ^ y;
x = x ^ y;
Don't confuse &&, which is the short-circuit logical and, with &, which is the uncommon bitwise
and. Altho the bitwise and can also be used with boolean operands, this is extremely rare and is
almost always a programming error.
Class Boolean
java.lang.Object
|
+--java.lang.Boolean
All Implemented Interfaces:
Serializable
extends Object
implements Serializable
The Boolean class wraps a value of the primitive type boolean in an object. An object of type
Boolean contains a single field whose type is boolean.
In addition, this class provides many methods for converting a boolean to a String and a
String to a boolean, as well as other constants and methods useful when dealing with a
boolean.
Since:
JDK1.0
See Also:
Serialized Form
Field Summary
static Boolean FALSE
The Boolean object corresponding to the primitive value false.
static Boolean TRUE
The Boolean object corresponding to the primitive value true.
static Class TYPE
The Class object representing the primitive type boolean.
Constructor Summary
Boolean(boolean value)
Allocates a Boolean object representing the value argument.
Boolean(String s)
Allocates a Boolean object representing the value true if the string argument is not null and
is equal, ignoring case, to the string "true".
Method Summary
boolean booleanValue()
Returns the value of this Boolean object as a boolean primitive.
boolean equals(Object obj)
Returns true if and only if the argument is not null and is a Boolean
object that represents the same boolean value as this object.
static boolean getBoolean(String name)
Returns true if and only if the system property named by the argument
exists and is equal to the string "true".
int hashCode()
Returns a hash code for this Boolean object.
String toString()
Returns a String object representing this Boolean's value.
static Boolean valueOf(String s)
Returns a Boolean with a value represented by the specified String.
Field Detail
TRUE
public static final Boolean TRUE
The Boolean object corresponding to the primitive value true.
FALSE
public static final Boolean FALSE
The Boolean object corresponding to the primitive value false.
TYPE
public static final Class TYPE
The Class object representing the primitive type boolean.
Since:
JDK1.1
Constructor Detail
Boolean
public Boolean(boolean value)
Allocates a Boolean object representing the value argument.
Parameters:
Boolean
public Boolean(String s)
Allocates a Boolean object representing the value true if the string argument is not null and
is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing
the value false. Examples:
Parameters:
Method Detail
booleanValue
public boolean booleanValue()
Returns the value of this Boolean object as a boolean primitive.
Returns:
valueOf
public static Boolean valueOf(String s)
Returns a Boolean with a value represented by the specified String. The Boolean returned
represents the value true if the string argument is not null and is equal, ignoring case, to the
string "true".
Parameters:
s - a string.
Returns:
toString
public String toString()
Returns a String object representing this Boolean's value. If this object represents the value
true, a string equal to "true" is returned. Otherwise, a string equal to "false" is returned.
Overrides:
Returns:
hashCode
public int hashCode()
Returns a hash code for this Boolean object.
Overrides:
Returns:
the integer 1231 if this object represents true; returns the integer 1237 if this object
represents false.
equals
public boolean equals(Object obj)
Returns true if and only if the argument is not null and is a Boolean object that represents
the same boolean value as this object.
Overrides:
Parameters:
Returns:
true if the Boolean objects represent the same value; false otherwise.
getBoolean
public static boolean getBoolean(String name)
Returns true if and only if the system property named by the argument exists and is equal to
the string "true". (Beginning with version 1.0.2 of the Java platform, the test of this string is
TM
If there is no property with the specified name, or if the specified name is empty or null,
then false is returned.
Parameters:
Returns:
See Also:
System.getProperty(java.lang.String),
System.getProperty(java.lang.String, java.lang.String)
Logical Operators in Java
The relational operators you've learned so far (<, <=, >, >=, !=, ==) are sufficient when you only
need to check one condition. However what if a particular action is to be taken only if several
conditions are true? You can use a sequence of if statements to test the conditions, as follows:
if (x == 2) {
if (y != 2) {
System.out.println("Both conditions are true.");
}
}
This, however, is hard to write and harder to read. It only gets worse as you add more conditions.
Fortunately, Java provides an easy way to handle multiple conditions: the logic operators. There
are three logic operators, &&, || and !.
&& is logical and. && combines two boolean values and returns a boolean which is true if and only
if both of its operands are true. For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
|| is logical or. || combines two boolean variables or expressions and returns a result that is true
if either or both of its operands are true. For instance
boolean b;
b = 3 > 2 || 5 < 7; // b is true
b = 2 > 3 || 5 < 7; // b is still true
b = 2 > 3 || 5 > 7; // now b is false
The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus
if b is true !b is false. If b is false !b is true.
boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b is true
These operators allow you to test multiple conditions more easily. For instance the previous
example can now be written as
if (x == 2 && y != 2) {
System.out.println("Both conditions are true.");
}
If you've never used an object-oriented programming language before, you'll need to learn a few
basic concepts before you can begin writing any code. This lesson will introduce you to objects,
classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts
relate to the real world, while simultaneously providing an introduction to the syntax of the Java
programming language.
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll
find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state
(name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have
state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing
pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a
great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For
each object that you see, ask yourself two questions: "What possible states can this object be in?"
and "What possible behavior can this object perform?". Make sure to write down your
observations. As you do, you'll notice that real-world objects vary in complexity; your desktop
lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn
off), but your desktop radio might have additional states (on, off, current volume, current station)
and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You
may also notice that some objects, in turn, will also contain other objects. These real-world
observations all translate into the world of object-oriented programming.
A software object.
Software objects are conceptually similar to real-world objects: they too consist of state and
related behavior. An object stores its state in fields (variables in some programming languages)
and exposes its behavior through methods (functions in some programming languages). Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object
communication. Hiding internal state and requiring all interaction to be performed through an
object's methods is known as data encapsulation — a fundamental principle of object-oriented
programming.
By attributing state (current speed, current pedal cadence, and current gear) and providing
methods for changing that state, the object remains in control of how the outside world is
allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could
reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can be
easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software
developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust to
run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be problematic,
you can simply remove it from your application and plug in a different object as
its replacement. This is analogous to fixing mechanical problems in the real
world. If a bolt breaks, you replace it, not the entire machine.
5. What Is a Class?
6. In the real world, you'll often find many individual objects all of the same kind.
There may be thousands of other bicycles in existence, all of the same make and
model. Each bicycle was built from the same set of blueprints and therefore
contains the same components. In object-oriented terms, we say that your bicycle
is an instance of the class of objects known as bicycles. A class is the blueprint
from which individual objects are created.
7. The following Bicycle class is one possible implementation of a bicycle:
8.
9. class Bicycle {
10.
11. int cadence = 0;
12. int speed = 0;
13. int gear = 1;
14.
15. void changeCadence(int newValue) {
16. cadence = newValue;
17. }
18.
19. void changeGear(int newValue) {
20. gear = newValue;
21. }
22.
23. void speedUp(int increment) {
24. speed = speed + increment;
25. }
26.
27. void applyBrakes(int decrement) {
28. speed = speed - decrement;
29. }
30.
31. void printStates() {
32. System.out.println("cadence:"+cadence+"
speed:"+speed+" gear:"+gear);
33. }
34. }
35. The syntax of the Java programming language will look new to you, but the
design of this class is based on the previous discussion of bicycle objects. The
fields cadence, speed, and gear represent the object's state, and the methods
(changeCadence, changeGear, speedUp etc.) define its interaction with the
outside world.
36. You may have noticed that the Bicycle class does not contain a main method.
That's because it's not a complete application; it's just the blueprint for bicycles
that might be used in an application. The responsibility of creating and using new
Bicycle objects belongs to some other class in your application.
37. Here's a BicycleDemo class that creates two separate Bicycle objects and
invokes their methods:
38.
39. class BicycleDemo {
40. public static void main(String[] args) {
41.
42. // Create two different Bicycle objects
43. Bicycle bike1 = new Bicycle();
44. Bicycle bike2 = new Bicycle();
45.
46. // Invoke methods on those objects
47. bike1.changeCadence(50);
48. bike1.speedUp(10);
49. bike1.changeGear(2);
50. bike1.printStates();
51.
52. bike2.changeCadence(50);
53. bike2.speedUp(10);
54. bike2.changeGear(2);
55. bike2.changeCadence(40);
56. bike2.speedUp(10);
57. bike2.changeGear(3);
58. bike2.printStates();
59. }
60. }
61.
62. The output of this test prints the ending pedal cadence, speed, and gear for the two
bicycles:
63. cadence:50 speed:10 gear:2
64. cadence:40 speed:20 gear:3
What Is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain
bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current
speed, current pedal cadence, current gear). Yet each also defines additional features that make
them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop
handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from
other classes. In this example, Bicycle now becomes the superclass of MountainBike,
RoadBike, and TandemBike. In the Java programming language, each class is allowed to have
one direct superclass, and each superclass has the potential for an unlimited number of
subclasses:
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to
focus exclusively on the features that make it unique. This makes code for your subclasses easy
to read. However, you must take care to properly document the state and behavior that each
superclass defines, since that code will not appear in the source file of each subclass.
What Is an Interface?
As you've already learned, objects define their interaction with the outside world through the
methods that they expose. Methods form the object's interface with the outside world; the
buttons on the front of your television set, for example, are the interface between you and the
electrical wiring on the other side of its plastic casing. You press the "power" button to turn the
television on and off.
In its most common form, an interface is a group of related methods with empty bodies. A
bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
}
Implementing an interface allows a class to become more formal about the behavior it promises
to provide. Interfaces form a contract between the class and the outside world, and this contract
is enforced at build time by the compiler. If your class claims to implement an interface, all
methods defined by that interface must appear in its source code before the class will
successfully compile.
The statements inside your source files are generally executed from top to bottom, in the order
that they appear. Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute
particular blocks of code. This section describes the decision-making statements (if-then, if-
then-else, switch), the looping statements (for, while, do-while), and the branching
statements (break, continue, return) supported by the Java programming language.
In addition, the opening and closing braces are optional, provided that the "then" clause contains
only one statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}
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 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, IfElseDemo, 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) {
The following program, SwitchDemo, declares an int named month whose value represents a
month out of the year. The program displays the name of the month, based on the value of
month, using the switch statement.
class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels. The
switch statement evaluates its expression and executes the appropriate case.
Of course, you could also implement the same thing 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 sometimes a
judgment call. You can decide which one to use based on readability and other factors. An if-
then-else statement can be used to make decisions based on ranges of values or conditions,
whereas a switch statement can make decisions based only on a single integer or enumerated
value.
Another point of interest is the break statement after each case. 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, case
statements fall through; that is, without an explicit break, control will flow sequentially through
subsequent case statements. The following program, SwitchDemo2, illustrates why it might be
useful to have case statements fall through:
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);
}
}
Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement
anyway. However, we recommend using a break so that modifying the code is easier and less
error-prone. The default section handles all values that aren't explicitly handled by one of the
case sections.
You can implement an infinite loop using the while statement as follows:
while (true){
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed as
follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
The initialization expression initializes the loop; it's executed once, as the loop
begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this
variable extends from its declaration to the end of the block governed by the for statement, so it
can be used in the termination and increment expressions as well. If the variable that controls a
for statement is not needed outside of the loop, it's best to declare the variable in the
initialization expression. The names i, j, and k are often used to control for loops; declaring
them within the initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
The for statement also has another form designed for iteration through Collections and arrays
This form is sometimes referred to as the enhanced for statement, and can be used to make your
loops more compact and easy to read. To demonstrate, consider the following array, which holds
the numbers 1 through 10:
The following program, EnhancedForDemo, uses the enhanced for to loop through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array. The output
from this program is the same as before:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We recommend using this form of the for statement instead of the general form whenever
possible
Branching Statements
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the
previous discussion of the switch statement. You can also use an unlabeled break to terminate a
for, while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int i;
boolean foundIt = false;
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface,
terminates the for loop when that value is found. Control flow then transfers to the print
statement at the end of the program. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while
statement, but a labeled break terminates an outer statement. The following program,
BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for
a value in a two-dimensional array. When the value is found, a labeled break terminates the
outer for loop (labeled "search"):
class BreakWithLabelDemo {
public static void main(String[] args) {
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to
the label. Control flow is transferred to the statement immediately following the labeled
(terminated) statement.
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
To see this effect more clearly, try removing the continue statement and recompiling. When
you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.
A labeled continue statement skips the current iteration of an outer loop marked with the given
label. The following example program, ContinueWithLabelDemo, uses nested loops to search
for a substring within another string. Two nested loops are required: one to iterate over the
substring and one to iterate over the string being searched. The following program,
ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer
loop.
class ContinueWithLabelDemo {
public static void main(String[] args) {
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++)
!= substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}
Found it
The last of the branching statements is the return statement. The return statement exits from
the current method, and control flow returns to where the method was invoked. The return
statement has two forms: one that returns a value, and one that doesn't. To return a value, simply
put the value (or an expression that calculates the value) after the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return value.
When a method is declared void, use the form of return that doesn't return a value.
return;
The Classes and Objects lesson will cover everything you need to know about writing methods.
The main difference between c++ and java is that "C++ does
not allow persistence because it does not support database
connection while Java allows persistence because it
supports database connection."
The main differences between c++ and Java are that "The
features that are present in C++ are not present in Java.
1) Pointers.
2) Templates.