Java Com 123 First Part
Java Com 123 First Part
1
f. Robustness: Java is a strongly typed programming language and encourages the development
of error free applications.
Types of Java Programs
Java programs may be developed in three ways. They will be mentioned briefly here:
a. Java Applications: These are stand-alone applications such word processors, inventory
control systems etc.
b. Java Applets: These programs that are executed within a browser. They are executed on
the client computer.
c. Java Serverlets: These are server side programs that are executed within a browser. In this
course we will limit ourselves to only the first two mentioned types of Java programs –
applications and applets.
Introduction to Java Applications
As earlier described Java applications are stand alone programs that can be executed to solve
specific problems. Before delving into the details of writing Java applications (and applets) we
will consider the concept on which the language is based upon being: Object Oriented
Programming (OOP).
a. Encapsulation: Encapsulation is a methodology that binds together data and the codes that it
manipulates thus keeping it safe from external interference and misuse. An object oriented
program contains codes that may have private members that are directly accessible to only the
members of that program. Also it may have program codes (methods) that will enable other
programs to access these data is a uniform and controlled fashion.
b. Polymorphism: Polymorphism is a concept whereby a particular “thing” may be employed in
many forms and the exact implementation is determined by the specific nature of the situation
(or problem). As an example, consider how a frog, lizard and a fish move (“the interface”) from
one place to another. A frog may leap ten centimeters, a lizard in a single movement moves two
centimeters and a shark may swim three meters in a single movement. All these animals exhibit a
common ability – movement – expressed differently.
c. Inheritance: Inheritance is the process of building new classes based on existing classes. The
new class inherits the properties and attributes of the existing class. Object oriented programs
models real world concepts of inheritance. For example children inherit attributes and behaviors
from their parents. The attributes such as color of eyes,complexion, facial features etc represent
the fields in an java. Behaviors such as being a good dancer, having a good sense of humor etc
represent the methods. The child may have other attributes and behaviors that differentiate them
from the parents.
Components of a Java Application Program
Every Java application program comprises of a class declaration header, fields (instance
variables – which is optional), the main method and several other methods as required for
solving the problem. The methods and fields are members of the class. In order to explore these
components let us write our first Java program.
2
/*
* [Link]
* Displays Hello world!!! to the output window
*
*/
public class HelloWorld // class definition header
{
public static void main( String[] args )
{
[Link]( “Hello World!!! “ ); // print text
} // end method main
} // end class HelloWorld
Listing 1.0 [Link]
The above program is a simple yet complete program containing the basic features of all Java
application programs. We will consider each of these features and explain them accordingly.
The first few lines of the program are comments.
/*
* [Link]
* Displays Hello world!!! to the output window
*
*/
The comments are enclosed between the /* */ symbols.
Comments are used for documenting a program, that is, for passing across vital information
concerning the program – such as the logic being applied, name of the program and any other
relevant information etc. Comments are not executed by the computer.
Comments may also be created by using the // symbols either at the beginning of a line:
// This is a comment
Or on the same line after with an executable statement. To do this the comment must be written
after the executable statement and not before else the program statement will be ignored by the
computer:
[Link]( “Hello World!!! “ ); // in-line comment.
3
The keyword class tells Java that we want to define a class using the name HelloWorld.
Note: The file containing this class must be saved using the name [Link]. The name of
the file and the class name must be the same both in capitalization and sequence. Java is very
case sensitive thus HelloWorld is different from helloworld and also different from
HELLOWORLD.
The next part of the program is the declaration of the main method. Methods are used for
carrying out the desired tasks in a Java program, they are akin to functions used in C/C++
programming languages. The listing:
public static void main( String[] args )
{
}
is the main method definition header. It starts with the access modifier public, followed by the
keyword static which implies that the method main( ) may be called before an object of the class
has been created. The keyword void implies that the method will not return any value on
completion of its task. These keywords public, static, and void should always be placed in the
sequenced shown.
Any information that you need to pass to a method is received by variables specified within the
set of parentheses that follow the name of the method. These variables are called parameters. If
no parameters are required for a given method, you still need to include the empty parentheses.
In main( ) there is only one parameter, String[] args, which declares a parameter named args.
This is an array of objects of type String. (Arrays are collections of similar objects.) Objects of
type String store sequences of characters. In this case, args receives any command-line
arguments present when the program is executed. Note that the parameters could have been
written as String args[]. This is perfectly correct.
The instructions (statements) enclosed within the curly braces will be executed once the main
method is run. The above program contains the instruction that tells Java to display the output
“Hello World!!!” followed by a carriage return. This instruction is:
[Link]( “Hello World!!!” ); //print text
This line outputs the string "Java drives the Web." followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it. As you will see, println( ) can be used to display
other types of information, too. The line begins with [Link]. While too complicated to
explain in detail at this time, briefly, System is a predefined class that provides access to the
system, and out is the output stream that is connected to the console. Thus, [Link] is an
object that encapsulates console output. The fact that Java uses an object to define console
output is further evidence of its object-oriented nature. As you have probably guessed, console
output (and input) is not used frequently in real-world Java programs and applets. Since most
modern computing environments are
windowed and graphical in nature, console I/O is used mostly for simple utility programs and for
demonstration programs. Later you will learn other ways to generate output using Java, but for
4
now, we will continue to use the console I/O methods. Notice that the println( ) statement ends
with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in
the program do not end in a semicolon is that they are not, technically, statements.
The first closing brace -}- in the program ends main( ), and the last } ends the HelloWorld
class definition; it is a good practice to place a comment after the closing curly brace. The
opening and close brace are referred to as a block of code.
One last point: Java is case sensitive. Forgetting this can cause you serious problems. For
example, if you accidentally type Main instead of main, or PrintLn instead of println, the
preceding program will be incorrect. Furthermore, although the Java compiler will compile
classes that do not contain a main( ) method, it has no way to execute them. So, if you had
Mistyped main, the compiler would still compile your program. However, the Java interpreter
would report an error because it would be unable to find the main( ) method.
In the above program some lines where left blank, this was done in order to make the program
readable. Furthermore, tabs (indentation) were used to within the body of a class or methods as
appropriate to spate characters and symbols. The blank spaces, tabs, and newline characters are
referred to as white spaces.
5
high-level languages are translated using language translators.
A language translator is that translates a high-level language program or an assembly
language program into a machine language program.
There are three types of translators:
o 1. Assemblers.
o 2. Compilers.
o 3. Interpreters.
Assemblers
o An assembler is a program that translates an assembly language program, written
in a particular assembly language, into a particular machine language.
Compilers
o A compiler is a program that translates a high-level language program, written in
a particular high-level language, into a particular machine language.
Interpreters
o An interpreter is a program that translates a high-level language program, one
instruction at a time, into machine language.
o As each instruction is translated it is immediately executed.
o Interpreted programs are generally slower than compiled programs because
compiled programs can be optimized to get faster execution.
Note that:
o Some high-level languages are compiled while others are interpreted.
o There are also languages, like Java, which are first complied and then interpreted
In the traditional compilation process, the compiler produces machine code for a specific
family of processors
For example, given a source program, a compiler for the x86 family of processors will
produce binary files for this family of processors.
A disadvantage of this compilation method is that the code produced in each case is not
portable.
To make the resulting code portable, we need the concept of a virtual machine as we
discuss in the following page.
JAVA VITUAL MACHINE
Instead of producing a processor-specific code, Java compilers produce an intermediate
code called bytecode.
The bytecode is also a binary code but is not specific to a particular CPU.
6
A Java compiler will produce exactly the same bytecode no matter what computer system
is used.
The Java bytecode is then interpreted by the Java Virtual Machine (JVM) interpreter.
Notice that each type of computer system has its own Java interpreter that can run on that
system.
This is how Java achieves compatibility.
o It does not matter on what computer system a Java program is compiled,
provided the target computer has a Java Virtual machine.
STRUCTURE OF A SIMPLE JAVA PROGRAM
A Java program consists of essential elements called classes. The classes in a program are
used to create specific things called objects.
This is an example of a Java source program
public class Hello {
public static void main(String[] args ){
[Link](“Hello.”);
}
}
Program execution: the main method is called by the runtime system
You must type this program and save it in a file named [Link]
[Link] names may start with and alphabet (a-z / A-Z) and the remaining characters may be,
underscore (_) or a dollar sign, or a number for example sum, counter, firstName,
amount_Paid are all valid variable names. 9x, 0value are invalid.
2. Embedded blank spaces may not be included in variable names though an underscore may be
used to join variable names that comprises of compound words. Example x 10 is not valid, it
could be written as x_10 or x10.
3. Reserved words (words defined for specific use in Java) may not be employed as variables
names. Example loop, do, for, while, switch are reserved.
4. Special symbols such as arithmetic operators, comma (,), ?, /, ! are not allowed.
5. Variable name may be of any [Link] is a good programming practice to use names that
indicate the meaning of the value it represents. For amountPaid, or amt_paid can be easily
remembered that it represent an amount paid value. Though if the programmer had used x or y as
the variable name it would still have been valid.
[Link] is a case sensitive programming language thus the programmer must be very careful an
consistent when giving and using variable names. Java distinguishes between upper case(capital)
letters and lower case letters (small letters) hence ‘a’ is different from ‘A’ as far as Java is
concerned.
7
Variable Declaration
Variable may represent values that are expected to change or not during the execution of a
computer program. When declaring variable names the scope (visibility) of variables from other
part of the program may be specified, the type of data that should be stored in the area of
memory. Variable names may also represent either primitive data or reference data. The general
form for creating or declaring variable is presented below.
accessModifier dataType variableList
Where:
accessModifier determines the visibility of the variable to other part of the program e.g. public
or private.
dataType represents either primitive (int, char, float) or reference type data (array, String).
variableList is one or more valid variables separated using commas.
Examples:
a. private int x, y, z;
In this example the access modifier is private, the data type is int and the variables that are
permitted to hold integer values are the identifiers x, y and z. similar pattern is applied in other
examples below.
b. private float balance, initTemperature;
c. private boolean alreadyPaid;
d. public long population;
Alternatively the initial values to be stored in the memory may be specified when declaring the
variables. The general form for declaring and initializing the variables is presented below:
accessModifier dataType variable1= value1, variable2 = value2, … , variable = valuen;
We will illustrate with examples.
private int x = 10;
private int a = 0, b= 0, c = 0;
public double amountLoaned = 100;
Note: we declaring variables in a method (e.g. main method) do not include the access modifiers
because all variables declared in methods are implicitly private hence localized to that method.
The examples given above can be used to create instance variables.
Now let us write a program to put together all that we have learnt. The program listing below
demonstrates how to create primitive variables (int) and non-primitive variable (of type
Scanner). It demonstrates how to write arithmetic expressions, input and output data from the
user.
8
Fundamental Data Types
Variable Declaration
9
A variable can be declared to hold a data value of any of the primitive types.
A variable is a named memory location in which a value is stored.
A variable name is a sequence of letters and digits starting with a letter.
int counter;
int numStudents = 583;
long longValue;
long numberOfAtoms = 1237890L;
float gpa;
float batchAverage = 0.406F;
double e;
double pi = 0.314;
char gender;
char grade = ‘B’;
boolean safe;
boolean isEmpty = true;
Numbers and Constants
By default, whole numbers are int and real numbers are double.
However, we can append a letter at the end of a number to indicate its type.
Upper and lower case letters can be used for ‘float’ (F or f), ‘double’ (D or d), and ‘long’ (l or
L):
Float and double numbers may be expressed in scientific notation: number * 10exponent as:
number E integerExponent or number e integerExponent
float maxGrade = 100f;
double temp = 583d;
float temp = 5.5; // Error as 5.5 is double
float temp = 5.5f;
long y = 583L;
double x = 2.25e-6;
Arithmetic Operators
10
Operator Description
+ Adds op1 and op2
Arithmetic Operators
The operators give results depending on the type of the operands.
11
If operand1 and operand2 are integer, then the result is also integer. But if either
operand1 and/or operand2 is double, then the result is double.
Examples:
1/2 0
86 / 10 8
86 / 10.0 8.6
86.0 / 10 8.6
86 % 10 6
Summary
12
Javadoc comments are delimited by /** and */. Javadoc comments enable programmers
to embed program documentation directly in their programs. The javadoc utility program
generates HTML documentation based on Javadoc comments.
A programming language's syntax specifies the rules for creating a proper program in that
language.
A syntax error (also called a compiler error, compile-time error or compilation error)
occurs when the compiler encounters code that violates Java's language rules.
Programmers use blank lines and space characters to make programs easier to read.
Together, blank lines, space characters and tab characters are known as white space.
Space characters and tabs are known specifically as white-space characters. White space
is ignored by the compiler.
Every program in Java consists of at least one class declaration that is defined by the
programmer (also known as a programmer-defined class or a user-defined class).
Keywords are reserved for use by Java and are always spelled with all lowercase letters.
Keyword class introduces a class declaration and is immediately followed by the class
name.
By convention, all class names in Java begin with a capital letter and capitalize the first
letter of each word they include (e.g., SampleClassName).
A Java class name is an identifier series of characters consisting of letters, digits,
underscores (_) and dollar signs ($) that does not begin with a digit and does not contain
spaces. Normally, an identifier that does not begin with a capital letter is not the name of
a Java class.
Java is case sensitivethat is, uppercase and lowercase letters are distinct.
The body of every class declaration is delimited by braces, { and }.
A public class declaration must be saved in a file with the same name as the class
followed by the ".java" file-name extension.
Method main is the starting point of every Java application and must begin with
public static void main( String args[] )
Methods are able to perform tasks and return information when they complete their tasks.
Keyword void indicates that a method will perform a task but will not return any
information.
Statements instruct the computer to perform actions.
A sequence of characters in double quotation marks is called a string, a character string, a
message or a string literal.
[Link], the standard output object, allows Java applications to display characters in
the command window.
Method [Link] displays its argument in the command window followed by a
new-line character to position the output cursor to the beginning of the next line.
Every statement ends with a semicolon.
Most operating systems use the command cd to change directories in the command
window.
13
You compile a program with the command javac. If the program contains no syntax
errors, a class file containing the Java bytecodes that represent the application is created.
These bytecodes are interpreted by the JVM when we execute the program.
[Link] displays its argument and positions the output cursor immediately after
the last character displayed.
A backslash (\) in a string is an escape character. It indicates that a "special character" is
to be output. Java combines the next character with the backslash to form an escape
sequence . The escape sequence \n represents the newline character, which positions the
cursor on the next line.
[Link] method (f means "formatted") displays formatted data.
When a method requires multiple arguments, the arguments are separated with commas
(,)this is known as a comma-separated list.
Method printf's first argument is a format string that may consist of fixed text and format
specifiers. Fixed text is output by printf just as it would be output by print or println.
Each format specifier is a placeholder for a value and specifies the type of data to output.
Format specifiers begin with a percent sign (%) and are followed by a character that
represents the (-) data type. The format specifier %s is a placeholder for a string.
At the first format specifier's position, printf substitutes the value of the first argument
after the format string. At each subsequent format specifier's position, printf substitutes
the value of the next argument in the argument list.
Integers are whole numbers, like 22, 7, 0 and 1024.
An import declaration helps the compiler locate a class that is used in a program.
Java provides a rich set of predefined classes that programmers can reuse rather than
"reinventing the wheel." These classes are grouped into packagesnamed collections of
classes.
Collectively, Java's packages are referred to as the Java class library, or the Java
Application Programming Interface (Java API).
A variable declaration statement specifies the name and type of a variable.
A variable is a location in the computer's memory where a value can be stored for use
later in a program. All variables must be declared with a name and a type before they can
be used.
A variable's name enables the program to access the value of the variable in memory. A
variable name can be any valid identifier.
Like other statements, variable declaration statements end with a semicolon (;).
A Scanner (package [Link]) enables a program to read data for use in a program. The
data can come from many sources, such as a file on disk or the user at the keyboard.
Before using a Scanner, the program must create it and specify the source of the data.
Variables should be initialized to prepare them for use in a program.
The expression new Scanner( [Link] ) creates a Scanner that reads from the keyboard.
The standard input object, [Link], enables Java applications to read data typed by the
user.
Data type int is used to declare variables that will hold integer values. The range of
values for an int is 2,147,483,648 to +2,147,483,647.
Types float and double specify real numbers, and type char specifies character data. Real
numbers are numbers that contain decimal points, such as 3.4, 0.0 and 11.19. Variables of
type char data represent individual characters, such as an uppercase letter (e.g., A), a digit
14
(e.g., 7), a special character (e.g., * or %) or an escape sequence (e.g., the newline
character, \n).
Types such as int, float, double and char are often called primitive types or built-in types.
Primitive-type names are keywords; thus, they must appear in all lowercase letters.
A prompt directs the user to take a specific action.
Scanner method nextInt obtains an integer for use in a program.
The assignment operator, =, enables the program to give a value to a variable. Operator =
is called a binary operator because it has two operands. A n assignment statement uses an
assignment operator to assign a value to a variable.
Portions of statements that have values are called expressions.
The format specifier %d is a placeholder for an int value.
Variable names correspond to locations in the computer's memory. Every variable has a
name, a type, a size and a value.
Whenever a value is placed in a memory location, the value replaces the previous value
in that location. The previous value is lost.
Most programs perform arithmetic calculations. The arithmetic operators are + (addition),
- (subtraction, * (multiplication), / (division) and % (remainder).
Integer division yields an integer quotient.
The remainder operator, %, yields the remainder after division.
Arithmetic expressions in Java must be written in straight-line form.
If an expression contains nested parentheses, the innermost set of parentheses is
evaluated first.
Java applies the operators in arithmetic expressions in a precise sequence determined by
the rules of operator precedence.
When we say that operators are applied from left to right, we are referring to their
associativity. Some operators associate from right to left.
Redundant parentheses in an expression can make an expression clearer.
A condition is an expression that can be either true or false. Java's if statement allows a
program to make a decision based on the value of a condition.
Conditions in if statements can be formed by using the equality (== and !=) and relational
(>, <, >= and <=) operators.
An if statement always begins with keyword if, followed by a condition in parentheses,
and expects one statement in its body.
The empty statement is a statement that does not perform a task.
15
abs(x) Returns the absolute value of x, x can be double, float, int or long.
cos(a), sin(a), tan(a) Returns the trigonometric cosine/sine/tangent of an angle given in radians
max(x, y) , min(x, y) Returns the greater/smaller of two values, x and y can be double, float, int o
pow(x, y) y
Returns x
Assignment Statement
Syntax:
variable = expression;
The expression in the right is evaluated and the result is assigned to the variable in the
left.
The left side must be a variable.
Examples:
16
a = 5;
b = a;
b = b + 12; // valid: assignment operator is not equals operator
c = a + b;
a + b = c; // invalid: left side not a variable
Assignment Statement (cont’d)
To exchange (or to swap) the contents of two variables, a third variable must be used.
Example:
Text-printing program.
Text-printing program.
begins with //, indicating that the remainder of the line is a comment. Programmers insert
comments to document programs and improve their readability. This helps other people to read
and understand programs. The Java compiler ignores comments, so they do not cause the
computer to perform any action when the program is run. We begin every program with a
comment indicating the figure number and file name.
17
A comment that begins with // is called an end-of-line (or single-line) comment, because the
comment terminates at the end of the line on which it appears. A // comment also can begin in
the middle of a line and continue until the end of that line
/* This is a traditional
comment. It can be
split over many lines */
can be spread over several lines . This type of comment begins with the delimiter /* and ends
with */. All text between the delimiters is ignored by the compiler. Java incorporated traditional
comments and end-of-line comments from the C and C++ programming languages, respectively.
In this book, we use end-of-line comments.
// Text-printing program.
Java also provides Javadoc comments that are delimited by /** and */. As with traditional
comments, all text between the Javadoc comment delimiters is ignored by the compiler. Javadoc
comments enable programmers to embed program documentation directly in their programs.
Such comments are the preferred Java commenting format in industry. The javadoc utility
program (part of the J2SE Development Kit) reads Javadoc comments and uses them to prepare
your program's documentation in HTML format. We demonstrate Javadoc comments and the
javadoc utility in Appendix H. For complete information, visit Sun's javadoc Tool Home Page
at [Link]/j2se/javadoc.
18
begins a class declaration for class Welcome1. Every program in Java consists of at least one
class declaration that is defined by youthe programmer. These are known as programmer-
defined classes or user-defined classes. The class keyword introduces a class declaration in
Java and is immediately followed by the class name (Welcome1). Keywords (sometimes called
reserved words) are reserved for use by Java (we discuss the various keywords throughout the
text) and are always spelled with all lowercase letters. The complete list of Java keywords is
shown in Appendix C.
By convention, all class names in Java begin with a capital letter and capitalize the first letter of
each word they include (e.g., SampleClassName). A Java class name is an identifiera series of
characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin
with a digit and does not contain spaces. Some valid identifiers are Welcome1, $value, _value,
m_inputField1 and button7. The name 7button is not a valid identifier because it begins with a
digit, and the name input field is not a valid identifier because it contains a space. Normally, an
identifier that does not begin with a capital letter is not the name of a Java class. Java is case
sensitivethat is, uppercase and lowercase letters are distinct, so a1 and A1 are different (but both
valid) identifiers.
By convention, always begin a class name's identifier with a capital letter and start each
subsequent word in the identifier with a capital letter. Java programmers know that such
identifiers normally represent Java classes, so naming your classes in this manner makes your
programs more readable
Java is case sensitive. Not using the proper uppercase and lowercase letters for an identifier
normally causes a compilation error
every class we define begins with the public keyword. For now, we will simply require this
keyword. When you save your public class declaration in a file, the file name must be the class
name followed by the ".java" file-name extension. For our application, the file name is
[Link].
It is an error for a public class to have a file name that is not identical to the class name (plus the
.java extension) in terms of both spelling and capitalization.
It is an error not to end a file name with the .java extension for a file containing a class
declaration. If that extension is missing, the Java compiler will not be able to compile the class
declaration.
A left brace {, begins the body of every class declaration. A corresponding right brace, }, must
end each class declaration. Note that This indentation is one of the spacing conventions
mentioned earlier. We define each spacing convention as a Good Programming Practice
Whenever you type an opening left brace, {, in your program, immediately type the closing right
brace, }, then reposition the cursor between the braces and indent to begin typing the body. This
practice helps prevent errors due to missing braces.
19
Indent the entire body of each class declaration one "level" of indentation between the left brace,
{, and the right brace, }, that delimit the body of the class. This format emphasizes the class
declaration's structure and makes it easier to read.
Set a convention for the indent size you prefer, and then uniformly apply that convention. The
Tab key may be used to create indents, but tab stops vary among text editors. We recommend
using three spaces to form a level of indent.
is the starting point of every Java application. The parentheses after the identifier main indicate
that it is a program building block called a method. Java class declarations normally contain one
or more methods. For a Java application, exactly one of the methods must be called main and
must be defined; otherwise, the JVM will not execute the application. Methods are able to
perform tasks and return information when they complete their tasks. Keyword void indicates
that this method will perform a task but will not return any information when it completes its
task. Later, we will see that many methods return information when they complete their task. The
left brace, {, on line 8 begins the body of the method declaration. A corresponding right
brace, }, must end the method declaration's body (line 11 of the program). Note that line 9 in the
body of the method is indented between the braces.
Indent the entire body of each method declaration one "level" of indentation between
the left brace, {, and the right brace, }, that define the body of the method. This format
makes the structure of the method stand out and makes the method declaration easier
to read.
instructs the computer to perform an actionnamely, to print the string of characters contained
between the double quotation marks. A string is sometimes called a character string, a message
or a string literal. We refer to characters between double quotation marks simply as strings.
White-space characters in strings are not ignored by the compiler.
20
OS X, the command window is called a terminal window or a shell. Many programmers refer to
the command window simply as the command line.
Method [Link] displays (or prints) a line of text in the command window. The
string in the parentheses is the argument to the method. Method [Link] performs its
task by displaying (also called outputting) its argument in the command window. When
[Link] completes its task, it positions the output cursor (the location where the next
character will be displayed) to the beginning of the next line in the command window. (This
move of the cursor is similar to when a user presses the Enter key while typing in a text editorthe
cursor appears at the beginning of the next line in the file.)
The entire [Link], the argument "Welcome to Java Programming!" in the parentheses
and the semicolon (;), is called a statement. Each statement ends with a semicolon. When the
statement of our program executes, it displays the message Welcome to Java Programming! in
the command window. As we will see in subsequent programs, a method is typically composed
of one or more statements that perform the method's task.
When the compiler reports a syntax error, the error may not be on the line number
indicated by the error message. First, check the line for which the error was reported. If
that line does not contain syntax errors, check several preceding lines.
Some programmers find it difficult when reading or writing a program to match the left and right
braces ({ and }) that delimit the body of a class declaration or a method declaration. For this
reason, some programmers include an end-of-line comment after a closing right brace (}) that
ends a method declaration and after a closing right brace that ends a class declaration
specifies the closing right brace (}) of class Welcome1. Each comment indicates the method or
class that the right brace terminates.
Following the closing right brace (}) of a method body or class declaration with an end-of-line
comment indicating the method or class declaration to which the brace belongs improves
program readability.
We are now ready to compile and execute our program. For this purpose, we assume you are
using the Sun Microsystems' J2SE Development Kit. On the Downloads page at our Web site
21
([Link]), we provide Deitel® Dive Into™ Series publications to help you begin using
several popular Java development tools.
To prepare to compile the program, open a command window and change to the directory where
the program is stored. Most operating systems use the command cd to change directories. For
example,
cd c:\examples\ch02\fig02_01
cd ~/examples/ch02/fig02_01
javac [Link]
. Printing a line of text with multiple statements.
22
is an end-of-line comment stating the purpose of this program. Line 4 begins the Welcome2 class
declaration.
display one line of text in the command window. The first statement uses [Link]'s method
print to display a string. Unlike println, after displaying its argument, print does not position the
output cursor at the beginning of the next line in the command windowthe next character the
program displays will appear immediately after the last character that print displays. Thus, line
10 positions the first character in its argument (the letter "J") immediately after the last character
that line 9 displays (the space character before the string's closing double-quote character). Each
print or println statement resumes displaying characters from where the last print or println
statement stopped displaying characters.
A single statement can display multiple lines by using newline characters, which indicate to
[Link]'s print and println methods when they should position the output cursor at the
beginning of the next line in the command window. Like blank lines, space characters and tab
characters, newline characters are white-space characters. Figure 2.4 outputs four lines of text,
using newline characters to determine when to begin each new line.
Welcome
to
Java
Programming!
// Printing multiple lines of text with a single statement.
23
is a comment stating the purpose of this program. Line 4 begins the Welcome3 class declaration.
Line 9
[Link]( "Welcome\nto\nJava\nProgramming!" );
displays four separate lines of text in the command window. Normally, the characters in a string
are displayed exactly as they appear in the double quotes. Note, however, that the two
characters \ and n (repeated three times in the statement) do not appear on the screen. The
backslash(\) is called an escape character. It indicates to [Link]'s print and println methods
that a "special character" is to be output. When a backslash appears in a string of characters, Java
combines the next character with the backslash to form an escape sequence. The escape
sequence \n represents the newline character. When a new-line character appears in a string
being output with [Link], the newline character causes the screen's output cursor to move to
the beginning of the next line in the command window. Figure below are the lists of several
common escape sequences and describes how they affect the display of characters in the
command window.
Escape
sequence Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor at the beginning of the current linedo
not advance to the next line. Any characters output after the carriage return
overwrite the characters previously output on that line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double-quote character. For example,
displays
"in quotes"
24
2.4. Displaying Text with printf
A new feature of J2SE 5.0 is the [Link] method for displaying formatted datathe f in
the name printf stands for "formatted." outputs the strings "Welcome to" and "Java
Programming!" with [Link].
A new feature of J2SE 5.0 is the [Link] method for displaying formatted datathe f in
the name printf stands for "formatted." outputs the strings "Welcome to" and "Java
Programming!" with [Link].
Welcome to
Java Programming!
[Link]( "%s\n%s\n",
"Welcome to", "Java Programming!" );
call method [Link] to display the program's output. The method call specifies three
arguments. When a method requires multiple arguments, the arguments are separated with
commas (,)this is known as a comma-separated list.
Place a space after each comma (,) in an argument list to make programs more
readable.
25
Remember that all statements in Java end with a semicolon (;). Therefore, lines 9,10 represent
only one statement. Java allows large statements to be split over many lines. However, you
cannot split a statement in the middle of an identifier or in the middle of a string
Method printf's first argument is a format string that may consist of fixed text and format
specifiers. Fixed text is output by printf just as it would be output by print or println. Each
format specifier is a placeholder for a value and specifies the type of data to output. Format
specifiers also may include optional formatting information.
Format specifiers begin with a percent sign (%) and are followed by a character that represents
the data type. For example, the format specifier %s is a placeholder for a string. The format
string in line 9 specifies that printf should output two strings and that each string should be
followed by a newline character. At the first format specifier's position, printf substitutes the
value of the first argument after the format string. At each subsequent format specifier's position,
printf substitutes the value of the next argument in the argument list. So this example substitutes
"Welcome to" for the first %s and "Java Programming!" for the second %s. The output shows
that two lines of text were displayed.
[Link] a java program to add two integer numbers and display the sum
SOLUTION 1
26
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
SOLUTION
// Assign a radius
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;
// Display results
Q6. . Write a java program to compute the area of a CIRCLE ,given, area = Pi X R 2, pi = 3.142
and radius = ?.
28
double radius = [Link]();
// Compute area
double area = radius * radius * 3.14159;
// Display result
[Link]("The area for the circle of radius " + radius + " is " + area);
}
}
// Compute average
double average = (number1 + number2 + number3) / 3;
// Display result
[Link]("The average of " + number1 + " " + number2 + " " + number3 + " is " +
average);
}
}
Q8. Write a java program to convert second to minutes and show the remaining seconds.
import [Link];
29
int minutes = seconds / 60; // Find minutes in seconds
int remainingSeconds = seconds % 60; // Seconds remaining
[Link](seconds + " seconds is " + minutes + " minutes and " + remainingSeconds
+ " seconds");
}
}
Introduction
This chapter introduces data structures—collections of related data items. Arrays are data
structures consisting of related data items of the same type. Arrays make it convenient to
process related groups of values. Arrays remain the same length once they’re created, although
an array variable may be reassigned such that it refers to a new array of a different
length.
Arrays
An array is a group of variables (called elements or components) containing values that all
have the same type. Arrays are objects, so they’re considered reference types. As you’ll soon
see, what we typically think of as an array is actually a reference to an array object in memory.
The elements of an array can be either primitive types or reference types (including
arrays). To refer to a particular element in an array, we specify
the name of the reference to the array and the position number of the element in the array.
The position number of the element is called the element’s index or subscript.
Figure below, shows a logical representation of an integer array called c. This array contains
30
12 elements. A program refers to any one of these elements with an array-access
expression that includes the name of the array followed by the index of the particular element
in square brackets ([]). The first element in every array has index zero and is sometimes
called the zeroth element. Thus, the elements of array c are c[0], c[1], c[2] and so
on. The highest index in array c is 11, which is 1 less than 12—the number of elements
in the array. Array names follow the same conventions as other variable names.
This expression can be used to create the array shown in below. When an array is created, each
element of the array receives a default value—zero for the numeric primitive-type elements,
false for boolean elements and null for references. As you’ll soon see, you can provide
nondefault initial element values when you create an array. Creating the array in can also be
performed in two steps as follows:
In the declaration, the square brackets following the type indicate that c is a variable that will
refer to an array (i.e., the variable will store an array reference). In the assignment statement, the
array variable c receives the reference to a new array of 12 int elements.
A program can create several arrays in a single declaration. The following declaration reserves
100 elements for b and 27 elements for x:
String[] b = new String[ 100 ], x = new String[ 27 ];
When the type of the array and the square brackets are combined at the beginning of the
declaration, all the identifiers in the declaration are array variables. In this case, variables b and x
refer to String arrays. For readability, we prefer to declare only one variable per declaration. The
preceding declaration is equivalent to:
31
// Initializing the elements of an array to default values of zero.
public class InitArray
{
public static void main( String[] args )
{
int[] array; // declare array named array
Q. Write a java program to computes the sum of the element of the array, given the following
as array elements. (87, 68, 94, 100, 83, 78, 85, 91, 76, 87)
32
SOLUTION
// Computing the sum of the elements of an array.
Q. Write a java program to initialize the elements of an array with an array initializer
given the following as array elements (32, 27, 64, 18, 95, 14, 90, 70, 60, 370).
SOLUTION
int b[][] = { { 1, 2 }, { 3, 4 } };
33
Two-Dimensional Arrays with Rows of Different Lengths
The manner in which multidimensional arrays are represented makes them quite
flexible. In fact, the lengths of the rows in array b are not required to be the same. For