You are on page 1of 33

Chapter Two

Introduction to Java elements


The Program and Its Execution
 A computer is a complex system consisting of many different components. But at the heart—
or the brain, of the computer is a single component that does the actual computing. This is
the Central Processing Unit, or CPU. In a modern desktop computer, the CPU is a single
―chip‖ on the order of one square inch in size. The job of the CPU is to execute programs.
 A program is simply a list of unambiguous instructions meant to be followed mechanically by
a computer. A computer is built to carry out instructions that are written in a very simple
type of language called machine language.
 Each type of computer has its own machine language, and the computer can directly
execute a program only if the program is expressed in that language. (It can execute
programs written in other languages if they are first translated into machine
language.)
 When the CPU executes a program, that program is stored in the computer’s main memory
(also called the RAM or random access memory). In addition to the program, memory can
also hold data that is being used or processed by the program.
 Main memory consists of a sequence of locations. These locations are numbered, and the
sequence number of a location is called its address. An address provides a way of picking out
one particular piece of information from among the millions stored in memory.
 When the CPU needs to access the program instruction or data in a particular location, it
sends the address of that information as a signal to the memory; the memory responds by
sending back the value contained in the specified location. The CPU can also store
information in memory by specifying the information to be stored and the address of the
location where it is to be stored.
 On the level of machine language, the operation of the CPU is fairly straightforward
(although it is very complicated in detail). The CPU executes a program that is stored as a
sequence of machine language instructions in main memory. It does this by repeatedly
reading, or fetching, an instruction from memory and then carrying out, or executing, that
instruction. This process—fetch an instruction, execute it, fetch another instruction, execute
it, and so on forever—is called the fetch-and-execute cycle.
 A computer executes machine language programs mechanically—that is without
understanding them or thinking about them—simply because of the way it is physically put
together.
 Machine language instructions are expressed as binary numbers. A binary number is made up
of just two possible digits, zero and one. Each zero or one is called a bit. So, a machine
language instruction is just a sequence of zeros and ones. Each particular sequence encodes
some particular instruction. The data that the computer manipulates is also encoded as

1
binary numbers. In modern computers, each memory location holds a byte, which is a
sequence of eight bits. A machine language instruction or a piece of data generally consists of
several bytes, stored in consecutive memory locations. For example, when a CPU reads an
instruction from memory, it might actually read four or eight bytes from four or eight
memory locations; the memory address of the instruction is the address of the first of those
bytes.
 Summary about how computers work? Main memory holds machine language programs and
data. These are encoded as binary numbers. The CPU fetches machine language instructions
from memory one after another and executes them. Each instruction makes the CPU perform
some very small task, such as adding two numbers or moving data to or from memory. The
CPU does all this mechanically, without thinking about or understanding what it does—and
therefore the program it executes must be perfect, complete in all details, and unambiguous
because the CPU can do nothing but execute it exactly as written.

Types of Programming Languages


 Programmers write instructions in various programming languages, some directly
understandable by computers and others requiring intermediate translation steps. Hundreds
of computer languages are in use today. These may be divided into three general types:
machine languages, assembly languages and high-level languages
 Any computer can directly understand only its own machine language. Machine language is
the ―natural language‖ of a computer and as such is defined by its hardware design. Machine
languages generally consist of strings of binary numbers (ultimately reduced to 1s and 0s)
that instruct computers to perform their most elementary operations one at a time. Machine
languages are machine dependent (i.e., a particular machine language can be used on only
one type of computer).Such languages are cumbersome for humans. Machine-language
programming was simply too slow and tedious for most programmers.
 Instead of using the strings of numbers that computers could directly understand,
programmers began using English-like abbreviations to represent elementary operations.
These abbreviations formed the basis of assembly languages. Translator programs called
assemblers were developed to convert early assembly-language programs to machine
language at computer speeds.
 Although assembly code is clearer to humans, it is incomprehensible to computers until
translated to machine language. Computer usage increased rapidly with the advent of
assembly languages, but programmers still had to use many instructions to accomplish even
the simplest tasks. To speed the programming process, high-level languages were developed
in which single statements could be written to accomplish substantial tasks. Translator
programs called compilers convert high-level language programs into machine language.
 High-level languages allow programmers to write instructions that look almost like every day
English and contain commonly used mathematical notations high-level languages are
preferable to machine and assembly language from the programmer’s standpoint. C, C++,
Microsoft’s .NET languages (e.g., Visual Basic.NET, Visual C++ .NET andC#) are among
the most widely used high-level programming languages; Java is the most widely used.

2
 A program written in a high-level language cannot be run directly on any computer. First, it
has to be translated into machine language. This translation can be done by a program called
a compiler. A compiler takes a high-level-language program and translates it into an
executable machine-language program. Once the translation is done, the machine-language
program can be run any number of times, but of course it can only be run on one type of
computer (since each type of computer has its own individual machine language). If the
program is to run on another type of computer it has to be re-translated, using a different
compiler, into the appropriate machine language.
 The process of compiling a high-level language program into machine language can take a
considerable amount of computer time. There is an alternative to compiling a high-level
language program. Instead of using a compiler, which translates the program all at once, you
can use an interpreter, which translates it instruction-by-instruction, as necessary. An
interpreter is a program that acts much like a CPU, with a kind of fetch-and-execute cycle. In
order to execute a program, the interpreter runs in a loop in which it repeatedly reads one
instruction from the program, decides what is necessary to carry out that instruction, and
then performs the appropriate machine-language commands to do so.
 There are ultimately two ways to translate a high-level language program into a form that
the computer understands—compilation and interpretation. A compiler is like a human
translator who translates an entire book from one language to another, producing a new book
in the second language. An interpreter is more like a human interpreter who translates a
speech at the parliament from one language to another at the same time that the speech is
being given.

History of java
 History of Java The microprocessor revolution’s most important contribution to date is that
it made possible the development of personal computers, which now number about a billion
worldwide. Personal computers have profoundly affected people’s lives and the ways
organizations conduct and manage their business. Microprocessors are having a profound
impact in intelligent consumer-electronic devices.
 Recognizing this, Sun Microsystems in 1991 funded an internal corporate research project
code-named Green, which resulted in a C++-based language that its creator, James Gosling,
called Oak after an oak tree outside his window at Sun. It was later discovered that there
already was a computer language by that name. When a group of Sun people visited a local
coffee shop, the name Java was suggested, and it stuck.
 The Green project ran into some difficulties. The marketplace for intelligent consumer-
electronic devices was not developing in the early 1990s as quickly as Sun had anticipated.
The project was in danger of being canceled. By sheer good fortune, the World Wide Web
exploded in popularity in 1993, and Sun people saw the immediate potential of using Java to
add dynamic content, such as interactivity and animations, to web p ages. This breathed new
life into the project. Sun formally announced Java at an industry conference in May 1995.
Java garnered the attention of the business community because of the phenomenal interest in
the World Wide Web.
 Java is now used to

3
 Develop large-scale enterprise applications
 Enhance the functionality of web servers (the computers that provide the content we
see in our web browsers)
 Provide applications for consumer devices (e.g., cell phones, pagers and personal digital
assistants) and for many other purposes.

The Five Phases of Java Program


 Java programs normally go through five phases—edit, compile, load, verify and execute.
 Phase1: Creating a Program: Consists of editing a file with an editor program (normally
known simply as an editor). You type a Java program (typically referred to as source code)
using the editor, make an y necessary corrections and save the program on a secondary
storage device, such as your hard drive. A file name ending with the.java extension indicates
that the file contains Java source code.
 Phase 2: Compiling a Java Program into Byte codes: The programmer uses Java compiler to
compile a program. For example, to compile a program called Welcome.java, If the program
compiles, the compiler produces a .class file called Welcome.class that contains the compiled
version of the program. The Java compiler translates Java source code into bytecodes that
represent the tasks to execute in the execution phase (Phase 5). Bytecodes are executed by
the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the Java
platform. A virtual machine (VM) is a software application that simulates a computer, but
hides the underlying operating system and hardware from the programs that interact with
the VM.
 Phase 3: Loading a Program into Memory: The program must be placed in memory before it
can execute—known as loading. The class loader takes the .class files containing the
program’s bytecodes and transfers them to primary memory. The class loader also loads any
of the .class files provided by Java that your program uses.
 Phase 4: Bytecode Verification: As the classes are loaded, the bytecode verifier examines their
bytecodes to ensure that they are valid and do not violate Java’s security restrictions. Java
enforces strong security, to make sure that Java programs arriving over the network do not
damage your files or your system (as computer viruses and worms might).
 Phase 5: Execution: the JVM executes the program’s bytecodes: Performing the actions
specified by the program. In early Java versions, the JVM was simply an interpreter for Java
bytecodes. This caused most Java programs to execute slowly because the JVM would
interpret and execute one bytecode at a time. Today’s JVMs typically execute bytecodes
using a combination of interpretation and so-called just-in-time (JIT) compilation. In this
process, The JVM analyzes the bytecodes as they are interpreted, searching for hot spots—
parts of the bytecodes that execute frequently. For these parts, a just-in-time (JIT)
compiler—known as the Java HotSpot compiler—translates the bytecodes into the underlying
computer’s machine language. When the JVM encounters these compiled parts again, the
faster machine-language code executes. Thus Java programs actually go through two
compilation phases—one in which source code is translated into bytecodes (for portability
across JVMs on different computer platforms) and a second in which, during execution, the

4
bytecodes are translated into machine language for the actual computer on which the
program executes. Figure bellow illustrates the five phases

5
The Java Development Environment
 A software development environment is the set of tools used to create, test, and modify a
program. Some development environments are available for free while others, which may
have advanced features, must be purchased. Some environments are referred to as integrated
development environments (IDEs) because they integrate various tools into one software
program and provide a convenient graphical user interface.
 Any java development environment will contain certain key tools, such as a Java compiler
and interpreter. Some will include a debugger, which helps you find errors in a program.
Other tools that may be included are documentation generators, archiving tools, and tools
that help you visualize your program structure.
 Java technology applications are typically general-purpose programs that run on any
machine where the Java runtime environment (JRE) is installed. Java Technology mainly
consists two parts : JDK and JRE
 JDK(Java Software Development kit (SDK) is a free software development package
from Sun Microsystems that implements the basic set of tools needed to write, test
and debug Java applications and applets.
 It is a toolkit for developers that include the Java compiler and the runtime
environment.
 JRE is the program that emulates the JVM, so that users can run Java programs. To
run Java programs, you need download and install the JRE.
 JRE runs code compiled for a JVM and performs class loading (through the class
loader), code verification (through the byte code verifier) and finally code execution.
 JRE =JVM + additional libraries
 JVM=class loader + byte code verifier + interpreter + just in compiler
 JDK = java compiler + debugger + JRE
 To write Java programs, you need the JDK installed where as to run java programs
you need JRE

Why is java preferable?


 Platform independence

The designers of Java chose to use a combination of compiling and interpreting. Programs written in
Java are compiled into machine language, but it is a machine language for a computer that doesn’t
really exist. This so-called ―virtual‖ computer is known as the Java Virtual Machine, or JVM. The
machine language for the Java Virtual Machine is called Java bytecode. All that the computer needs
is an interpreter for Java bytecode. (The term JVM is also used for the Java bytecode interpreter
program that does the simulation, so we say that a computer needs a JVM in order to run Java
programs. Of course, a different Java bytecode interpreter is needed for each type of computer, but
once a computer has a Java bytecode interpreter, it can run any Java bytecode program, and the
same program can be run on any computer that has such an interpreter. This is one of the essential
features of Java: the same compiled program can be run on many different types of computers.

6
Why, you might wonder, use the intermediate Java bytecode at all? Why not just distribute the
original Java program and let each person compile it into the machine language of whatever
computer they want to run it on? There are several reasons. First of all, a compiler has to understand
Java, a complex high-level language. The compiler is itself a complex program. A Java bytecode
interpreter, on the other hand, is a relatively small, simple program. This makes it easy to write a
bytecode interpreter for a new type of computer; once that is done, that computer can run any
compiled Java program. It would be much harder to write a Java compiler for the same computer.

Furthermore, some Java programs are meant to be downloaded over a network. This leads to obvious
security concerns: you don’t want to download and run a program that will damage your computer or
your files. The bytecode interpreter acts as a buffer between you and the program you download. You
are really running the interpreter, which runs the downloaded program indirectly. The interpreter can
protect you from potentially dangerous actions on the part of that program.

When Java was still a new language, it was criticized for being slow: Since Java bytecode was
executed by an interpreter, it seemed that Java bytecode programs could never run as quickly as
programs compiled into native machine language (that is, the actual machine language of the
computer on which the program is running). However, this problem has been largely overcome by the
use of just-in-time compilers for executing Java bytecode. A just-in-time compiler translates Java
bytecode into native machine language. It does this while it is executing the program. Just as for a
normal interpreter, the input to a just-in-time compiler is a Java bytecode program, and its task is to
execute that program. But as it is executing the program, it also translates parts of it into machine
language. The translated parts of the program can then be executed much more quickly than they
could be interpreted. Since a given part of a program is often executed many times as the program
runs, a just-in-time compiler can significantly speed up the overall execution time.

 In addition to platform independency java programs have the following characteristics:


 Easier to learn the syntax and hence easy to program. Especially If you know C/C++,
the transition to the Java syntax easy. There are also extensive and freely available
helpful libraries
 Java is object oriented language[Next chapters]

7
 Distributed: Java has an extensive library of routines for coping with TCP/IP
protocols like HTTP and FTP. Java applications can open and access objects across
the Net via URLs with the same ease as when accessing a local file system.
 Robust: Java is intended for writing programs that must be reliable in a variety of
ways. Java puts a lot of emphasis on early checking for possible problems, later
dynamic (run-time) checking, and eliminating situations that are error-prone[memory
management capabilities makes it special).
 Secure: Java is intended to be used in networked/distributed environments. Toward
that end, a lot of emphasis has been placed on security. Java enables the construction
of virus-free, tamper-free systems.
 Interpreted: The Java interpreter can execute Java bytecodes directly on any machine
to which the interpreter has been ported.
 High Performance: While the performance of interpreted bytecodes is usually more
than adequate, there are situations where higher performance is required. The
bytecodes can be translated on the fly (at run time) into machine code for the
particular CPU the application is running on.

Simple Program in java

Let's look more closely at about the simplest Java program you can have—one that simply prints a
message to the console window:

public class FirstSample


{
public static void main(String[] args)
{
System.out.println("We will not use 'Hello, World!'");
}
}

 Java is case sensitive. If you made any mistakes in capitalization (such as typing Main
instead of main), the program will not run.
 The keyword public is called an access modifier; these modifiers control the level of access
other parts of a program have to this code. [more on that later].
 The keyword class reminds you that everything in a Java program lives inside a class. A class
can be considered as a container for the program logic that defines the behavior of an
application. Classes are the building blocks with which all Java applications and applets are
built. Everything in a Java program must be inside a class.

 Following the keyword class is the name of the class. The rules for class names in Java are
quite generous. Names must begin with a letter, and after that, they can have any
combination of letters and digits. The length is essentially unlimited. You cannot use a Java
reserved word (such as public or class) for a class name. Below are lists of java keywords.The
standard naming convention (which we follow in the name FirstSample) is that class names
are nouns that start with an uppercase letter. If a name consists of multiple words, use an
initial uppercase letter in each of the words.

8
 You need to make the file name for the source code the same as the name of the public class,
with the extension .java appended. Thus, you must store this code in a file called
FirstSample.java. (Again, case is important—don't use firstsample.java.)
 If you have named the file correctly and not made any typos in the source code, then when
you compile this source code, you end up with a file containing the bytecodes for this class.
The Java compiler automatically names the bytecode file FirstSample.class and stores it in
the same directory as the source file.
 To run a compiled program, the Java virtual machine always starts execution with the code
in the main method in the class you indicate. Thus, you must have a main method in the
source file for your class for your code to execute. You can, of course, add your own methods
to a class and call them from the main method.
 The braces { } in the source code. In Java, as in C/C++, braces delineate the parts (usually
called blocks) in your program. In Java, the code for any method must be started by an
opening brace { and ended by a closing brace }.
 For now, don't worry about the keywords static void—just think of them as part of what you
need to get a Java program to compile. The point to remember for now is that every Java
application must have a main method that is declared in the following way:

Public class ClassName


{
public static void main(String[] args)
{
program statements
}
}

 Next, turn your attention to this fragment.

9
System.out.println("We will not use 'Hello, World!'");
}

 Braces mark the beginning and end of the body of the method. This method has only one
statement in it. As with most programming languages, you can think of Java statements as
being the sentences of the language. In Java, every statement must end with a semicolon. In
particular, carriage returns do not mark the end of a statement, so statements can span
multiple lines if need be.
 The body of the main method contains a statement that outputs a single line of text to the
console. Here, we are using the System.out object and calling its println method. Notice the
periods used to invoke a method. Java uses the general syntax: object.method(parameters)
 In this case, we are calling the println method and passing it a string parameter. The method
displays the string parameter on the console. It then terminates the output line so that each
call to println displays its output on a new line. Notice that Java, like C/C++, uses double
quotes to delimit strings. (You can find more information about strings later in this chapter.)
 Methods in Java, like functions in any programming language, can use zero, one, or more
parameters (some programmers call them arguments). Even if a method takes no parameters,
you must still use empty parentheses. For example, a variant of the println method with
no parameters just prints a blank line. You invoke it with the call

System.out.println();

 Comments: Comments in Java, like comments in most programming languages, do not show
up in the executable program. Thus, you can add as many comments as needed without fear
of bloating the code. Java has two ways of marking comments. The most common method is
a //. You use this for a comment that will run from the // to the end of the line.

System.out.println("We will not use 'Hello, World!'"); // is this too cute?

 When longer comments are needed, you can mark each line with a //. Or you can use the /*
and */ comment delimiters that let you block off a longer comment. The above code is
repeated here with comments.

FirstSample.java

1. /*
2. This is the first sample program in java
3. Copyright
4. */
5.
6. public class FirstSample
7. {
8. public static void main(String[] args)
9. {
10. System.out.println("We will not use 'Hello, World!'");
11. }
12. }

10
Data Types
Java is a strongly typed language. This means that every variable must have a declared type. There
are eight primitive types in Java. Four of them are integer types; two are floating-point number
types; one is the character type char and one is a boolean type for truth values.

 Integers: The integer types are for numbers without fractional parts. Negative values
are allowed. Java provides the four integer types as shown in the beginning of page
four.

 In most situations, the int type is the most practical. If you want to represent the
number of inhabitants of our planet, you'll need to resort to a long. The byte and
short types are mainly intended for specialized applications, such as low-level file
handling, or for large arrays when storage space is at a premium.
 Long integer numbers have a suffix L (for example, 4000000000L). Hexadecimal
numbers have a prefix 0x (for example, 0xCAFE). Octal numbers have a prefix 0. For
example, 010 is 8.
 int type requires 4bytes, short requires 2bytes , long requires 8 bytes and byte
requires 1byte memory storage

 Floating-Point Types: The floating-point types denote numbers with fractional parts.
The two floating-point types are : float (requires 4 bytes storage) and double( requires
8 bytes storage)

 The name double refers to the fact that these numbers have twice the precision of the
float type. (Some people call these double-precision numbers.) Here, the type to
choose in most applications is double. The limited precision of float is simply not
sufficient for many situations. Seven significant (decimal) digits may be enough to
precisely express your annual salary in dollars and cents, but it won't be enough for
other's salary. The only reasons to use float are in the rare situations in which the
slightly faster processing of single-precision numbers is important or when you need to
store a large number of them.
 Numbers of type float have a suffix F (for example, 3.402F). Floating-point numbers
without an F suffix (such as 3.402) are always considered to be of type double. You
can optionally supply the D suffix (for example, 3.402D).
 The char Type: char type variable holds a single character from the Unicode character
set.
 To type a value of type char in a program, you must surround it with a pair of single
quote marks, such as ’A’, ’*’, or ’x’. The character and the quote marks make up a
literal of type char. Without the quotes, A would be an identifier (name for variable or
method or class) and * would be a multiplication operator.
 The quotes are not part of the value and are not stored in the variable; they are just a
convention for naming a particular character constant in a program. If you want to
store the character A in a variable ch of type char, you could do so with the
assignment statement ch = ’A’;
 Certain special characters have special literals that use a backslash, \, as an ―escape
character.‖ In particular, a tab is represented as ’\t’, a carriage return as ’\r’, a linefeed
as ’\n’, the single quote character as ’\’’, and the backslash itself as ’\\’. Note that even
though you type two characters between the quotes in ’\t’, the value represented by
this literal is a single tab character.

11
Escape Sequence Name
\b Backspace
\t Tab
\n Linefeed
\" Double quote
\' Single quote
\\ Backslash
 The boolean type: The boolean type has two values, false and True. It is used for
evaluating logical conditions. You cannot convert between integers and boolean
values.

Variables

 In Java, every variable has a type. You declare a variable by placing the type first, followed
by the name of the variable. Here are some examples:

double salary;
int vacationDays;
long earthPopulation;
boolean done;

 Notice the semicolon at the end of each declaration. The semicolon is necessary because a
declaration is a complete Java statement.
 A variable name must begin with a letter and must be a sequence of letters or digits. A letter
is defined as 'A'–'Z', 'a'–'z', '_', Similarly, digits are '0'–'9'.
 Symbols like '+' or '©' cannot be used inside variable names, nor can spaces. All characters in
the name of a variable are significant and case is also significant. The length of a variable
name is essentially unlimited. You also cannot use a Java reserved word for a variable name,
 You can have multiple declarations on a single line:

int i, j; // both are integers

 Initializing Variables: After you declare a variable, you must explicitly initialize it by means
of an assignment statement—you can never use the values of uninitialized variables. For
example, the Java compiler flags the following sequence of statements as an error:
int vacationDays;
System.out.println(vacationDays); // ERROR--variable not initialized

 You assign to a previously declared variable by using the variable name on the left, an equal
sign (=), and then some Java expression that has an appropriate value on the right.

int vacationDays;
vacationDays = 12;

12
 You can both declare and initialize a variable on the same line. For example:

int vacationDays = 12;

 Finally, in Java you can put declarations anywhere in your code. For example, the following
is valid code in Java:

double salary = 65000.0;


System.out.println(salary);
int vacationDays = 12; // ok to declare a variable here
 Constants: In Java, you use the keyword final to denote a constant. For example,
public class Constants
{
public static void main(String[] args)
{
final double CM_PER_INCH = 2.54;
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "
+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);
}
}

 The keyword final indicates that you can assign to the variable once, and then its value is set
once and for all. It is customary to name constants in all upper case.
 It is probably more common in Java to want a constant that is available to multiple methods
inside a single class. These are usually called class constants. You set up a class constant with
the keywords static final. Here is an example of using a class constant:

public class Constants2


{
public static void main(String[] args)
{
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters: "
+ paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH);
}

public static final double CM_PER_INCH = 2.54;


}

 Note that the definition of the class constant appears outside the main method. Thus, the
constant can also be used in other methods of the same class. Furthermore, if (as in our
example) the constant is declared public, methods of other classes can also use the constant—
in our example, as Constants2.CM_PER_INCH.

Operators

 The usual arithmetic operators + – * / are used in Java for addition, subtraction,
multiplication, and division. The / operator denotes integer division if both arguments are

13
integers, and floating-point division otherwise. Integer remainder (sometimes called modulus)
is denoted by %. For example, 15 / 2 is 7, 15 % 2 is 1, and 15.0 / 2 is 7.5.
 Note that integer division by 0 raises an exception, whereas floating-point division by 0 yields
an infinite or NaN result.
 There is a convenient shortcut for using binary arithmetic operators in an assignment. For
example, x += 4; is equivalent to x = x + 4;(In general, place the operator to the left of the =
sign, such as *= or %=.)
 Increment and Decrement Operators: Programmers, of course, know that one of the most
common operations with a numeric variable is to add or subtract 1. Java, following in the
footsteps of C and C++, has both increment and decrement operators: n++ adds 1 to the
current value of the variable n, and n-- subtracts 1 from it. For example, the code
int n = 12;
n++;
changes n to 13. Because these operators change the value of a variable, they cannot be applied to
numbers themselves. For example, 4++ is not a legal statement.

 There are actually two forms of these operators; you have seen the "postfix" form of
the operator that is placed after the operand. There is also a prefix form, ++n. Both
change the value of the variable by 1. The difference between the two only appears
when they are used inside expressions. The prefix form does the addition first; the
postfix form evaluates to the old value of the variable.

int m= 7;
int n= 7;
int a= 2 * ++m; // now a is 16, m is 8
int b= 2 * n++; // now b is 14, n is 8
 Relational and boolean Operators: Java has the full complement of relational operators. To
test for equality you use a double equal sign, ==. For example, the value of
3 == 7 is false.

Use != for inequality. For example, the value of 3 != 7 is true.

 Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >=
(greater than or equal) operators.
 Java, following C++, uses && for the logical "and" operator and || for the logical "or"
operator. If you combine two expressions with the && operator,

expression1 && expression2

and the truth value of the first expression has been determined to be false, then it is impossible for the
result to be true. Similarly, the value of expression1 || expression2 is automatically true if the first
expression is true, without evaluation of the second expression.

 Conversions between numeric types: It is often necessary to convert from one numeric type to
another. Next figure shows the legal conversions.

14
Legal conversions between numeric types

 The six solid arrows in the figure denote conversions without information loss. The
three dotted arrows denote conversions that may lose precision. For example, a large
integer such as 123456789 has more digits than the float type can represent. When the
integer is converted to a float, the resulting value has the correct magnitude but it
loses some precision.

int n = 123456789;
float f = n; // f is 1.23456792E8

 When two values with a binary operator (such as n + f where n is an integer and f is a
floating-point value) are combined, both operands are converted to a common type
before the operation is carried out.

 If either of the operands is of type double, the other one will be converted to a
double.
 Otherwise, if either of the operands is of type float, the other one will be converted
to a float.
 Otherwise, if either of the operands is of type long, the other one will be converted
to a long.
 Otherwise, both operands will be converted to an int.

 Casts: In the preceding section, you saw that int values are automatically converted to double
values when necessary. On the other hand, there are obviously times when you want to
consider a double as an integer. Numeric conversions are possible in Java, but of course
information may be lost. Conversions in which loss of information is possible are done by
means of casts. The syntax for casting is to give the target type in parentheses, followed by
the variable name. For example:
double x = 9.997;
int nx = (int) x;

Then, the variable nx has the value 9 because casting a floating-point value to an integer discards the
fractional part.

15
 Enumerated Types: An enum is a type that has a fixed list of possible values, which is
specified when the enum is created. In some ways, an enum is similar to the boolean
data type, which has true and false as its only possible values. However, boolean is a
primitive type, while an enum is not. The definition of an enum type has the
(simplified) form:

enum <enum-type-name> { <list-of-enum-values> }

 You can define your own enumerated type whenever such a situation arises. An
enumerated type has a finite number of named values. For example,
enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY }
enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV,
DEC }

 By convention, enum values are given names that are made up of upper case letters, but that
is a style guideline and not a syntax rule. An enum value is a constant; that is, it represents a
fixed value that cannot be changed. The possible values of an enum type are usually referred
to as enum constants.

 Note that the enum constants of type Season are considered to be ―contained in‖ Season,
which means—following the convention that compound identifiers are used for things that
are contained in other things—the names that you actually use in your program to refer to
them are Season.SPRING, Season.SUMMER, Season.FALL, and Season.WINTER.

 Once an enum type has been created, it can be used to declare variables in exactly the same
ways that other types are used. For example, you can declare a variable named vacation of
type Season with the statement:

Season vacation;

 After declaring the variable, you can assign a value to it using an assignment statement. The
value on the right-hand side of the assignment can be one of the enum constants of type
Season. Remember to use the full name of the constant, including ―Season‖! For example:

vacation = Season.SUMMER;
 You can print out an enum value with an output statement such as
System.out.print(vacation). The output value will be the name of the enum constant (without
the ―Season.‖). In this case, the output would be ―SUMMER‖.

Strings

 Conceptually, Java strings are sequences of characters. The standard Java library contains a
predefined class called, naturally enough, String. Each quoted string is an instance of the
String class:

String e = ""; // an empty string

16
String greeting = "Hello";

 The length method yields the number of characters. For example:

String greeting = "Hello";


int n = greeting.length(); // is 5.

 The call s.charAt(n) returns the character at position n, where n is between 0 and
s.length() – 1. For example,

char first = greeting.charAt(0); // first is 'H'


char last = greeting.charAt(4); // last is 'o'

 You extract a substring from a larger string with the substring method of the
String class. For example,

String greeting = "Hello";


String s = greeting.substring(0, 3);//creates a string consisting of
the characters "Hel".

 Java, like most programming languages, allows you to use the + sign to join
(concatenate) two strings.

String expletive = "Expletive";


String PG13 = "deleted";
String message = expletive + PG13;

The above code sets the variable message to the string "Expletivedeleted". (Note the lack of a
space between the words: the + sign joins two strings in the order received, exactly as they are
given.)

 When you concatenate a string with a value that is not a string, the latter is
converted to a string. For example:

int age = 13;


String rating = "PG" + age; //sets rating to the string "PG13".

This feature is commonly used in output statements. For example,

System.out.println("The answer is " + answer);

is perfectly acceptable and will print what one would want (and with the correct spacing because
of the space after the word is).

 Testing Strings for Equality: To test whether two strings are equal, use the equals method.
The expression s.equals(t)

returns true if the strings s and t are equal, false otherwise. Note that s and t can be string variables
or string constants. For example, the expression

17
"Hello".equals(greeting)

is perfectly legal. To test whether two strings are identical except for the upper/lowercase letter
distinction, use the equalsIgnoreCase method.

"Hello".equalsIgnoreCase("hello")

 Do not use the == operator to test whether two strings are equal! It only determines
whether or not the strings are stored in the same location. Sure, if strings are in the
same location, they must be equal. But it is entirely possible to store multiple copies
of identical strings in different places.

String greeting = "Hello"; //initialize greeting to a string


if (greeting == "Hello") . . .
// probably true
if (greeting.substring(0, 3) == "Hel") . . .
// probably false

Input and Output


 Reading Input: You saw that it is easy to print output to the "standard output stream" (that
is, the console window) just by calling System.out.println.
 To read console input, you first construct a Scanner that is attached to the "standard
input stream" System.in.
Scanner in = new Scanner(System.in);
 Now you use the various methods of the Scanner class to read input. For example, the
nextLine method reads a line of input.
System.out.print("What is your name? ");
String name = in.nextLine();

Here, we use the nextLine method because the input might contain spaces. To read a single word
(delimited by whitespace), call

String firstName = in.next();// To read an integer, use the nextInt method.


System.out.print("How old are you? ");
int age = in.nextInt();

Similarly, the nextDouble method reads the next floating-point number.

The program in below asks for the user's name and age and then prints a message like

Hello, _____. Next year, you'll be ____

Finally, add the line

import java.util.*;

at the beginning of the program. The Scanner class is defined in the java.util package. Whenever you
use a class that is not defined in the basic java.lang package, you need to use an import directive..

18
InputTest.java
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? ");
String name = in.nextLine();
// get second input
System.out.print("How old are you? ");
int age = in.nextInt();
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be " + (age
+ 1));
}}
 Formatting Output: You might have noticed that System.out.print outputs real numbers
with as many digits after the decimal point as necessary, so that for example π is output as
3.141592653589793, and numbers that are supposed to represent money might be output as
1050.0 or 43.575. You might prefer to have these numbers output as, for example, 3.14159,
1050.00, and 43.58. Java has a ―formatted output‖ capability that makes it easy to control
how real numbers and other values are printed. A lot of formatting options are available.
 The function System.out.printf can be used to produce formatted output
System.out.printf takes one or more parameters. The first parameter is a String that
specifies the format of the output. This parameter is called the format string. The
remaining parameters specify the values that are to be output. Here is a statement
that will print a number in the proper format for a dollar amount, where amount is a
variable of type double:
System.out.printf( "%1.2f", amount );
 The output format for a value is give by a format specifier in the format string. In this
example, the format specifier is %1.2f. The format string (in the simple cases that I cover
here) contains one format specifier for each of the values that is to be output. Some typical
format specifiers are %d, %12d, %10s, %1.2f and %15.8e. Every format specifier begins with
a percent sign (%) and ends with a letter, possibly with some extra formatting information in
between. The letter specifies the type of output that is to be produced. For example, in %d
and %12d, the ―d‖ specifies that an integer is to be written. The ―12‖ in %12d specifies the
minimum number of spaces that should be used for the output. If the integer that is being
output takes up fewer than 12 spaces, extra blank spaces are added in front of the integer to
bring the total up to 12. We say that the output is ―right-justified in a field of length 12.‖ A
very large value is not forced into 12 spaces; if the value has more than 12 digits, all the digits
will be printed, with no extra spaces. The specifier %d means the same as %1d—that is, an
integer will be printed using just as many spaces as necessary. (The ―d,‖ by the way, stands
for ―decimal‖—that is, base-10—numbers. You can replace the ―d‖ with an ―x‖ to output an
integer value in hexadecimal form.) The letter ―s‖ at the end of a format specifier can be used
with any type of value. It means that the value should be output in its default format, just as
it would be in unformatted output. A number, such as the ―20‖ in %20s, can be added to
specify the (minimum) number of characters. The ―s‖ stands for ―string,‖ and it can be used
for values of type String. It can also be used for values of other types; in that case the value is
converted into a String value in the usual way. The format specifiers for values of type double
are more complicated. An ―f‖, as in %1.2f, is used to output a number in ―floating-point‖

19
form, that is with digits after a decimal point. In %1.2f, the ―2‖ specifies the number of digits
to use after the decimal point. The ―1‖ specifies the (minimum) number of characters to
output; a ―1‖ in this position effectively means that just as many characters as are necessary
should be used. Similarly, %12.3f would specify a floating-point format with 3 digits after the
decimal point, right-justified in a field of length 12. Very large and very small numbers should
be written in exponential format, such as 6.00221415e23, representing ―6.00221415 times 10
raised to the power 23.‖ A format specifier such as %15.8e specifies an output in exponential
form, with the ―8‖ telling how many digits to use after the decimal point
System.out.printf("The product of %d and %d is %d", x, y, x*y);
 When this statement is executed, the value of x is substituted for the first %d in the string,
the value of y for the second %d, and the value of the expression x*y for the third, so the
output would be something like ―The product of 17 and 42 is 714‖ (quotation marks not
included in output!).

Control Flow
 Blocks: The block is the simplest type of structured statement. Its purpose is simply to group
a sequence of statements into a single statement. The format of a block is:

statements

 A variable declared inside a block is completely inaccessible and invisible from outside that
block. When the computer executes the variable declaration statement, it allocates memory
to hold the value of the variable. When the block ends, that memory is discarded (that is,
made available for reuse). The variable is said to be local to the block. There is a general
concept called the ―scope‖ of an identifier. The scope of an identifier is the part of the
program in which that identifier is valid. The scope of a variable defined inside a block is
limited to that block, and more specifically to the part of the block that comes after the
declaration of the variable.

While loop
 A while loop is used to execute statements over and over, but only so long as a specified
condition remains true. A while loop has the form:
while (boolean-expression)

Statement/s

 When the computer comes to a while statement, it evaluates the boolean-expression, which
yields either true or false as its value. If the value is false, the computer skips over the rest of
the while loop and proceeds to the next command in the program. If the value of the
expression is true, the computer executes the statement or block of statements inside the loop.
Then it returns to the beginning of the while loop and repeats the process. That is, it re-
evaluates the boolean-expression, ends the loop if the value is false, and continues it if the

20
value is true. This will continue over and over until the value of the expression is false when
the computer evaluates it; if that never happens, then there will be an infinite loop.
 Here is an example of a while loop that simply prints out the numbers 1, 2, 3, 4, 5:
int number; // The number to be printed.

number = 1; // Start with 1.

while ( number < 6 ) { // Keep going as long as number is < 6.

System.out.println(number);

number = number + 1; // Go on to the next number.

}System.out.println("Done!");

 The variable number is initialized with the value 1. So when the computer evaluates the
expression ―number < 6‖ for the first time, it is asking whether 1 is less than 6, which is true.
The computer therefore proceeds to execute the two statements inside the loop. The first
statement prints out ―1‖. The second statement adds 1 to number and stores the result back
into the variable number; the value of number has been changed to 2. The computer has
reached the end of the loop, so it returns to the beginning and asks again whether number is
less than 6. Once again this is true, so the computer executes the loop again, this time printing
out 2 as the value of number and then changing the value of number to 3. It continues in this
way until eventually number becomes equal to 6. At that point, the expression ―number < 6‖
evaluates to false. So, the computer jumps past the end of the loop to the next statement and
prints out the message ―Done!‖. Note that when the loop ends, the value of number is 6, but
the last value that was printed was 5.

If Statement
 An if statement tells the computer to take one of two alternative courses of action, depending
on whether the value of a given boolean-valued expression is true or false. It is an example of
a ―branching‖ or ―decision‖ statement. An if statement has the form:

21
if ( boolean-expression)

statement1

else

statement2

 When the computer executes an if statement, it evaluates the boolean expression. If the value
is true, the computer executes the first statement and skips the statement that follows the
―else‖. If the value of the expression is false, then the computer skips the first statement and
executes the second one. Note that in any case, one and only one of the two statements inside
the if statement is executed. The two statements represent alternative courses of action; the
computer decides between these courses of action based on the value of the boolean
expression.
 In many cases, you want the computer to choose between doing something and not doing it.
You can do this with an if statement that omits the else part:
if ( boolean-expression )

statement

 To execute this statement, the computer evaluates the expression. If the value is true, the
computer executes the statement that is contained inside the if statement; if the value is false,
the computer skips over that statement. In either case, the computer then continues with
whatever follows the if statement in the program.

 In these diagrams, the arrows represent the flow of time as the statement is executed. Control
enters the diagram at the top and leaves at the bottom. Similarly, a flow control diagram for
an if..else statement makes it clear that exactly one of the two nested statements is executed:

22
 Of course, either or both of the statements in an if statement can be a block, and again many
programmers prefer to add the braces even when they contain just a single statement.
 As an example, here is an if statement that exchanges the value of two variables, x and y, but
only if x is greater than y to begin with. After this if statement has been executed, we can be
sure that the value of x is definitely less than or equal to the value of y:
if ( x > y ) { int temp; // A temporary variable for use in this block.

temp = x; // Save a copy of the value of x in temp.

x = y; // Copy the value of y into x.

y = temp; // Copy the value of temp into y.

The do..while Statement


 Sometimes it is more convenient to test the continuation condition at the end of a loop,
instead of at the beginning, as is done in the while loop. The do..while statement is very
similar to the while statement, except that the word ―while,‖ along with the condition that it
tests, has been moved to the end. The word ―do‖ is added to mark the beginning of the loop.
A do..while statement has the form
do {

statements

} while ( boolean-expression );

 Note the semicolon, ’;’, at the very end. This semicolon is part of the statement, just as the
semicolon at the end of an assignment statement or declaration is part of the statement.
 To execute a do loop, the computer first executes the body of the loop—that is, the statement
or statements inside the loop—and then it evaluates the boolean expression. If the value of
the expression is true, the computer returns to the beginning of the do loop and repeats the
process; if the value is false, it ends the loop and continues with the next part of the program.
Since the condition is not tested until the end of the loop, the body of a do loop is always
executed at least once.

break and continue


 The syntax of the while and do..while loops allows you to test the continuation condition at
either the beginning of a loop or at the end. Sometimes, it is more natural to have the test in
the middle of the loop, or to have several tests at different places in the same loop. Java
provides a general method for breaking out of the middle of any loop. It’s called the break
statement, which takes the form
break;

 When the computer executes a break statement in a loop, it will immediately jump out of the
loop. It then continues on to whatever follows the loop in the program.
 The continue statement is related to break, but less commonly used. A continue statement
tells the computer to skip the rest of the current iteration of the loop. However, instead of
jumping out of the loop altogether, it jumps back to the beginning of the loop and continues
with the next iteration (including evaluating the loop’s continuation condition to see whether

23
any further iterations are required). As with break, when a continue is in a nested loop, it will
continue the loop that directly contains it; a ―labeled continue‖ can be used to continue the
containing loop instead.

The for Statement


 The formal syntax of the for statement is as follows:
for ( initialization; continuation-condition; update ) {

statements

 The continuation-condition must be a boolean-valued expression. The initialization is usually


a declaration or an assignment statement, but it can be any expression that would be allowed
as a statement in a program. The update can be any simple statement, but is usually an
increment, a decrement, or an assignment statement. Any of the three parts can be empty. If
the continuation condition is empty, it is treated as if it were ―true,‖ so the loop will be
repeated forever or until it ends for some other reason, such as a break statement. (Some
people like to begin an infinite loop with ―for (;;)‖ instead of ―while (true)‖.) Here’s a flow
control diagram for a for statement:

 Usually, the initialization part of a for statement assigns a value to some variable, and the
update changes the value of that variable with an assignment statement or with an increment
or decrement operation. The value of the variable is tested in the continuation condition, and
the loop ends when this condition evaluates to false. A variable used in this way is called a
loop control variable.

24
Nested for Loops
 Any combination of one control structure inside another is possible. We say that one
structure is nested inside another. You can even have multiple levels of nesting, such as a
while loop inside an if statement inside another while loop. The syntax of Java does not set a
limit on the number of levels of nesting.
 Nested for loops arise naturally in many algorithms.Consider the following codes:

for ( rowNumber = 1; rowNumber <= 12; rowNumber++ )

for ( N = 1; N <= 12; N++ ) {

System.out.printf( "%4d", N * rowNumber );

System.out.println();

The output when the above code is executed is

Multi-way Branching
 You can go on stringing together ―else-if’s‖ to make multi-way branches with any number of
cases:

if (test-1) statement-1

else if (test-2) statement-2

else if (test-3) statement-3. . // (more cases) .

else if (test-N) statement-N

else statement-(N+1)

25
 The computer evaluates the tests, which are boolean expressions, one after the other until it
comes to one that is true. It executes the associated statement and skips the rest. If none of
the boolean expressions evaluate to true, then the statement in the else part is executed.

The switch Statement


 A switch statement allows you to test the value of an expression and, depending on that
value, to jump directly to some location within the switch statement. Only expressions of
certain types can be used. The value of the expression can be one of the primitive integer
types int, short, or byte. It can be the primitive char type. It can be String. Or it can be an
enum type.
 The positions within a switch statement to which it can jump are marked with case labels
that take the form: ―case constant:‖. The constant here is a literal of the same type as the
expression in the switch. A case label marks the position the computer jumps to when the
expression evaluates to the given constant value. You can also use the label ―default:‖ in a
switch statement; this provides a default jump point that is used when the value of the
expression is not listed in any case label. A switch statement, as it is most often used, has the
form:

switch (expression) {

case constant-1: statement-1i

break;

case constant-2: statements-2i

break; . . // (more cases)

. case constant-N: statements-N

break; default:

// optional

default case statements-(N+1)

} // end of switch statement

 This has exactly the same effect as the following multi-way if statement, but the switch
statement can be more efficient because the computer can evaluate one expression and jump
directly to the correct case, whereas in the if statement, the computer must evaluate up to N
expressions before it knows which set of statements to execute:

if (expression == constant-1) { // but use .equals for String!!

statements-1

} else if (expression== constant-2) {

26
statements-2 }

. . . else if (expression== hconstant-N)

statements-N

} else {

statements-(N+1) }

 The break statements in the switch are not actually required by the syntax of the switch
statement. The effect of a break is to make the computer jump past the end of the switch
statement, skipping over all the remaining cases.
 Here is an example of a switch statement. This is not a useful example, but it should be easy
for you to follow. Note, by the way, that the constants in the case labels don’t have to be in
any particular order, but they must all be different:

switch ( N ) { // (Assume N is an integer variable.)

case 1: System.out.println("The number is 1.");

break;

case 2: case 4: case 8: System.out.println("The number is 2, 4, or


8."); System.out.println("(That’s a power of 2!)");

break;

case 3: case 6: case 9: System.out.println("The number is 3, 6, or


9.");

System.out.println("(That’s a multiple of 3!)");

break;

case 5: System.out.println("The number is 5.");

break;

default: System.out.println("The number is 7 or is outside the range 1


to 9.");

27
Array
 A data structure consists of a number of data items chunked together so that they can be
treated as a unit.
 An array is a data structure in which the items are arranged as a numbered sequence, so that
each individual item can be referred to by its position number.
 In Java—but not in some other programming languages—all the items must be of the same
type, and the numbering always starts at zero. The number of items in an array is called the
length of the array. The type of the individual items in an array is called the base type of the
array. And the position number of an item in an array is called the index of that item.
 Suppose that you want to write a program that will process the names of, say, one thousand
people. You will need a way to deal with all that data. Before you knew about arrays, you
might have thought that the program would need a thousand variables to hold the thousand
names, and if you wanted to print out all the names, you would need a thousand print
statements. Clearly, that would be ridiculous! In reality, you can put all the names into an
array. The array is represented by a single variable, but it holds the entire list of names. The
length of the array would be 1000, since there are 1000 individual names. The base type of the
array would be String since the items in the array are strings. The first name would be at
index 0 in the array, the second name at index 1, and so on, up to the thousandth name at
index 999.
 The base type of an array can be any Java type, but for now, we will stick to arrays whose
base type is String or one of the eight primitive types. If the base type of an array is int, it is
referred to as an ―array of ints.‖ An array with base type String is referred to as an ―array of
Strings.‖ However, an array is not, properly speaking, a list of integers or strings or other
values. It is better thought of as a list of variables of type int, or a list of variables of type
String, or of some other type. As always, there is some potential for confusion between the
two uses of a variable: as a name for a memory location and as a name for the value stored in
that memory location. Each position in an array acts as a variable. Each position can hold a
value of a specified type (the base type of the array), just as a variable can hold a value. The
value can be changed at any time, just as the value of a variable can be changed. The items in
an array—really, the individual variables that make up the array—are more often referred to
as the elements of the array.
 As mentioned above, when you use an array in a program, you can use a variable to refer to
the array as a whole. But you often need to refer to the individual elements of the array. The
name for an element of an array is based on the name for the array and the index number of
the element. The syntax for referring to an element looks, for example, like this: namelist[7].
Here, namelist is the variable that names the array as a whole, and namelist[7] refers to the
element at index 7 in that array. That is, to refer to an element of an array, you use the array
name, followed by element index enclosed in square brackets. An element name of this form
can be used like any other variable: You can assign a value to it, print it out, use it in an
expression, and so on.

28
 An array also contains a kind of variable representing its length. For example, you can refer
to the length of the array namelist as namelist.length. However, you cannot assign a value to
namelist.length, since the length of an array cannot be changed.
 Before you can use a variable to refer to an array, that variable must be declared, and it must
have a type. For an array of Strings, for example, the type for the array variable would be
String[], and for an array of ints, it would be int[]. In general, an array type consists of the
base type of the array followed by a pair of empty square brackets. Array types can be used
to declare variables; for example

String[] namelist;

int[] A;

double[] prices;

 And variables declared in this way can refer to arrays. However, declaring a variable does not
make the actual array. Like all variables, an array variable has to be assigned a value before
it can be used. In this case, the value is an array. Arrays have to be created using a special
syntax. (The syntax is related to the fact that arrays in Java are actually objects, but that
doesn’t need to concern us here.) Arrays are created with an operator named new. Here are
some examples:

namelist = new String[1000];

A = new int[5];

prices = new double[100];

 The general syntax is

array-variable = new base-type [array-length];

 The length of the array can be given as either an integer or an integer-valued expression. For
example, after the assignment statement ―A = new int[5];‖, A is an array containing the five
integer elements A[0], A[1], A[2], A[3], and A[4]. Also, A.length would have the value 5. It’s
useful to have a picture in mind:

 When you create an array of int, each element of the array is automatically initialized to zero.
Any array of numbers is filled with zeros when it is created. An array of boolean is filled with

29
the value false. And an array of char is filled with the character that has Unicode code
number zero. (For an array of String, the initial value is null, a special value used for objects.

Arrays and For Loops


 A lot of the real power of arrays comes from the fact that the index of an element can be given
by an integer variable or even an integer-valued expression. For example, if list is an array
and i is a variable of type int, then you can use list[i] and even list[2*i+1] as variable names.
The meaning of list[i] depends on the value of i. This becomes especially useful when we want
to process all the elements of an array, since that can be done with a for loop. For example, to
print out all the items in an array, list, we can just write

int i; // the array index

for (i = 0; i < list.length; i++) {

System.out.println( list[i] );

 The first time through the loop, i is 0, and list[i] refers to list[0]. So, it is the value stored in
the variable list[0] that is printed. The second time through the loop, i is 1, and the value
stored in list[1] is printed. If the length of the list is 5, then the loop ends after printing the
value of list[4], when i becomes equal to 5 and the continuation condition ―i < list.length‖ is
no longer true. This is a typical example of using a loop to process an array.
 Let’s look at a few more examples. Suppose that A is an array of double, and we want to find
the average of all the elements of the array. We can use a for loop to add up the numbers, and
then divide by the length of the array to get the average:

double total; // The sum of the numbers in the array.

double average; // The average of the numbers.

int i; // The array index.

total = 0;

for ( i = 0; i < A.length; i++ ) {

total = total + A[i]; // Add element number i to the total.

average = total / A.length; // A.length is the number of items

 Another typical problem is to find the largest number in the array A. The strategy is to go
through the array, keeping track of the largest number found so far. We’ll store the largest
number found so far in a variable called max. As we look through the array, whenever we find
a number larger than the current value of max, we change the value of max to that larger
value. After the whole array has been processed, max is the largest item in the array overall.

30
The only question is, what should the original value of max be? One possibility is to start
with max equal to A[0], and then to look through the rest of the array, starting from A[1], for
larger items:

double max; // The largest number seen so far.

max = A[0]; // At first, the largest number seen is A[0].

int i;

for ( i = 1; i < A.length; i++ ) {

if (A[i] > max) {

max = A[i];

} } // at this point, max is the largest item in A

 Sometimes, you only want to process some elements of the array. In that case, you can use an
if statement inside the for loop to decide whether or not to process a given element. Let’s look
at the problem of averaging the elements of an array, but this time, suppose that we only
want to average the non-zero elements. In this case, the number of items that we add up can
be less than the length of the array, so we will need to keep a count of the number of items
added to the sum:

double total; // The sum of the non-zero numbers in the array.

int count; // The number of non-zero numbers.

double average; // The average of the non-zero numbers.

int i;

total = 0;

count = 0;

for ( i = 0; i < A.length; i++ ) {

if ( A[i] != 0 ) {

total = total + A[i]; // Add element to the total

count = count + 1; // and count it.

} if (count == 0) {

System.out.println("There were no non-zero elements.");

31
else {

average = total / count; // Divide by number of items

System.out.printf("Average of %d elements is %1.5g%n", count, average);

 So far, my examples of array processing have used sequential access. That is, the elements of
the array were processed one after the other in the sequence in which they occur in the array.
But one of the big advantages of arrays is that they allow random access. That is, every
element of the array is equally accessible at any given time.

Two-dimensional Arrays
 The arrays that we have considered so far are ―one-dimensional.‖ This means that the array
consists of a sequence of elements that can be thought of as being laid out along a line. It is
also possible to have two-dimensional arrays, where the elements can be laid out in a
rectangular grid.
 In a two-dimensional, or ―2D,‖ array, the elements can be arranged in rows and columns.
Here, for example, is a 2D array of int that has five rows and seven columns:

 This 5-by-7 grid contains a total of 35 elements. The rows in a 2D array are numbered 0, 1, 2,
..., up to the number of rows minus one. Similarly, the columns are numbered from zero up to
the number of columns minus one. Each individual element in the array can be picked out by
specifying its row number and its column number. (The illustration shown here is not what
the array actually looks like in the computer’s memory, but it does show the logical structure
of the array.)
 In Java, the syntax for two-dimensional arrays is similar to the syntax for one-dimensional
arrays, except that an extra index is involved, since picking out an element requires both a
row number and a column number. For example, if A is a 2D array of int, then A[3][2] would
be the element in row 3, column 2. That would pick out the number 17 in the array shown
above. The type for A would be given as int[][], with two pairs of empty brackets. To declare
the array variable and create the array, you could say,
int[][] A;

A = new int[5][7];

32
The second line creates a 2D array with 5 rows and 7 columns. Two-dimensional arrays are often
processed using nested for loops. For example, the following code segment will print out the elements
of A in neat columns:

The base type of a 2D array can be anything, so you can have arrays of type double[][], String[][],
and so on.

33

You might also like