Вы находитесь на странице: 1из 92

Summary of Variables

The Java programming language uses both "fields" and "variables" as part of its terminology.
Instance variables (non-static fields) are unique to each instance of a class. Class variables (static
fields) are fields declared with the static modifier; there is exactly one copy of a class variable,
regardless of how many times the class has been instantiated. Local variables store temporary
state inside a method. Parameters are variables that provide extra information to a method; both
local variables and parameters are always classified as "variables" (not "fields"). When naming
your fields or variables, there are rules and conventions that you should (or must) follow.
The eight primitive data types are: byte, short, int, long, float, double, boolean, and char. The
java.lang.String class represents character strings. The compiler will assign a reasonable
default value for fields of the above types; for local variables, a default value is never assigned.
A literal is the source code representation of a fixed value. An array is a container object that
holds a fixed number of values of a single type. The length of an array is established when the
array is created. After creation, its length is fixed.
Arithmetic Operators
+ Additive operator (also used
for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operators
+ Unary plus operator; indicates
positive value (numbers are
positive without this, however)
- Unary minus operator; negates
an expression
++ Increment operator; increments
a value by 1
-- Decrement operator; decrements
a value by 1
! Logical complement operator;
inverts the value of a boolean
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for
if-then-else statement)
Type Comparison Operator
instanceof Compares an object to
a specified type
Bitwise and Bit Shift Operators
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR



Home : Course Map : Chapter 2 : Java : Operators
Operators


JavaTech
Course Map
Chapter 2
Introduction
Essentials
Structure
Keywords
Primitive Types
Comments
Literals
Expressions
Operators
Statements
Casts & Mixing
Strings
Console Output
Demo
Exercises
Supplements
Conditional: if-else
Repetitions
Flow Control
Java vs C/C++
JVM Instructions 1
The tables below group the Java operators according to similar
actions. For newcomers to Java, you can just scan these tables for
now, especially for operations dealing with class and objects, and
then refer back to them as you encounter more of the language.
Most of the operators are fairly straightforward but there can be
subtle details in their implementation that you must understand. For
example, you must know the difference in the pre- and post-
increment operations with regard to when the operation executes
versus when the value of the operand value returns.
We will return to many of these operators as the course proceeds.
General Properties of Operators
Comparison Operators
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Boolean Operators
Bitwise Operators
Class & Object Operators
Other Operators
Operator Precedence
Operator Associativity
Tech
Arithmetic Ops
Math Class
More on Integers
FP : Overview
FP : Java
Demo 1
More Mix/Cast
Demo 2
Exercises
Physics
Differential Eq.
Euler Method
Demo 1
Predictor-Corrector
Demo 2
Exercises

About JavaTech
Codes List
Exercises
Feedback
References
Resources
Tips
Topic Index
Course Guide
What's New
General Properties of Operators
In Java, an expression carries out some operation or operations that
are directed by a list of allowed operators. An operator acts upon
one, two or three operands. Here are some general properties of
operators:
Operands
An operand can be:
a numeric variable - integer, floating point or character
any primitive type variable - numeric and boolean
reference variable to an object
a literal - numeric value, boolean value, or string.
an array element, "a[2]"
char primitive, which in numeric operations is treated as an
unsigned two byte integer
The operator is unary if it acts on a single operand; binary if it
requres two operands. The conditional operator is the only ternary
operator in Java.
Each operator places specific requirements on the operand types
allowed. For example, the subtractive operator "- " in x=a-b;
requires that a and b variables be numeric types. The assignment
operator "=" then requires that x also be a numeric type. (If a and b
were wider types than x, a casting operation would also be
required.)
Returned Value
A value is "returned" at the completion of an operation. The
following statements use the assignment operator "=" and the
addition operator "+"
int x = 3;
int y = x+5;
and result in x holding the value 3 and y holding the value 8. The
entire expression y= x+5 could be used in another expression:
int x=3;
int y;
int z = (y=x+5) * 4;
which results in y holding 8 and z holding 32. The assignment
operator "=" in the expression "y=x+5" produces a new value for y
and also returns the value of y to be used in the expression for z.
Effects on Operands
In most of the operations, the operands themselves are not changed.
However, for some operators, the operand(s) do undergo a change:
Assignment operators: "x=y" replaces the value of the first
operand with that of the second. The other assignment
operators, "*=, +=, etc" will also replace the value of the
first operand but only after using its initial value in the
particular operation indicated by the symbol before the =
sign.
Increment & decrement operators: The operand is
incremented or decremented, before or after the operand's
value is returned, depending on whether it is a pre- or post-
increment of decrement.
If an operand is changed by the operation, note that if the statement
holding that expression is processed again, e.g. in a loop, the
resulting value can be different for each pass.
Expression Evaluation
The operands of an operator are always evaluated left to right. For
example, in
x = a + b;
the first "+" operator will determine the value of a and then b.
Do not get this rule confused with the precedence and associativity
rules.
Precedence determines the order in which operators act in
an expression of more than one operator. The table below
gives the rating for each operator, the higher number
indicating higher precedence.
Associativity rules determine the grouping of operands and
operators in an expression with more than one operator of
the same precedence.
For example, in the expression
x = a + b * c;
the first "+" operator still first determines its left operand ("a" in
this case) and then its right operand. But in this case the right
operand consists of the expression "b*c". The multiplication
operator "*" has a higher precedence than the additive "+".
Precedence can be overridden with parentheses, e.g.
x = (a + b) * c;
will force the addition of b to a, and then this sum is multiplied by
c.
Although the precedence ratings, which are similar to those in
C/C++, were chosen for the most "natural" ordering of the operator
evaluations, it never hurts to use the parentheses if you are unsure
of the precedence and don't have the table handy.
When the operations in an expression all have the same precedence
rating, the associativity rules determine the order of the operations.
For most operators, the evaluation is done left to right, e.g.
x = a + b - c;
Here, addition and subtraction have the same precedence rating and
so a and b are added and then from this sum c is subtracted. Again,
parentheses can be used to overrule the default associativity, e.g.
x = a + (b - c);
However, the assignment and unary operators, are associated right
to left, e.g.
x += y -= -~4;
is equivalent to
x += (y -= (-(~4)));
or in long hand,
int a = ~4;
a = -a;
y = y - a;
x = x + y;
Other Operator Tricks
Finally, here are some other miscellaneous notes about operators.
As indicated in the last example above, assignment operations can
be chained:
x = y = z = 4;
with the evaluations proceeding right to left.
Assignments can be combined into other operations, to compact the
code, e.g.
if( (x = 5) == b) y = 10;
which first sets x to 5, then returns that value for the test of b. You
should not overuse this technique else it makes the code unreadable.
Occasionally, though, it can be a neat approach.

Tables of Java Operators
Assignment Operators
x operation= y
is equivalent to
x = x operation y
x and y must be numeric or char types except for "=", which allows x and y also to be
object references. In this case, x must be of the same type of class or interface as y. If mixed
floating-point and integer types, the rules for mixed types in expressions apply.
=
Assignment operator.
x = y;
y is evaluated and x set to this value.
The value of x is then returned.
+=, -=, *=, /=, %=
Arithmetic operation and then assignment, e.g.
x += y;
is equivalent to
x = x + y;
&=, |=, ^=
Bitwise operation and then assignment, e.g.
x &= y;
is equivalent to
x = x & y;
<<=, >>=, >>>=
Shift operations and then assignment, e.g.
x <<= n;
is equivalent to
x = x << n;

Arithmetic Operators
x and y are numeric or char types. If mixed floating-point and integer types, then floating-
point arithmetic used and a floating-point value returned. If mixed integer types, the wider
type is returned. If double and float mixed, double is returned.
x + y Addition
x - y Subtraction
x * y Multiplication
x / y
Division
If FP arithmetic and y = 0.0, then infinity returned if x is not zero,
NaN if x is zero.
ArthmeticException thrown if x & y are integer types and y is zero.
x % y
Modulo - remainder of x/y returned.
If FP arithmetic and y = 0.0 or infinity,
then NaN returned
ArthmeticException thrown if x & y are integer types and y is zero.
-x
Unary minus
Negation of x value

Increment & Decrement Operators
x and y are numeric (FP & integer) or char types.
x++
Post-increment : add 1 to the value.
The value is returned before the increment is made, e.g.
x = 1;
y = x++;
Then y will hold 1 and x will hold 2
x--
Post-decrement : subtract 1 from the value.
The value is returned before the decrement is made, e.g. :
x = 1;
y = x--;
Then y will hold 1 and x will hold 0.
++x
Pre-increment : add 1 to the value.
The value is returned after the increment is made, e.g.
x = 1;
y = ++x;
Then y will hold 2 and x will hold 2.
--x
Pre-decrement : subtract 1 from the value.
The value is returned after the decrement is made, e.g.
x = 1;
y = --x;
Then y will hold 0 and x will hold 0.

Boolean Operators
x and y are boolean types. x and y can be expressions that result in a boolean value.
Result is a boolean true or false value.
x && y
Conditional
AND
If both x and y are true, result is true.
If either x or y are false, the result is false
If x is false, y is not evaluated.
x & y
Boolean
AND
If both x and y are true,the result is true.
If either x or y are false, the result is false
Both x and y are evaluated before the test.
x || y
Conditional
OR
If either x or y are true, the result is true.
If x is true, y is not evaluated.
x | y
Boolean
OR
If either x or y are true, the result is true.
Both x & y are evaluated before the test.
!x
Boolean
NOT
If x is true, the result is false.
If x is false, the result is true.
x ^ y
Boolean
XOR
If x is true and y is false, the result is true.
If x is false and y is true, the result is true.
Otherwise, the result is false.
Both x and y are evaluated before the test.

Comparison Operators
x and y are numeric or char types only except for "==" and "!="
operators, which can also compare references. If mixed types, then the
narrower type converted to wider type. Returned value is boolean true
or false.
x < y Is x less than y ?
x <= y Is x less than or equal to y ?
x > y Is x greater than y ?
x >= y Is x greater than or equal to y ?
x == y Is x equal to y ?
x != y Is x not equal to y ?

Bitwise Operators
x and y are integers. If mixed integer types, such as int and long,
the result will be of the wider type.

Note: Operations on byte and short types may give unexpected
results since operands are promoted to integers during intermediate
operations. For example,
byte x = (byte)0xFF;
x >>>= 1;
will result in 0xFF in x rather than 0x7F. That is because the
operation is carried out on a signed integer rather than simply on 8
bits. Here the signed byte is promoted to the signed integer
0xFFFFFFFF.

Use of an integer would go as follows:
int i = 0xFF;
i >>>= 1;
This results in 0x7F in the variable i.
~x Compliment
Flip each bit, ones to zeros, zeros to
ones
x & y AND
AND each bit a with corresponding bit
in b
x | y OR
OR each bit in a with corresponding
bit in b
x ^ y XOR
XOR each bit in x with corresponding
bit in y
x << y Shift left
Shift x to the left by y bits. High order
bits lost.
Zero bits fill in right bits.
x >> y
Shift Right
-
Signed
Shift x to the right by y bits. Low
order bits lost.
Same bit value as sign (0 for positive
numbers, 1 for negative) fills in the
left bits.
x >>> y
Shift Right
-
Unsigned
Shift x to the right by y bits. Low
order bits lost.
Zeros fill in left bits regardless of sign.

Class and Object Operators
x instanceof c
Class Test
Operator
The first operand must be an object reference.
c is the name of a class or interface.
If x is an instance of type c or a subclass of c, then true
returned.
If x is an instance of interface type c or a sub-interface, then
true is returned.
Otherwise, false is returned.
new c(args)
Class
Instantiation
Create an instance of class c using constructor c(args)
"."
Class Member
Access
Access a method or field of a class or object :
o.f - field access for object o
o.m() - method access for object o
()
Method
Invocation
Parentheses after a method name invokes
(i.e. calls) the code for the method, e.g.
o.m()
o.m(x,y)
(c)
Object
Cast
Treat an object as the type of class or interface c:
c x=(c)y;
Treat y as an instance of class or interface c
+
String
Concatenation
This binary operator will concatenate one string to another.
E.g.
String str1 = "abc";
String str2 = "def";
String str3 = str1 + str2
results in str3 holding "abcdef".
For mixed operands, if either a or b in (a + b) is a string,
concatenation to a string will occur. Primitives will be
converted to strings and the toString() methods of objects
will be called.
(This is the only case of operator overloading in Java.)
Note that the equivalence operator "+=" will also perform
string concatenation.
[]
Array Element
Access
In Java, arrays are classes. However, the bracket operators
work essentially the same as in the C/C++.
To access a given element of an array, place the number of
the element as an int value (long values cannot be used in
Java arrays) into the brackets, e.g.
float a = b[3];
int n = 5;
char c=c[n];
where b is a float array and c is a char array.

Other Operators
x=boolean?y:x
Conditional
Operator
The first operand - boolean - is a boolean variable or expression.
First this boolean operand is evaluated. If it is true then the second
operator evaluated and x is set to that value.
If the boolean operator is false, then the third operand is evaluated
and x is set to that value.
(primitive type) Type Cast
To assign a value of one primitive numeric type a more narrow type,
e.g. long to int, an explicit cast operation is required, e.g.
long a = 5;
int b = (int)a;

Operator Precedence
The larger the number, the higher the precedence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=
?: || && | ^ & ==
!=
<
<=
>
>=
<<
>>
>>>
+
-
*
/
%
new
(type)
++x
--x
+x
-x
~
!
.
[]
(args)
x++
x--
Notes:
(type) refers to the casting operator
"." is the object member access operator
[] is the array access operator
(args) indicates the invocation of a method.
In column 11, the + and - refer to binary addition and subtraction. Also, the + refers tothe string
append operator. Whereas in column 14, the + & - refer to the unary operations +x and -x specify
the sign of the value.
|, ^, and & refer to both the bitwise and boolean operators.

Operator Associativity
The following operators have Right to Left associativity. All other operators (see
precedence table above) are evaluated left to right.
=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=
?:
new
(type cast)
++x
--x
+x
-x
~
!

References & Web Resources
JVM Specification, 2nd Ed.
Java in a Nutshell, 4th Ed.
Latest update: May 22, 2008


Part I
Part II
Part
III
Java Core 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20 21
22 23
24
Supplements 1 2 3 4 5 6 7 8 9 10 11 12
Tech 1 2 3 4 5 6 7 8 9 10 11 12
Physics 1 2 3 4 5 6 7 8 9 10 11 12

Java is a trademark of Sun Microsystems, Inc.



A Java applet is a special kind of Java program that a browser enabled with Java technology can
download from the internet and run. An applet is typically embedded inside a web page and runs in the
context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet
class provides the standard interface between the applet and the browser environment.

From Zero to Applet in 60 Minutes

Written by: Larry Coffey

Who is this written for?

If you've always wanted to know how to write a small program that you could put up on your website,
then, with only a little programming experience, this tutorial can help you achieve that goal.

You don't have to know Java - yet - but you should have at least some technical background, with at
least a remedial understanding of web pages, the Internet, and your operating system (i.e. Windows).
Also, some programming background is very helpful, perhaps a class in high school or in college, or even
just writing small scripts or SQL queries.

I won't be teaching you programming concepts here. But I will introduce you to some of the Java
language; however it will only be enough of what it takes to write a small Java applet and put it onto a
web page.

Still with me? Excellent. Let's go build a Java applet!

(Photo credit: Eric Kilby)
Table of Contents
1. Section 1: The Java Development Environment
2. Section 2: Java Basics
3.
4.
5.
6. Section 3: Applet Structure
7.
8. Section 4: Compiling The Applet Code
9.
10.
11.
12.
13.
14.
15.
16.
17. Section 5: The Web Page
18.
19. Section 6: Testing The Applet
20. Section 7: The Jar File
21.
22.
23.
24.
25. Section 8: Something Useful
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41. Appendix A: Links - For Further Study
42. Appendix B: Definitions - Useful Terms Related To This Tutorial
43.
Section 1: The Java Development Environment
You will need a Java development environment set up on your system to complete this tutorial. If you
haven't set one up yet, no worries, simply follow the instructions here: My First Java Environment. I will
make use of the tools you installed there: TextPad (text editor) and Eclipse (integrated development
environment or "IDE").

If you have your own favorite text editor or integrated development environment (IDE), you can still
follow this tutorial as a guideline for what it takes to build a Java applet. While some of the procedures
may be different between Eclipse and what you use, the final concepts are the same.
Section 2: Java Basics
nvented in 1991 at Sun Microsystems by a team led by James Gosling, Java has matured over the years,
yet retained much of the structural cleanliness that has made it one of the most popular programming
languages in recent years. Recently, with Oracle's acquisition of Sun Microsystems, Oracle affirmed its
committment to continue support of the language, with the initial focus being on greater modularity,
better support for non-Java languages, and better performance".

Much of the syntax is borrowed from the original "C" language, so if you're already familiar with "C",
you'll most likely be able to read a Java program listing. The major difference is that Java was designed
from the ground up to be an object oriented language, and, as such, places some restrictions on what
can and cannot be done syntactically. Furthermore, while "C" compiles down to a computer's native
machine code, for platform portability, Java compiles into a bytecode (also called "P-code") which is
then interpretted by the local machine. One other Java feature is the lack of exposed pointers, which
causes some frustration to "C" programmers first learning the Java language.

The famous "Hello World" program, in "C":

#include
int main (int argc, char **argv)
{
printf ("Hello, World!"); // Display the string.
return (0);
}

The famous "Hello World" program, in "Java":

class HelloWorldApp
{
public static void main (String[] args)
{
System.out.println ("Hello, World!"); // Display the
string.
}
}
The following is by no means a comprehensive list, but it does highlight some of the differences
between the "C" and Java languages:


Java
C


Runs in secure virtual machine
Exposes access to system-wide resources


No pointers for primitive types
Pointers, pass by reference, widely used


Immutable strings
Arrays of char


Native Unicode support
ASCII char type


Classes
Structures


Garbage collection
Explicit memory management


Uses import statements
Uses include statements


No class destructor
C defines an optional destructor



The following compares the primitive data types used by "C" and Java. Note that "C" sometimes uses
long, short, signed, and unsigned as prefixes to standard data types to explicitly define the
variable, while, in Java, all numeric data types are signed:


Primitive
Java
C


byte
8-bit signed value, similar to C's char
No definition


short
16-bit signed integer
16-bit integer


int
32-bit signed integer
Implementation dependent, typically 32-bit


long
64-bit signed integer
64-bit signed integer


float
32-bit IEEE floating point
32-bit IEEE floating point


double
64-bit IEEE floating point
64-bit IEEE floating point


boolean
Can be true or false, size dependent on implmentation; similar to C's bool
No definition


char
16-bit Unicode character
8-bit signed value, similar to Java's byte


bool
No definition
Can be true or false, size dependent on implmentation though typically the size of an int;
similar to Java's boolean



A Java program has one class per module (file), though a class may contain one or more nested classes.
A class is said to be instantiated when it is bound to an object. For example, when executed, TextArea
ta = new TextArea (); will create the object named ta, an instantiation of the class
TextArea. Simply defining the variable, TextArea ta;, does not create an instantiation. An
object must be assigned to it before the variable can be used.

A typical Java source file uses the following physical structure to define a class:

import statements;
class definition
{
instance variables;
constructor definition (arguments)
{
local variables;
procedural statements;
}
method definition (arguments)
{
local variables;
procedural statements;
}
...
method definition (arguments)
{
local variables;
procedural statements;
}
}
Section 3: Applet Structure
Now that the 25 cent tour of the Java language is over, let's concentrate on what it takes to build a real
live Java applet. An applet lives within a browser's context. All the major browsers work the same: an
HTML statement called Applet defines how the browser finds, makes space for, and executes the
applet code. We'll get into the exact syntax of the HTML later, as well as the building of the JAR file that
the Applet statement uses. For now, we'll concentrate on building a real simple that demonstrates the
entry points to an applet.

When an browser first loads an applet, it calls the init method once and only once. The start
method is executed whenever the applet is refreshed. The stop method is called to halt the execution
of the applet, while destroy is called by the browser to reclaim all resources used by the applet.
Below, I present a complete barebones applet, and though it is completely functional, it doesn't do
anything except take up space.

1 import java.applet.Applet;
2 public class TutorialOne extends Applet
3 {
4 public TutorialOne ()
5 {
6 System.out.println ("Tutorial: Constructor");
7 }
8 public String getAppletInfo ()
9 {
10 return ("Written by: *YOUR NAME GOES HERE*");
11 }
12 public void init ()
13 {
14 System.out.println ("Tutorial: init");
15 }
16 public void start ()
17 {
18 System.out.println ("Tutorial: start");
19 }
20 public void stop ()
21 {
22 System.out.println ("Tutorial: stop");
23 }
24 public void destroy ()
25 {
26 System.out.println ("Tutorial: destroy");
27 }
28 }
Let's examine this applet, line by line.

Line 1 - The import declaration is used to reference classes declared in other packages. In this case, we
only need the Applet class, but later you'll see that the list of import declarations will grow as you use
more of Java's standard package libraries.

Line 2 - The class statement declares the scope and name of the class, as well as any superclasses or
interfaces it uses. Since this is a top-level class, it must be declared public, and since we are writing an
applet, we need to extend the java.applet.Applet class. At this time we won't be using any
interfaces, but a commonly used interface for an applet is the Runnable interface.

Line 3 - Curly braces are used to identify a block of programming statements. A class statement, a
method declaration, if, while, and for constructs all make use of curly braces to uniquely identify the
code associated with those statements. For every open brace, there must be a matching close brace. In
this example, the matching close brace is on line 28.

Line 4 - The constructor method takes the same name as class, in this case, TutorialOne. Note that
in Java, there is no explicit destructor like in C++. While coding an explicit constructor is usually good
programming practice, it is not necessary. If a constructor is not provided, then the compiler will default
to using the no-argument constructor of the superclass. If no superclass is declared, it will default to the
Object class's constructor.

Line 6 - Procedural code is placed within each class's methods. In this case we just use a print statement
to announce the class has been instantialized. When a class is bound to a variable, the object's
constructor is called.

Line 8 - The getAppletInfo method returns information about the applet you write. You should
return a String containing the author, version, and copyright of the applet.

Line 10 - The return statement from getAppletInfo uses a string literal. Though strings are
handled internally very differently in Java than in "C", you'll notice that the literals look very similar.

Line 12 - The init method is called by the browser to inform you that this applet has been loaded into
the system. It is only called once.

Line 16 - The start method is called by the browser to inform you that this applet should start its
execution. If we needed to start any threads, this is the right place to do it (we'll do that later).

The Java documentation is a little misleading on when the start and stop methods are used. Older
browsers would call the stop method only when the browser switched to another page, and then call
only the start method again should you eventually cycle back to the page with the applet on it again.
This type of behavior caused stability problems with browsers, so is no longer in modern browsers. They
will call the stop and destroy methods upon exiting and completetely reload the applet upon a
return to the same webpage, calling the init and start methods once again. An brief explanation of
this behavior is given in the evaluation section of this bug recorded in the Java bug database.

Line 20 - The stop method is called by the browser to inform you that this applet should stop its
execution. This method is always called before the destroy method.

Line 24 - The destroy method is called by the browser to inform you that this applet is being
reclaimed and should free any resources that it has allocated. This is usually the last method that an
applet will see before the applet terminates.
Section 4: Compiling The Applet Code
Here's where the real fun begins. Now we need to start up the IDE, enter the applet code, and compile
it. I'll describe the procedure using the Eclipse IDE here for this tutorial. Go ahead and start up the the
Eclipse IDE now, either by double clicking on the Eclipse shortcut or on the eclipse.exe executable itself.

If you use a different IDE, go ahead and enter the code now and compile it into a TutorialOne.class file.

If you use the command line, enter javac -deprecation TutorialOne.java to create the
TutorialOne.class file.

Click on the File menu, select New, and click on Java Project.

Enter a Project Name of TutorialOne and then click the Finish button.

Next, find the TutorialOne project in the Package Explorer tab (below the File menu), and
click the [+] box to expand the contents of the list. Right click on the src folder, select New, and
click on File.

Enter a File Name of TutorialOne.java and click the Finish button. Please note that the
".java" extension is very important. If you omit it, the project won't compile correctly.

Copy and paste the TutorialOne source into the editor. Here it is again, without the line numbers:

import java.applet.Applet;
public class TutorialOne extends Applet
{
public TutorialOne ()
{
System.out.println ("Tutorial: Constructor");
}
public String getAppletInfo ()
{
return ("Written by: *YOUR NAME GOES HERE*");
}
public void init ()
{
System.out.println ("Tutorial: init");
}
public void start ()
{
System.out.println ("Tutorial: start");
}
public void stop ()
{
System.out.println ("Tutorial: stop");
}
public void destroy ()
{
System.out.println ("Tutorial: destroy");
}
}

Finally, from the Run menu, open the Run As submenu and select Java Applet.

If you have correctly completed the above steps, then an empty Applet Viewer should pop up.
Don't worry about it not containing anything, we'll do something useful shortly. However, the
Console Window at the bottom of the screen should display some of the print messages we put
into the program.

If you close the Applet Viewer, then the applet displays its closing print messages and
terminates.

At this point, you have successfully compiled a very basic Java applet. However, you are only
half way there, since to create a real applet that others may use, it must run on a webpage not
from within development environment's applet viewer. We tackle that problem next.
Section 5: The Web Page
A Java applet lives within the context of a webpage. The key component for loading a Java applet is the
HTML applet tag. Though the applet tag is officially deprecated, it is the only tag that runs
[relatively] cleanly against the widest range of browsers. Other alternatives, the object or embed tags
can be used, but have compatibility issues between browser venders and older browsers. Since the goal
of this exercise is to quickly learn how to write a Java applet, we'll forgo the discussion of browser
compatibility and stick with the deprecated, yet still useful, applet tag.

The applet tag takes a few parameters that are useful to us:
code - Specifies the name of the Java applet
width - Specifies the width of the applet
height - Specifies the height of the applet
archive - Specifies the location of the archive file (See The JAR File below)

Between the <applet> and </applet> tags, you place any HTML code that would be displayed if
the applet fails to load. This is a good place to inform the user that the browser needs to be Java-
enabled to view the applet.

Using a text editor, like TextPad, copy and paste the following HTML code into a new file, and save it
with the name TutorialOne.html:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head>
<title>Tutorial</title>
<style type="text/css">
body { color: white; background: black }
</style>
</head>
<body>
<div>
<h1 align="center">Tutorial One</h1>
<applet code=TutorialOne.class width=640 height=480>
<p>
Sorry, you need a Java-enabled browser to run this
applet.
</p>
</applet>
</div>
</body>
</html>
Section 6: Testing The Applet
Before you run the applet, if you haven't done so already, enable the Java Console so you can see the
debugging output. This setting is found in the Windows Control Panel, in the Java Control Panel (Java
icon). For more details see: How do I enable and view the Java Console?

The Java Console allows you to see output from the applet's numerous System.out.println
statements. The Java Console starts up automatically when an applet is executed - when the webpage
for the applet is loaded the first time.

The key to making this work is to place the compiled Java code in the same directory as the HTML file.
You will need to copy TutorialOne.class into the same directory as TutorialOne.html.

Compiled Java files have a .class extension. In this particular example, you are looking to grab the
TutorialOne.class file. If you used the Eclipse IDE to build your this applet, then the compiled Java code
will be found in your Eclipse workspace directory, under the project name's bin directory. For example, if
your workspace was off the top level, then the compiled Java file would be
C:\workspace\TutorialOne\bin\TutorialOne.class.

Once you have insured that the two files are in the same directory, double click the TutorialOne.html
file. Your default browser will launch, displaying the HTML file you just created. The Java Console should
also popup, displaying some housekeeping information, followed by the lines:

Tutorial: Constructor
Tutorial: init
Tutorial: start

When you close the webpage, or shut down the browser, two more lines will be displayed briefly before
the Java Console eventually closes after a few seconds. Note that the Java Console will remain active and
visible as long as a Java applet is running or until you manually close the Java Console. On some
browsers, it may remain open for as long as you leave any browser window open.

Tutorial: stop
Tutorial: destroy

Note that for some browsers, especially Microsoft Interent Explorer, there may be a minor issue running
the applet. Even if you have enabled Java for your browser, if you run this on a local machine, some
browsers may restrict Java execution with a message similar to "To help protect your security, Internet
Explorer has restricted this webpage from running scripts or ActiveX controls that could access your
computer." If you find this to be the case, simply click on the message and select "Allow Blocked
Content..." from the popup menu to allow the applet to run.
Section 7: The Jar File
Remember back in Section 2 when I mentioned that a Java program has one class per file? Well applets
would become pretty unwieldy if they were all written as one monolithic class, not to mention the
violation of every good programming practice on the planet. But, the applet tag has only one provision
for a single class file. So how do we use multiple classes when only one class file can be specified?

Enter, the JAR file. A JAR file (or Java ARchive) is a compressed file, like a ZIP, that contains all the
compiled modules, and if necessary, the resources (like image files, sounds, etc.) that an applet needs.

Fortunately, Eclipse provides a facility to build JAR files for you. Once you've debugged the applet, using
the applet viewer and Eclipse's development facilities, you can easily export a JAR file.

For those that use the command line, running jar cf NAME.jar *.class in the directory
containing the compiled binaries will build you a simple JAR file. Replace NAME with your archive name.

Okay, so let's build a JAR file from what you've built already. Find the TutorialOne project in the
PackageExplorer tab (positioned below the File menu). Right click on TutorialOne to get the pop up
menu, and select Export...

Next, click on the [+] next to Java to expand the tree, select JAR file and then click the Next
button.

The next step is just telling Eclipse where to put the JAR file it creates. Just put it in the same
directory that you have the HTML file already (i.e. the TutorialOne.html file). Click on the
Browse button to do this, then enter the name of TutorialOne.jar and click the Finish button.

Since there shouldn't be any compiler errors, it should complete properly. However, it may build
with one warning. Ignore that for now - we'll get to that later in the next section. Note that the
next time you build this, there will be an additional prompt asking if you want to overwrite the
existing file (that's a Yes, by the way).

We're almost done. One last thing. Edit the TutorialOne.html file to change the applet statement
to include the JAR file using the archive parameter:

<applet code=TutorialOne.class archive=TutorialOne.jar width=640
height=480>

And that's all there is to it. Double click on the HTML file, and the applet will launch just like before. If
you had previously copied the TutorialOne.class file to your working folder, delete it to verify it is
executing from the JAR and not the class file. Of course, the applet doesn't do anything useful yet - I'll
show you how to do that in the next section.
Section 8: Something Useful
Build the Applet
Okay, then. Suppose, for an instance, that the ancient Romans had actually discovered electricity and
used that knowledge to make something more sophisticated to measure time than a sun dial. Perhaps
they would've eventually got around to making digital clocks. Silly? Quite possibly, but it'd certainly
make a good Java applet. And it's a lot more fun than printing strings to a debugging console. So, let's
make a digital clock, using Roman numerals!

I will quickly touch on some Java concepts that are used in the applet. This is by no means intended to be
a comprehensive how to program in Java. I refer you to the online documentation for more details about
the classes and methods I use here.

First let us create the new project, compile it, and run it, then I will briefly explain some of the concepts I
use in the program. Like before, click on the File menu, select New, and click on Java Project. Enter a
Project Name of TutorialTwo and then click the Finish button.

Also, as before, find the TutorialTwo project in the Package Explorer tab (below the File
menu) and click the [+] box to expand the contents of the list. Right click on the src folder, select
New, and click on File. Enter a File Name of TutorialTwo.java and click the Finish
button. Don't forget the ".java" extension in the file name or it won't compile and run!



Now, copy and paste the following code into the file, and then save it (don't worry about what it
all does at the moment - I'll explain the key points of it later).

Editorial note: Due to Squidoo limitations, the following code sample spans two Squidoo text
areas and therefore needs to be copied and pasted from the two sections below. For those that
want to download the file directly, I provide it here: TutorialTwo.java

//
// Roman Digital Clock
// Written by: Larry Coffey
//
import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
* TutorialTwo is the main class for the TutorialTwo applet.
*
* @author Larry Coffey
* @version 0.01, 19 March 2010
*/
public class TutorialTwo extends Applet implements Runnable
{
/** Serial version ID as required by serializable classes */
private static final long serialVersionUID = 1L;
/** Size of the applet area */
private Dimension appletSize = null;
/** Timer thread object used to signal refreshing the clock
*/
private volatile Thread timerThread = null;
/** Font object used to draw Roman digits */
private Font digitsFont = null;
/** Paired lookup table used by the "toRoman" method */
private StringIntPair tableNumerals[] =
{
new StringIntPair ("M", 1000),
new StringIntPair ("CM", 900),
new StringIntPair ("D", 500),
new StringIntPair ("CD", 400),
new StringIntPair ("C", 100),
new StringIntPair ("XC", 90),
new StringIntPair ("L", 50),
new StringIntPair ("XL", 40),
new StringIntPair ("X", 10),
new StringIntPair ("IX", 9),
new StringIntPair ("V", 5),
new StringIntPair ("IV", 4),
new StringIntPair ("I", 1)
};

/**
* Constructor for the TutorialTwo class.
*/
public TutorialTwo ()
{
// Initialize member variables
System.out.println ("Tutorial: Constructor");
timerThread = null;
digitsFont = null;
}

/**
* Returns information about the author.
*
* @return Applet author information string
*/
public String getAppletInfo ()
{
return ("Written by Larry Coffey, Copyright (c) 2010
SillyTutu.com, Inc.");
}

/**
* Called by the browser or applet viewer to inform this
applet that it has been loaded into the system.
*/
public void init ()
{
System.out.println ("Tutorial: init");
appletSize = getSize ();
digitsFont = new Font ("Serif", Font.BOLD, 48);
}

/**
* Called by the browser or applet viewer to inform this
applet that it should start its execution.
*/
public void start ()
{
System.out.println ("Tutorial: start");
timerThread = new Thread (this);
timerThread.start ();
}

/**
* Called by the browser or applet viewer to inform this
applet that it should stop its execution.
*/
public void stop ()
{
System.out.println ("Tutorial: stop");
timerThread = null;
}

/**
* Called by the browser or applet viewer to inform this
applet that it is being reclaimed
* and that it should destroy any resources that it has
allocated.
*/
public void destroy ()
{
System.out.println ("Tutorial: destroy");
}

/**
* Executes the main thread of this applet.
*/
public void run ()
{
Thread currentThread = Thread.currentThread ();
while (currentThread == timerThread)
{
repaint ();
try {Thread.sleep (500);}
catch (InterruptedException e) {e.printStackTrace ();};
}
}

/**
* Repaints the canvas
*
* @param g Graphics context
*/
public void paint (Graphics g)
{
GregorianCalendar currentDate;
int s, m, h, width, height, x, y;
String timeString;
FontMetrics fm;

// Get the current time and convert it to Roman numerals
currentDate = new GregorianCalendar ();
s = currentDate.get (Calendar.SECOND);
m = currentDate.get (Calendar.MINUTE);
h = currentDate.get (Calendar.HOUR);
timeString = "" + toRoman (h) + " : " + toRoman (m) + " :
" + toRoman (s);

// Set the font, and calculate the size of the string
g.setFont (digitsFont);
fm = g.getFontMetrics ();
width = fm.stringWidth (timeString);
height = fm.getHeight ();

// Calculate the string position and draw it centered
x = (appletSize.width - width) / 2;
y = ((appletSize.height - height) / 2) + fm.getAscent ();
g.drawString (timeString, x, y);
}

/**
* Converts a given value into a string of Roman digits.
*
* @param number Value to convert
*
* @return String of Roman numerals
*/
private String toRoman (int number)
{
String romanString;
int i;

// Number out of range
if ((number < 0) || (number > 4000))
return ("-");

// Cheating: Romans didn't have a zero
if (number == 0)
return ("0");

romanString = "";
for (i = 0; i < tableNumerals.length; i++)
{
while (number >= tableNumerals[i].integer)
{
number -= tableNumerals[i].integer;
romanString += tableNumerals[i].string;
}
}
return (romanString);
}

/**
* Class used to implement a string and integer paired
value data structure.
*
* @author Larry Coffey
*/
class StringIntPair
{
/** String component of the pair */
String string;
/** Integer component of the pair */
int integer;
/**
* Constructor for the StringIntPair class.
*
* @param string Initial string value
* @param integer Initial integer value
*/
StringIntPair (String string, int integer)
{
this.string = string;
this.integer = integer;
}
}
}
The first decision we need to make is to determine the applet size. There are two reasons for this. The
first is obvious: the HTML applet tag takes a width and height parameter to lay out the real estate the
applet needs on a webpage. The second is for debugging purposes. The applet viewer in Eclipse needs to
be told how big to be.

Let's set the applet viewer size first, so that we can run it within the Eclipse debugging environment. In
the Package Explorer, right click on the TutorialTwo project and select the Properties item from the
popup menu.

In the Properties for TutorialTwo dialog box, click on the Run/Debug Settings, select
TutorialTwo, and then click the Edit button.

In the Edit Configuration dialog box, you'll see several tabs. Select the (x)=Parameters tab,
and enter 500 into the Width field and 100 into the Height field. That should be sufficient space
to display our Roman digital clock. Through experimentation, you may wish to change these
values to suit your own tastes.

Now we are set to run the program in the debugger. Go ahead and run it! Hint: From the Run
menu, select Run As, then Java Applet. What you see should be something like this:

To build a JAR file and run it from within a webpage, follow the same instructions as for
TutorialOne above, except use a filename of TutorialTwo.jar. Here is the HTML code for the
webpage; save it as TutorialTwo.html in the same folder with the TutorialTwo.jar file (please
note the width and height parameters for the applet tag):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">
<head>
<title>Tutorial Two</title>
<style type="text/css">
body { color: white; background: black }
</style>
</head>
<body>
<div>
<h1 align="center">Tutorial Two</h1>
<applet code="TutorialTwo.class" archive="TutorialTwo.jar"
width="500" height="100">
<p>
Sorry, you need a Java-enabled browser to run this
applet.
</p>
</applet>
</div>
</body>
</html>
Once you've built the JAR file and created the HTML file, double click the HTML file to launch the
browser. Now you've created a Java applet that can be deployed onto a real web server!
Java Concepts Used in the TutorialTwo Applet
Let me explain some of the key points to the applet we just built. I suggest that you take the time to look
at some of the Java documentation for each of these, especially if one or more of the concepts are new
to you.

Serialization - Remember that warning we had in TutorialOne? The one that said we had not defined a
static final serialVersionUID field of type long? Well, we solve that problem by actually defining a
static final serialVersionUID field of type long on line 22.

Simple, eh? But what is it used for? It is a unique identifier for a class that can be serialized - and the
class Applet implements the Serializable interface. Serialization is useful on larger projects
where different versions of classes and class libraries may exist during the life of the software. For such a
simple program as this, serialization is irrelevent, so I use a simple, default value.

Nested Classes - The class StringIntPair (starting on line 188) is a very simple nested class,
completely subordinate to the TutorialTwo class. Nested classes do not require a separate module,
being wholly contained within their parent class. I use StringIntPair very similarly to a "C" struct
here, to make an array named, tableNumerals (line 30), which contains a paired list of two separate
data types, a String and an int.

The private method toRoman (line 58) makes use of this array to convert an integer value into a string
of Roman numerals. Note that, like in most programming situations, there are other equally valid ways
to solve this problem. I could've used parallel arrays (one of type String and one of type int), or I
could've used a doubly subscripted array of type Object. But if I had done that, I would've passed up a
perfect opportunity to demonstrate nested classes.

Threads - To keep the Java applet updating the screen with the correct time, we need to create a thread
that wakes up every half second or so and redraws the screen. Java threads are easy to work with. A
class that uses threads needs to implement the Runnable interface with the class definition (line 19).
The class then needs to include a run method in its definition (line 109).

The thread is actually created in the start method (line 81) and stored in the member variable,
timerThread (defined on line 26). This variable, timerThread is used as a signal to terminate the
thread when, in the stop method (line 91), it is set to null (line 94). The next time the thread wakes
up, the run method will exit when the current thread and timerThread values fail to match (line
112).

What goes on inside the run method is worth examining. The exit condition test, mentioned above,
allows the applet to exit gracefully. Within the loop itself, the repaint call (line 114) forces the applet
to redraw itself (an Applet class inherits this method from the Panel class) which triggers a call to
the overridden paint method (line 125) (also inherited from the Panel class. After the repaint call,
the thread then goes to sleep for a half-second, using the Thread.sleep (500); method. Note
that this method can generate an exception that must be handled - I'll discuss exceptions next.

While it is true that Applet inherits from Panel, Panel in turn inherits from Container,
which itself in turn inherits from the Component class. The repaint method is technically
from the Component class and this applet's paint method is technically overriding the
paint method from the Container class.
Exceptions - During execution, any program may encounter an abnormal situation or unexpected event.
The Java language handles this by "throwing" an exception, which may come in one of two ways:
checked or unchecked. Checked exceptions are explicitly required to be handled by the calling methods.
The Thread.sleep method described above (line 115) is a good example of a checked exception.

An unchecked exception, on the other hand, is one that is not explicitly required to be caught, but could
be generated during program execution nevertheless. For example, a divide by zero error is a good
example of an unchecked exception. In Java, any subclass of RuntimeException is considered an
unchecked exception.

In either case, the handling is the same: using a try, catch, finally construct. It works like this:
the code that could generate an exception is placed within the try block. If and only if an exception
occurs, then code placed within the catch block is executed. Regardless of which block exited, the try
or catch, the finally block is executed. The finally block is optional and if it doesn't exist,
program execution just falls through to the next statement following the catch block.

Since Thread.sleep requires handling the InterruptedException exception, we place the
try block around Thread.sleep (500); (line 115) and the catch block follows it (line 116). I
don't do anything special to handle the exception; we simply ask that a stack trace be sent to the
console device (e.printStackTrace ();) so we can debug any problem should it occur.

There is one case where this exception can occur that is perfectly legal - when the program is exiting.
Under normal circumstances you probably wouldn't leave the stack trace for this situation in a deployed
program, but - as you've probably seen already - leaving it in demonstrates how exception handling
works. You should see a stack trace upon exit, because the Thread.sleep (500); method was
interrupted. And that's okay.

GregorianCalendar - At the heart of any program that wants to display the time, there must be a facility
for retrieving the current date and time from the system. In Java, the easiest way to do this is with the
GregorianCalendar class. Note that while Java does have a Date class, most of its functionality has been
deprecated.

A GregorianCalendar object is first instantiated (line 133) and then current time is retrieved using
the get method, passing it in sequence, Calendar.SECOND, Calendar.MINUTE, and
Calendar.HOUR (lines 134-136). We then convert those values to Roman numerals and construct the
string to be displayed (line 137).

Graphics - As with most windowing operating systems, a graphics context needs to be specified. Java
facilitates the maintaining and rendering a basic graphics state with the Graphics class. More complex
operations can be handled with its subclass, Graphics2D.

An instantiated Graphics object is passed to us in the paint method (line 125). You can see we
make use of the Graphics object to set the font (line 140), to get information about the font (line
141), and to draw the Roman numerals onto the screen (line 148). The Graphics and Graphics2D
classes are fairly extensive; I highly recommend you familiarize yourself with these classes if you plan on
doing more complex graphical programming.

Font - Java provides extensive support for maintaining and rendering a wide variety of character
representations. A font, at its simplest, is just a description of how to render a character's glyph to the
screen. In our case, all we want to do is create a "big" font in which to display Roman numerals.

When the applet is first loaded, the init method is called (line 71). At this point we create a 48 point
font (line 75) that will be used to render the Roman numerals later. We do this up front because it's a
one time operation that would be time consuming to do each time in the paint method.

Since we want the Roman numerals to be centered within the applet window, we need to know how big
the string will be when rendered. Since the string size changes each second, unfortunately, it must be
calculated with in the paint method (line 125).

The first step is to set the graphics context to use the 48 point font (line 140), and then retreive
information about the rendered version of that font (line 141). From there we can get the exact width
(line 142) and height (line 143) of the string before it's drawn on the screen. Since we already saved the
size of the applet window (line 74), it's a simple calculation to center the string.

BUT WAIT... Where would a programming environment be without its strange quirks? The
Graphics.drawString method does not use the coordinates you pass to it to start drawing the
string at the upper left of the string nor at the lower left of the string or any seemingly reasonable spot
you'd want to start. Instead it is drawn at the baseline of the leftmost character. Without going into the
hows and whys of it here, to compensate for this weirdness, we need to add back the distance for the
font's baseline to the font height to give us a usable upper left coordinate of the string. This is achieved
with a call to FontMetrics.getAscent (line 147).
Preparing a Program for JavaDoc
By now you've probably noticed the way the program is documented. Java has a facility for easily
producing program documentation from program source code if a few simple rules are followed:
Comments that begin with /** will show up in the generated Java documentation
Comments that begin with /* or // will be ignored by JavaDoc
Certain tags can, and should, be placed within JavaDoc comments using the @ symbol
The @author tag indicates the programmer of the class
The @version tag indicates the class version number
The @param tag indicates the input parameter to a method, followed by the variable name, and
a brief description of its usage
The @return tag indicates the return value from a method, followed by a brief description of its
meaning
Other @ tags exist that may or may not be relevant in documenting your code

Let's go ahead and generate our own documentation right now!

In Eclipse, from the Project menu, select Generate JavaDoc... The first time you run it, you'll have to
give it the JavaDoc command. This means you just need to give it the full pathname of the javadoc.exe
that was installed along with the JDK. Click on the Configue button and browse to the bin directory of
the JDK, then select the javadoc.exe file that is there. This should result in a pathname similar to:
C:\Program Files\Java\jdk1.6.0_18\bin\javadoc.exe when you are done (depending on the JDK version
you installed).
Click the Finish button, confirm you destination directory, and after some crunching, your
program is documented in JavaDoc style. Easy, eh? Go take a look at it. It'll be in your
workspace directory under the doc subdirectory. To view it, click on the TutorialTwo.html file
that it generated. Note that this is a different TutorialTwo.html than the one you built to display
the applet in a webpage.

And with that, you have successfully completed this tutorial! You should have enough
knowledge now to modify this applet, and study how it works so you can go off and write your
own! Have fun!

Java Basic Operators



Advertisements

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Show Examples
Operator Description Example
+
Addition - Adds values on either side of the
operator
A + B will give 30
-
Subtraction - Subtracts right hand operand
from left hand operand
A - B will give -10
*
Multiplication - Multiplies values on either
side of the operator
A * B will give 200
/
Division - Divides left hand operand by right
hand operand
B / A will give 2
%
Modulus - Divides left hand operand by right
hand operand and returns remainder
B % A will give 0
++
Increment - Increase the value of operand by
1
B++ gives 21
--
Decrement - Decrease the value of operand
by 1
B-- gives 19
The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
Operator Description Example
==
Checks if the value of two operands are equal
or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal
or not, if values are not equal then condition
becomes true.
(A != B) is true.
>
Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater
than or equal to the value of right operand, if
yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less
than or equal to the value of right operand, if
yes then condition becomes true.
(A <= B) is true.
The Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Show Examples
Operator Description Example
&
Binary AND Operator copies a bit to the
result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
|
Binary OR Operator copies a bit if it exists in
eather operand.
(A | B) will give 61 which is 0011 1101
^
Binary XOR Operator copies the bit if it is set
in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
~
Binary Ones Complement Operator is unary
and has the efect of 'flipping' bits.
(~A ) will give -60 which is 1100 0011
<<
Binary Left Shift Operator. The left operands
value is moved left by the number of bits
specified by the right operand.
A << 2 will give 240 which is 1111 0000
>>
Binary Right Shift Operator. The left
operands value is moved right by the number
of bits specified by the right operand.
A >> 2 will give 15 which is 1111
>>>
Shift right zero fill operator. The left
operands value is moved right by the number
of bits specified by the right operand and
shifted values are filled up with zeros.
A >>>2 will give 15 which is 0000 1111
The Logical Operators:
The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Show Examples
Operator Description Example
&&
Called Logical AND operator. If both the
operands are non zero then then condition
becomes true.
(A && B) is false.
||
Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to reverses
the logical state of its operand. If a condition
is true then Logical NOT operator will make
false.
!(A && B) is true.
The Assignment Operators:
There are following assignment operators supported by Java language:
Show Examples
Operator Description Example
=
Simple assignment operator, Assigns
values from right side operands to left
side operand
C = A + B will assigne value of A + B into C
+=
Add AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It
C -= A is equivalent to C = C - A
subtracts right operand from the left
operand and assign the result to left
operand
*=
Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It
takes modulus using two operands and
assign the result to left operand
C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment
operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment
operator
C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate boolean expressions. The goal of the operator is to decide which
value should be assigned to the variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This would produce following result:
Value of b is : 30
Value of b is : 20
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type(class type or interface type). instanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side then the result will be true. Following is the example:
String name = = 'James';
boolean result = name instanceOf String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:
class Vehicle {}

public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
This would produce following result:
true
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right




Example:
import java.util.*;

public class EvenOddFunction {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
System.out.println("Input any number to check even or odd:");
number = input.nextInt();
evenMethod( number);
oddMethod(number);
}

public static void evenMethod(int n) {
if (n % 2 == 0){
System.out.println("Your number " + n + " is even");
}

}

public static void oddMethod(int n) {
if (n % 2 != 0) {
System.out.println("Your number " + n + " is odd");
}
}
}
Description : Number which is divisible by 2 is called even numbers and which is not divisible
by 2 is called odd numbers. Here we have two separate functions for checking either number is
even or odd. We are passing number as argument in methods.


Calculate sum of even and odd numbers in Java
Posted on: November 10, 2009 at 12:00 AM
In this Java Tutorial session, you will learn how to read the file that contains even and odd numbers
and calculate their sum separately.
Calculate sum of even and odd numbers
In this section, you will learn how to read the file that contains even and odd numbers and
calculate their sum separately. To do this, first of all, we have found all the even and odd
numbers from 1 to 100.Then we have created a file and add even and odd numbered integers
separated by a comma to it. After that we have used StreamTokenizer class to parse numbers
from the file and then calculate their sum.
Here is the code:
import java.io.*;

class AddEvenAndOdd {
public static void main(String[] args) throws Exception {
String evenNo = "";
String oddNo = "";
for (int i = 1; i < 100; i++) {
if (i % 2 == 0) {
evenNo += i + ",";
} else {
oddNo += i + ",";
}
}
File myFile = new File("numbers.txt");
FileWriter outStream = new FileWriter(myFile, true);
BufferedWriter out = new BufferedWriter(outStream);
out.write(evenNo);
out.write("\n");
out.close();
Reader r = new BufferedReader(new FileReader(myFile));
StreamTokenizer st = new StreamTokenizer(r);
st.parseNumbers();
int sum1 = 0;
st.nextToken();
while (st.ttype != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_NUMBER)
sum1 += st.nval;
else
System.out.print("");
st.nextToken();
}
System.out.println("Sum of even numbers is: " + sum1);
FileWriter outStream1 = new FileWriter(myFile, true);
BufferedWriter out1 = new BufferedWriter(outStream1);
out1.write(oddNo);
out1.close();

Reader reader = new BufferedReader(new FileReader(myFile));
StreamTokenizer stt = new StreamTokenizer(reader);
int sum = 0;
stt.parseNumbers();
stt.nextToken();
while (stt.ttype != StreamTokenizer.TT_EOF) {
if (stt.ttype == StreamTokenizer.TT_NUMBER)
sum += stt.nval;
else
System.out.print("");
stt.nextToken();
}
int sum2 = sum - sum1;
System.out.println("Sum of odd numbers is: " + sum2);
}
}
Output
Sum of even numbers is: 2450
Sum of odd numbers is: 2500




How to check given number is even or odd?
View Answers


May 23, 2012 at 5:51 PM


Simple if it is devided by 2 it is even and if not if is Odd


May 23, 2012 at 5:53 PM


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class EvenNumber{

public static void main(String args[]) throws IOException {

Sys tem.out.println("Enter the number");
int num= 0;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String data = br.readLine();

num = Integer.parseInt(data);
if((num %2)==0){
System.out.println("Number is Even");

} else{

System.out.println("Number is Odd");

}
}
}
Description: num is variable which hold the inputted number. BufferReader is used for inputting
number. Even numbers are those numbers, which are divisible by 2, and odd numbers are not
divisible by 2. if((num %2)==0) is checking the condition of num divisibility. If divisible then it
will print even number else odd number.


May 25, 2012 at 12:37 AM


/* Even Odd Number Example This Java Even Odd Number Example shows how to check if the
given number is even or odd. */
public class FindEvenOrOddNumber {
public static void main(String[] args) {

//create an array of 10 numbers
int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};

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

/*
* use modulus operator to check if the number is even or
odd.
* If we divide any number by 2 and reminder is 0 then
the number is
* even, otherwise it is odd.
*/

if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even
number.");
else
System.out.println(numbers[i] + " is odd
number.");

}

}
}
/* Output of the program would be
1 is odd number.
2 is even number.
3 is odd number.
4 is even number.
5 is odd number.
6 is even number.
7 is odd number.
8 is even number.
9 is odd number.
10 is even number


How to Check Perfect Number in Java
Program
A perfect number is a positive integer where the sum of all its positive divisors, except itself, is
equal to the number itself. For example 6 is a perfect number as 1,2 and3 are its divisors and the
sum of divisors=1+2+3=6. Here we have created a program that will take the number from the
user and reports whether it is perfect or not.
Here is the code:
import java.util.*;

public class PerfectNumber {
public static void main(String[] args) {
System.out.println("Enter any number");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int perfectNo = 0;
int i;
System.out.println("Factors are:");
for (i = 1; i < num; i++) {
if (num % i == 0) {
perfectNo += i;
System.out.println(i);
}
}
if (perfectNo == num) {
System.out.println("number is a perfect number");
} else {
System.out.println("number is not a perfect number");
}
}
}
Output:
Enter any number
28
Factors are:
1
2
7
14
number is a perfect number

import java.util.*;
class Assignment
{
String name;
int totalMarks;

Assignment(String name, int totalMarks){
this.name=name;
this.totalMarks=totalMarks;
}
public String getName(){
return name;
}

public int getTotalMarks(){
return totalMarks;
}
public static void main(String[] args)
{
ArrayList<Assignment> list=new ArrayList<Assignment>();
String names[]=new String[4];
int marks[]=new int[4];
Scanner input=new Scanner(System.in);
for(int i=0;i<marks.length;i++){
System.out.print("Enter Name:");
String n=input.next();
System.out.print("Enter marks in test1:");
int t1=input.nextInt();
System.out.print("Enter marks in test2:");
int t2=input.nextInt();
int m=t1+t2;
names[i]=n;
marks[i]=m;
list.add(new Assignment(names[i],marks[i]));
}
int lowest = marks[0];
int highest = marks[0];

for(int i=1; i< marks.length; i++)
{
if(marks[i] > highest)
highest = marks[i];
else if (marks[i] < lowest)
lowest = marks[i];
}
for(Assignment a: list){
if(a.getTotalMarks()==highest){
System.out.println(a.getName() + " get the highest marks");
}
if(a.getTotalMarks()==lowest){
System.out.println(a.getName() + " get the lowest marks");
}
}


}
}



import java.util.*;
class Assignment
{
String name;
int totalMarks;

Assignment(String name, int totalMarks){
this.name=name;
this.totalMarks=totalMarks;
}
public String getName(){
return name;
}

public int getTotalMarks(){
return totalMarks;
}
public static void main(String[] args)
{
ArrayList<Assignment> list=new ArrayList<Assignment>();
String names[]=new String[4];
int marks[]=new int[4];
Scanner input=new Scanner(System.in);
for(int i=0;i<marks.length;i++){
System.out.print("Enter Name:");
String n=input.next();
System.out.print("Enter marks in test1:");
int t1=input.nextInt();
System.out.print("Enter marks in test2:");
int t2=input.nextInt();
int m=t1+t2;
names[i]=n;
marks[i]=m;
list.add(new Assignment(names[i],marks[i]));
}
int lowest = marks[0];
int highest = marks[0];

for(int i=1; i< marks.length; i++)
{
if(marks[i] > highest)
highest = marks[i];
else if (marks[i] < lowest)
lowest = marks[i];
}
for(Assignment a: list){
if(a.getTotalMarks()==highest){
System.out.println(a.getName() + " get the highest marks");
}
if(a.getTotalMarks()==lowest){
System.out.println(a.getName() + " get the lowest marks");
}
}


}
}



yet another insignificant programming notes... | HOME
TABLE OF CONTENTS (HIDE)
1. Exercises on Flow Controls
1.1 Exercises on Conditional (Decision)
1.2 Exercises on Loop (Iteration)
1.3 Exercises on Nested-Loop
2. Exercises on Keyboard and File Input
3. Exercises on User Input and String Operations
4. Exercises on Array
5. Exercises on Command-line Arguments
6. Exercises on Method
7. More (Difficult) Exercises
8. Exercises on Number Theory
Java Programming Tutorial
Exercises on Java Basics
1. Exercises on Flow Controls
1.1 Exercises on Conditional (Decision)
Exercise CheckPassFail (if-else): Write a program called CheckPassFail which prints "PASS" if
the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise.
Hints:
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
int mark = 49; // set the value of mark here!
System.out.println("The mark is " + mark);

if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}

Exercise CheckOddEven (if-else): Write a program called CheckOddEven which prints "Odd
Number" if the int variable number is odd, or Even Number otherwise.
Hints: n is an even number if (n % 2) is 0.
public class CheckOddEven { // saved as "CheckOddEven.java"
public static void main(String[] args) {
int number = 49; // set the value of number here!
System.out.println("The number is " + number);
if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}

Exercise PrintNumberInWord (nested-if, switch-case): Write a program called
PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable
"number" is 1, 2,... , 9, or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case"
statement.
Hints:
public class PrintNumberInWord { // saved as "PrintNumberInWord.java"
public static void main(String[] args) {
int number = 5;

// Using nested-if
if (number == 1) {
System.out.println("ONE");
} else if (......) {
......
} else if (......) {
......
......
} else {
......
}

// Using switch-case
switch(number) {
case 1: System.out.println("ONE"); break;
case 2: ......
......
......
default: System.out.println("OTHER");
}
}
}
Similarly, write a program called PrintDayInWord, which prints Sunday, Monday, ...
Saturday if the int variable "day" is 0, 1, ..., 6, respectively. Otherwise, it shall print Not a
valid day.
1.2 Exercises on Loop (Iteration)
Exercise SumAndAverage (Loop): Write a program called SumAndAverage to produce the sum
of 1, 2, 3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output
shall look like:
The sum is 5050
The average is 50.5
Hints:
public class SumAndAverage { // saved as "SumAndAverage.java"
public static void main (String[] args) {
int sum = 0; // store the accumulated sum, init to 0
double average; // average in double
int lowerbound = 1; // the lower bound to sum
int upperbound = 100; // the upper bound to sum

for (int number = lowerbound; number <= upperbound; number++) { // for
loop
sum += number; // same as "sum = sum + number"
}
// Compute average in double. Beware that int/int produces int.
......
// Print sum and average.
......
}
}
TRY:
1. Modify the program to use a "while-do" loop instead of "for" loop.
2. int number = lowerbound;
3. int sum = 0;
4. while (number <= upperbound) {
5. sum += number;
6. number++;
}
7. Modify the program to use a "do-while" loop.
8. int number = lowerbound;
9. int sum = 0;
10. do {
11. sum += number;
12. number++;
} while (number <= upperbound);
13. What is the difference between "for" and "while-do" loops? What is the difference between
"while-do" and "do-while" loops?
14. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int
variable called count to count the numbers in the specified range.
15. int count = 0; // count the number within the range, init to 0
16. for (...; ...; ...) {
17. ......
18. count++;
}
19. Modify the program to sum only the odd numbers from 1 to 100, and compute the average.
(Hint: n is an odd number if n % 2 is not 0.)
20. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the
average.
21. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 +
2*2 + 3*3 + ... + 100*100.

Exercise Product1ToN (Loop): Write a program called Product1ToN to compute the product of
integers 1 to 10 (i.e., 123...10). Try computing the product from 1 to 11, 1 to 12, 1 to 13
and 1 to 14. Write down the product obtained and explain the results.
Hints: Declares an int variable called product (to accumulate the product) and initialize to 1.

Exercise HarmonicSum (Loop): Write a program called HarmonicSum to compute the sum of a
harmonic series, as shown below, where n=50000. The program shall compute the sum from left-
to-right as well as from the right-to-left. Obtain the difference between these two sums and
explain the difference. Which sum is more accurate?

Hints:
public class HarmonicSum { // saved as "HarmonicSum.java"
public static void main (String[] args) {
int maxDenominator = 50000;
double sumL2R = 0.0; // sum from left-to-right
double sumR2L = 0.0; // sum from right-to-left

// for-loop for summing from left-to-right
for (int denominator = 1; denominator <= maxDenominator; denominator++)
{
......
// Beware that int/int gives int.
}
// for-loop for summing from right-to-left
......
// Find the difference and display
......
}
}

Exercise ComputePI (Loop & Condition): Write a program called ComputePI to compute the
value of , using the following series expansion. You have to decide on the termination criterion
used in the computation (such as the number of terms used or the magnitude of an additional
term). Is this series suitable for computing ?

JDK maintains the value of in a double constant called Math.PI. Compare the values obtained
and the Math.PI, in percents of Math.PI.
Hint: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3.
double sum = 0;
int maxDenom = 10000000;
for (int denom = 1; ..... ; denom = denom + 2) {
if (denom % 4 == 1) {
sum += ......;
} else if (denom % 4 == 3) {
sum -= ......;
} else {
System.out.println("The computer has gone crazy?!");
}
}

Exercise CozaLozaWoza (Loop & Condition): Write a program called CozaLozaWoza which
prints the numbers 1 to 110, 11 numbers per line. The program shall print "Coza" in place of the
numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7,
"CozaLoza" for multiples of 3 and 5, and so on. The output shall look like:
1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
......
Hints:
public class CozaLozaWoza { // saved as "CozaLozaWoza.java"
public static void main(String[] args) {
int lowerbound = 1;
int upperbound = 110;
for (int number = lowerbound; number <= upperbound; number++) {
// Print "Coza" if number is divisible by 3
if (......) {
System.out.print("Coza");
}
// Print "Loza" if number is divisible by 5
if (......) {
System.out.print(.....);
}
// Print "Woza" if number is divisible by 7
......
// Print the number if it is not divisible by 3, 5 and 7
if (......) {
......
}
// Print a space
......
// Print a newline if number is divisible by 11
if (......) {
System.out.println();
}
}
}
}
TRY: Modify the program to use nested-if (if ... else if ... else if ... else) instead.

Exercise Fibonacci (Loop): Write a program called Fibonacci to display the first 20 Fibonacci
numbers F(n), where F(n)=F(n1)+F(n2) and F(1)=F(2)=1. Also compute their average. The
output shall look like:
The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
The average is 885.5
Hints:
public class Fibonacci {
public static void main (String args[]) {
int n = 3; // the index n for F(n), starting from n=3
int fn; // F(n) to be computed
int fnMinus1 = 1; // F(n-1), init to F(2)
int fnMinus2 = 1; // F(n-2), init to F(1)
int nMax = 20; // maximum n, inclusive
int sum = fnMinus1 + fnMinus2;
double average;

System.out.println("The first " + nMax + " Fibonacci numbers are:");
......

while (n <= nMax) {
// Compute F(n), print it and add to sum
......
// Adjust the index n and shift the numbers
......
}

// Compute and display the average (=sum/nMax)
......
}
}
Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a
number is formed by adding the three previous numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3),
T(1)=T(2)=1, and T(3)=2. Write a program called Tribonacci to produce the first twenty
Tribonacci numbers.
1.3 Exercises on Nested-Loop
Exercise SquareBoard (nested-loop): Write a program called SquareBoard that displays the
following nn (n=5) pattern using two nested for-loops.
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
Your program should use only two output statements, one EACH of the followings:
System.out.print("# "); // print # and a space, without newline
System.out.println(); // print a newline
Hints:
public class SquareBoard { // saved as "SquareBoard.java"
public static void main (String[] args) {
int size = 5; // size of the board
for (int row = 1; ......; ......) {
for (int col = 1; ......; ......) {
......
}
......
}
}
}

Exercise CheckerBoard (nested-loop): Write a program called CheckerBoard that displays the
following nn (n=7) checkerboard pattern using two nested for-loops.
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
# # # # # # #
Your program should use only three output statements, one EACH of the followings:
System.out.print("# "); // print # and a space, without newline
System.out.print(" "); // print a space, without newline
System.out.println(); // print a newline
Hints:
public class CheckerBoard { // saved as "CheckerBoard.java"
public static void main (String[] args) {
int size = 7; // size of the board

for (int row = 1; ......; ......) {
// Use modulus 2 to find alternate lines
if ((row % 2) == 0) { // row 2, 4, 6, 8
......
}
for (int col = 1; ......; ......) {
......
}
......
}
}
}

Exercise TimeTable (nested-loop): Write a program called TimeTable to produce the
multiplication table of 1 to 9 as shown using two nested for-loops:
* | 1 2 3 4 5 6 7 8 9
-------------------------------
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81
Modify the program to print the multiplication table of 1 to 12.
2. Exercises on Keyboard and File Input
Exercise KeyboardScanner (Keyboard Input): Write a program called KeyboardScanner to
prompt user for an int, a double, and a String. The output shall look like (the inputs are shown
in bold):
Enter an integer: 12
Enter a floating point number: 33.44
Enter your name: Peter
Hi! Peter, the sum of 12 and 33.44 is 45.44
Hints:
import java.util.Scanner; // needed to use Scanner for input
public class KeyboardScanner {
public static void main(String[] args) {
int num1;
double num2;
String name;
double sum;

// Setup a Scanner called in to scan the keyboard (System.in)
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
num1 = in.nextInt(); // use nextInt() to read int
System.out.print("Enter a floating point number: ");
num2 = in.nextDouble(); // use nextDouble() to read double
System.out.print("Enter your name: ");
name = in.next(); // use next() to read String

// Display
......
}
}

Exercise FileScanner (File Input): Write a program called FileScanner to read an int, a
double, and a String form a text file called "in.txt", and produce the following output:
The integer read is 12
The floating point number read is 33.44
The String read is "Peter"
Hi! Peter, the sum of 12 and 33.44 is 45.44
You need to create a text file called "in.txt" (in Eclipse, right-click on the "project" "New"
"File") with the following contents:
12
33.44
Peter
import java.util.Scanner; // Needed to use Scanner for input
import java.io.File; // Needed to use File
import java.io.FileNotFoundException; // Needed for file operation

public class FileScanner {
public static void main(String[] args)
throws FileNotFoundException { // Needed for file operation
int num1;
double num2;
String name;
double sum;

// Setup a Scanner to read from a text file
Scanner in = new Scanner(new File("in.txt"));
num1 = in.nextInt(); // use nextInt() to read int
num2 = in.nextDouble(); // use nextDouble() to read double
name = in.next(); // use next() to read String

// Display
......
}
}

Exercise CircleComputation (User Input): Write a program called CircleComputation, which
prompts user for a radius (of double) and compute the area and perimeter of a circle. The
output shall look like:
Enter the radius: 1.2
The area is 4.5239
The perimeter is 7.5398223686155035
Hints: is kept in a constant called Math.PI.
3. Exercises on User Input and String Operations
Exercise ReverseString: Write a program called ReverseString, which prompts user for a
String, and prints the reverse of the String. The output shall look like:
Enter a String: abcdef
The reverse of String "abcdef" is "fedcba".
Hints:
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
String inStr; // input String
int inStrLen; // length of the input String

Scanner in = new Scanner(System.in);
System.out.print("Enter a String: ");
inStr = in.next(); // use next() to read String
inStrLen = inStr.length();

// Use inStr.charAt(index) to extract character at 'index' from inStr
......
}
}
For a String called inStr, you can use inStr.length() to get the length of the String; and
inStr.charAt(index) to retrieve the char at the index position, where index begins with 0.

Exercise PhoneKeyPad: On your phone keypad, the alphabets are mapped to digits as follows:
ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9).
Write a program called PhoneKeyPad, which prompts user for a String (case insensitive), and
converts to a sequence of digits. Use a nested-if (or switch-case) in this exercise. Modify your
program to use an array for table look-up later.
Hints: You can use in.next().toLowerCase() to read a string and convert it to lowercase to
reduce your cases.

Exercise TestPalindromicWord: A word that reads the same backward as forward is called a
palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a
program called TestPalindromicWord, that prompts user for a word and prints ""xxx" is|is
not a palindrome".
Hints: Read in a word and convert to lowercase via in.next().toLowercase().
A phrase that reads the same backward as forward is also called a palindrome, e.g., "Madam, I'm
Adam", "A man, a plan, a canal - Panama!" (ignoring punctuation and capitalization). Modify
your program (called TestPalindromicPhrase) to test palindromic phrase.
Hints: Read in the lowercase phrase via in.nextLine().toLowercase(). Maintain two indexes,
forwardIndex and backwardIndex, used to scan the phrase forward and backward.

Exercise Bin2Dec: Write a program called Bin2Dec to convert an input binary string into its
equivalent decimal number. Your output shall look like:
Enter a Binary string: 1011
The equivalent decimal number for binary "1011" is 11

Enter a Binary string: 1234
Error: Invalid Binary String "1234"
Hints: For a n-bit binary number b
n-1
b
n-2
...b
1
b
0
, b
i
{0,1}, the equivalent decimal number is
b
n-1
2
n-1
+b
n-2
2
n-2
+ ...+b
1
2
1
+b
0
2
0
.
import java.util.Scanner;
public class Bin2Dec {
public static void main(String[] args) {
String binStr; // input binary string
int binStrLen; // length of the input string
int dec = 0; // equivalent decimal number
char binChar; // each individual char in the binary string

Scanner in = new Scanner(System.in);

// Read input binary string
......

// Convert binary string into Decimal
......
}
}
binStr : 1 0 1 1 1 0 0 1
charAt(idx) : 0 1 2 3 4 5 6 7
Math.pow(2, order) : 7 6 5 4 3 2 1 0

binStr.length() = 8
idx + order = binStr.length() - 1
You can use JDK method Math.pow(x, y) to compute the x raises to the power of y. This
method takes two doubles as argument and returns a double. You may have to cast the result
back to int.
To convert a char (of digit '0' to '9') to int (0 to 9), simply subtract by char '0', e.g., '5'-
'0' gives int 5.

Exercise Hex2Dec: Write a program called Hex2Dec to convert an input hexadecimal string into
its equivalent decimal number. Your output shall look like:
Enter a Hexadecimal string: 1a
The equivalent decimal number for hexadecimal "1a" is 26

Enter a Hexadecimal string: 1y3
Error: Invalid Hexadecimal String "1y3"
Hints:
For a n-digit hexadecimal number h
n-1
h
n-2
...h
1
h
0
, h
i
{0,,9,A,,F}, the equivalent decimal
number is h
n-1
16
n-1
+h
n-2
16
n-2
+ ...+h
1
16
1
+h
0
16
0
.
You do not need a big nested-if statement of 16 cases (or 22 considering the upper and lower
letters). Extract the individual character from the hexadecimal string, says c. If char c is between
'0' to '9', you can get the integer offset via c-'0'. If c is between 'a' to 'f' or 'A' to 'F', the
integer offset is c-'a'+10 or c-'A'+10.
String hexStr;
char hexChar;
......
hexChar = hexStr.charAt(i);
......
if (hexChar >= '0' && hexChar <= '9') {
... (hexChar-'0') ...
...
} else if (hexChar >= 'a' && hexChar <= 'f') { // lowercase
... (hexChar-'a'+10) ...
...
} else if (hexChar >= 'A' && hexChar <= 'F') { // uppercase
... (hexChar-'A'+10) ...
...
} else {
System.out.println("Error: Invalid hexadecimal string");
System.exit(1); // quit the program
}
4. Exercises on Array
Exercise GradesAverage (Array): Write a program called GradesAverage, which prompts user
for the number of students, reads it from the keyboard, and saves it in an int variable called
numStudents. It then prompts user for the grades of each of the students and saves them in an
int array called grades. Your program shall check that the grade is between 0 and 100. A
sample session is as follow:
Enter the number of students: 3
Enter the grade for student 1: 55
Enter the grade for student 2: 108
Invalid grade, try again...
Enter the grade for student 2: 56
Enter the grade for student 3: 57
The average is 56.0

Exercise Hex2Bin (Array and Table Lookup): Write a program called Hex2Bin to convert a
hexadecimal string into its equivalent binary string. The output shall look like:
Enter a Hexadecimal string: 1abc
The equivalent binary for hexadecimal "1abc" is 0001 1010 1011 1100
Hints: Use an array of 16 binary Strings corresponding to hexadecimal number '0' to 'F', as
follows:
String[] hexBits = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"}
5. Exercises on Command-line Arguments
Exercise Arithmetic (Command-line arguments): Write a program called Arithmetic that takes
three command-line arguments: two integers followed by an arithmetic operator (+, -, * or /).
The program shall perform the corresponding operation on the two integers and print the result.
For example:
> java Arithmetic 3 2 +
3+2=5

> java Arithmetic 3 2 -
3-2=1

> java Arithmetic 3 2 /
3/2=1
Hints:
The method main(String[] args) takes an argument: "an array of String", which is often
(but not necessary) named args. This parameter captures the command-line arguments supplied
by the user when the program is invoked. For example, if a user invokes:
> java Arithmetic 12345 4567 +
The three command-line arguments "12345", "4567" and "+" will be captured in a String array
{"12345", "4567", "+"} and passed into the main() method as the argument args. That is,
args is {"12345", "4567", "+"}; // args is a String array
args.length is 3; // length of the array
args[0] is "12345"; // 1st element of the String array
args[1] is "4567"; // 2nd element of the String array
args[2] is "+"; // 3rd element of the String array
args[0].length() is 5; // length of 1st String element
args[1].length() is 4; // length of the 2nd String element
args[2].length() is 1; // length of the 3rd String element
public class Arithmetic {
public static void main (String[] args) {
int operand1, operand2;
char theOperator;

// Check if there are 3 command-line arguments in the
// String array args[] by using length variable of array.
if (args.length != 3) {
System.err.println("Usage: java Arithmetic int1 int2 op");
return;
}

// Convert the 3 Strings args[0], args[1], args[2] to int and char.
// Use the Integer.parseInt(aStr) to convert a String to an int.
operand1 = Integer.parseInt(args[0]);
operand2 = ......

// Get the operator, assumed to be the first character of
// the 3rd string. Use method charAt() of String.
theOperator = args[2].charAt(0);
System.out.print(args[0] + args[2] + args[1] + "=");

switch(theOperator) {
case ('-'): System.out.println(operand1 operand2); break;
case ('+'): ......
case ('*'): ......
case ('/'): ......
default:
System.err.println("Error: invalid operator!");
}
}
}
Notes:
To provide command-line arguments, use the "cmd" shell to run your program in the form
"java ClassName arg1 arg2 ....".
To provide command-line arguments in Eclipse, right click the source code "Run As" "Run
Configurations..." Select "Main" and choose the proper main class Select "Arguments"
Enter the command-line arguments, e.g., "3 2 +" in "Program Arguments".
To provide command-line arguments in Netbeans, right click the "Project" name "Set
Configuration" "Customize..." Select categories "Run" Enter the command-line
arguments, e.g., "3 2 +" in the "Arguments" box (but make sure you select the proper Main
class).
Question: Try "java Arithmetic 2 4 *" (in CMD shell and Eclipse/Netbeans) and explain the
result obtained. How to resolve this problem?
In Windows' CMD shell, * is known as a wildcard character, that expands to give the list of file
in the directory (called Shell Expansion). For example, "dir *.java" lists all the file with
extension of ".java". You could double-quote the * to prevent shell expansion. Eclipse has a
bug in handling this, even * is double-quoted. NetBeans??

Exercise SumDigits (Command-line arguments): Write a program called SumDigits to sum up
the individual digits of a positive integer, given in the command line. The output shall look like:
> java SumDigits 12345
The sum of digits = 1 + 2 + 3 + 4 + 5 = 15
6. Exercises on Method
Exercise GradesStatistics (Method): Write a program called GradesStatistics, which reads in
n grades (of int between 0 and 100, inclusive) and displays the average, minimum, maximum,
and standard deviation. Your program shall check for valid input. You should keep the grades in
an int[] and use a method for each of the computations. Your output shall look like:
Enter the number of students: 4
Enter the grade for student 1: 50
Enter the grade for student 2: 51
Enter the grade for student 3: 56
Enter the grade for student 4: 53
The average is 52.5
The minimum is 50
The maximum is 56
The standard deviation is 2.29128784747792
Hints: The formula for calculating standard deviation is:

public class GradesStatistics {
public static int[] grades; // Declare an int[], to be allocated later

// main() method
public static void main(String[] args) {
readGrades();
System.out.println("The average is " + average());
System.out.println("The minimum is " + min());
System.out.println("The maximum is " + max());
System.out.println("The standard deviation is " + stdDev());
}

// Prompt user for the number of students and allocate the "grades" array.
// Then, prompt user for grade, check for valid grade, and store in
"grades".
public static void readGrades() { ....... }

// Return the average value of int[] grades
public static double average() { ...... }

// Return the maximum value of int[] grades
public static int max() { ...... }

// Return the minimum value of int[] grades
public static int min() { ....... }

// Return the standard deviation of the int[] grades
public static double stdDev() { ....... }
}

Exercise GradesHistogram (Method): Write a program called GradesHistogram, which reads in
n grades (of int between 0 and 100, inclusive) from a text file called "grades.in" and displays
the histogram horizontally and vertically. The file has the following format:
numStduents:int
grade1:int grade2:int .... gradeN:int
For example:
15
49 50 51 59 0 5 9 10 15 19 50 55 89 99 100
The output shall consist of a horizontal histogram and a vertical histogram as follows:
0 - 9: ***
10 - 19: ***
20 - 29:
30 - 39:
40 - 49: *
50 - 59: *****
60 - 69:
70 - 79:
80 - 89: *
90 -100: **

*
*
* * *
* * * *
* * * * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
Hints:
public class GradesHistogram {
public static int[] grades;
// Declare an int array of grades, to be allocated later
public static int[] bins = new int[10];
// Declare and allocate an int array for histogram bins.
// 10 bins for 0-9, 10-19,...., 90-100

public static void main(String[] args) {
readGrades("grades.in");
computeHistogram();
printHistogramHorizontal();
printHistogramVertical();
}

// Read the grades from "filename", store in "grades" array.
// Assume that the inputs are valid.
public static void readGrades(String filename) { ...... }

// Based on "grades" array, populate the "bins" array.
public static void computeHistogram() { ....... }

// Print histogram based on the "bins" array.
public static void printHistogramHorizontal() { ...... }

// Print histogram based on the "bins" array.
public static void printHistogramVertical() { ...... }
}

Exercise ReverseArrayTest (Method): Write a method called reverseArray() with the
following signature:
public static void reverseArray(int[] intArray)
The method accepts an int array, and reverses its orders. For example, if the input array is {12,
56, 34, 79, 26}, the reversal is {26, 79, 34, 56, 12}. You MUST NOT use another array
in your method (but you need a temporary variable to do the swap). Also write a test class called
ReverseArrayTest to test this method.
Take note that the array passed into the method can be modified by the method (this is called
"pass by reference"). On the other hand, primitives passed into a method cannot be modified.
This is because a clone is created and passed into the method instead of the original copy (this is
called "pass by value").
7. More (Difficult) Exercises
Exercise (JDK Source Code): Extract the source code of the class Math from the JDK source
code ("$JAVA_HOME" "src.zip" "Math.java" under folder "java.lang"). Study how
constants such as E and PI are defined. Also study how methods such as abs(), max(), min(),
toDegree(), etc, are written.

Exercise Matrix: Similar to Math class, write a Matrix library that supports matrix operations
(such as addition, subtraction, multiplication) via 2D arrays. The operations shall support both
doubles and ints. Also write a test class to exercise all the operations programmed.
Hints:
public class Matrix {
public static void printMatrix(int[][] m) { ...... }
public static void printMatrix(double[][] m) { ...... }
public static boolean haveSameDimension(int[][] m1, int[][] m2) { ...... }
public static boolean haveSameDimension(double[][] m1, double[][] m2) {
...... }
public static int[][] add(int[][] m1, int[][] m2) { ...... }
public static double[][] add(double[][] m1, double[][] m2) { ...... }
......
}

Exercise PrintAnimalPattern (Special Characters and Escape Sequences): Write a program called
PrintAnimalPattern, which uses println() to produce this pattern:
'__'
()
/========\/
/ || %% ||
* ||----||

"" ""
Hints:
Use escape sequence \uhhhh where hhhh are four hex digits to display Unicode characters
such as and . is 165 (00A5H) and is 169 (00A9H) in both ISO-8859-1 (Latin-1) and
Unicode character sets.
Double-quote (") and black-slash (\) require escape sign inside a String. Single quote (') does
not require escape sign.
TRY: Print the same pattern using printf(). (Hints: Need to use %% to print a % in printf()
because % is the suffix for format specifier.)

Exercise PrintPatterns: Write a method to print each of the followings patterns using nested loops
in a class called PrintPatterns. The signatures of the methods are:
public static void printPatternX(int size) // 'X' from 'A' to ..., size is a
positive integer.
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
# # # # # # # # # # # # # # # # #
#
(a) (b) (c) (d)

Hints: On the diagonal, row = col. On the opposite diagonal, row + col =
size + 1.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# # # # # # # #
# #
# # # # # # # # #
#
# # # # # # #
#
# # # # # # # # #
#
# # # # # # # #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
(e) (f) (g) (h) (i)

# # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # #
(j) (k) # # # # # # # # #
# # # # # # #
# # # # #
# # #
#
(l)

1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2
1
1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1
1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1
1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1
1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1
1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1
1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1
1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(m) (n) (o) (p)

1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 2 1 1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1
1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1 1 2 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1
(q) (r)

1 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1
1 2 3 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 5 4 3 2 1 1 2 3 4 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 3 2 1
1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 1
(s) (t)

1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 0 1 0 9 8 7 6
7 8 9 0 1 2 3 2 1 0 9 8 7
8 9 0 1 2 3 4 5 4 3 2 1 0 9 8
(u)

Exercise PrintTriangles: Write a method to print each of the following patterns using nested-
loops in a class called PrintTriangles. The signatures of the methods are:
public static void printXxxTriangle(int numRows) // Xxx is the pattern's
name
Write the main() which prompts the user for the numRows and prints all the patterns.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
(a) PowerOf2Triangle

1 1
1 1 1 1
1 2 1 1 2 1
1 3 3 1 1 3 3 1
1 4 6 4 1 1 4 6 4 1
1 5 10 10 5 1 1 5 10 10 5 1
1 6 15 20 15 6 1 1 6 15 20 15 6 1
(b) PascalTriangle1 (c) PascalTriangle2

Exercise TrigonometricSeries: Write a method to compute sin(x) and cos(x) using the
following series expansion, in a class called TrigonometricSeries. The headers of the methods
are:
public static double sin(double x, int numTerms) // x in radians
public static double cos(double x, int numTerms)

Compare the values computed using the series with the JDK methods Math.sin(), Math.cos()
at x=0, /6, /4, /3, /2 using various numbers of terms.
Hints: Avoid generating large numerator and denominator (which may cause arithmetic
overflow, e.g., 13! is out of int range). Compute the terms as:


Exercise SpecialSeries: Write a method to compute the sum of the series in a class called
SpecialSeries. The signature of the method is:
public static double sumOfSeries(double x, int numTerms)


Exercise FibonacciInt (Overflow) : Write a program called FibonacciInt to list all the
Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of
[-2147483648, 2147483647]). The output shall look like:
F(0) = 1
F(1) = 1
F(2) = 2
...
F(45) = 1836311903
F(46) is out of the range of int
Hints: The maximum and minimum values of a 32-bit int are kept in constants
Integer.MAX_VALUE and Integer.MIN_VALUE, respectively. Try these statements:
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but
silently wraps the number around. Hence, you cannot use F(n-1) + F(n-2) >
Integer.MAX_VALUE to check for overflow. Instead, overflow occurs for F(n) if
(Integer.MAX_VALUE F(n-1)) < F(n-2) (i.e., no room for the next Fibonacci number).
Write a similar program for Tribonacci numbers.

Exercise FactorialInt (Overflow): Write a program called Factorial1to10, to compute the
factorial of n, for 1n10. Your output shall look like:
The factorial of 1 is 1
The factorial of 2 is 2
...
The factorial of 10 is 3628800
Modify your program (called FactorialInt), to list all the factorials, that can be expressed as
an int (i.e., 32-bit signed integer). Your output shall look like:
The factorial of 1 is 1
The factorial of 2 is 2
...
The factorial of 12 is 479001600
The factorial of 13 is out of range
Hints: Overflow occurs for Factorial(n+1) if (Integer.MAX_VALUE / Factorial(n)) <
(n+1).
Modify your program again (called FactorialLong) to list all the factorials that can be
expressed as a long (64-bit signed integer). The maximum value for long is kept in a constant
called Long.MAX_VALUE.

Exercise NumberConversion: Write a method call toRadix() which converts a positive integer
from one radix into another. The method has the following header:
public static String toRadix(String in, int inRadix, int outRadix) // The
input and output are treated as String.
Write a program called NumberConversion, which prompts the user for an input number, an
input radix, and an output radix, and display the converted number. The output shall look like:
Enter a number and radix: A1B2
Enter the input radix: 16
Enter the output radix: 2
"A1B2" in radix 16 is "1010000110110010" in radix 2.

Exercise NumberGuess: Write a program called NumberGuess to play the number guessing
game. The program shall generate a random number between 0 and 99. The player inputs his/her
guess, and the program shall response with "Try higher", "Try lower" or "You got it in n trials"
accordingly. For example:
> java NumberGuess
Key in your guess:
50
Try higher
70
Try lower
65
Try lower
"
You got it in 4 trials!
Hints: Use Math.random() to produce a random number in double between 0.0 and (less than)
1.0. To produce an int between 0 and 99, use:
int secretNumber = (int)(Math.random()*100);

Exercise WordGuess: Write a program called WordGuess to guess a word by trying to guess the
individual characters. The word to be guessed shall be provided using the command-line
argument. Your program shall look like:
> java WordGuess testing
Key in one character or your guess word: t
Trail 1: t__t___
Key in one character or your guess word: g
Trail 2: t__t__g
Key in one character or your guess word: e
Trail 3: te_t__g
Key in one character or your guess word: testing
Trail 4: Congratulation!
You got in 4 trials
Hints:
Set up a boolean array to indicate the positions of the word that have been guessed correctly.
Check the length of the input String to determine whether the player enters a single character
or a guessed word. If the player enters a single character, check it against the word to be
guessed, and update the boolean array that keeping the result so far.
Try retrieving the word to be guessed from a text file (or a dictionary) randomly.

Exercise DateUtil: Complete the following methods in a class called DateUtil:
boolean isLeapYear(int year): returns true if the given year is a leap year. A year is a
leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
boolean isValidDate(int year, int month, int day): returns true if the given
year, month and day constitute a given date. Assume that year is between 1 and 9999, month
is between 1 (Jan) to 12 (Dec) and day shall be between 1 and 28|29|30|31 depending on the
month and whether it is a leap year.
int getDayOfWeek(int year, int month, int day): returns the day of the week,
where 0 for SUN, 1 for MON, ..., 6 for SAT, for the given date. Assume that the date is valid.
String toString(int year, int month, int day): prints the given date in the format
"xxxday d mmm yyyy", e.g., "Tuesday 14 Feb 2012". Assume that the given date is valid.
To find the day of the week (Reference: Wiki "Determination of the day of the week"):
1. Based on the first two digit of the year, get the number from the following "century" table.
1700- 1800- 1900- 2000- 2100- 2200- 2300- 2400-
4 2 0 6 4 2 0 6
2. Take note that the entries 4, 2, 0, 6 repeat.
3. Add to the last two digit of the year.
4. Add to "the last two digit of the year divide by 4, truncate the fractional part".
5. Add to the number obtained from the following month table:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Non-Leap Year 0 3 3 6 1 4 6 2 5 0 3 5
Leap Year 6 2 same as above
6. Add to the day.
7. The sum modulus 7 gives the day of the week, where 0 for SUN, 1 for MON, ..., 6 for SAT.
For example: 2012, Feb, 17
(6 + 12 + 12/4 + 2 + 17) % 7 = 5 (Fri)
/* Utilities for Date Manipulation */
public class DateUtil {

// Month's name for printing
public static String strMonths[]
= {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

// Number of days in each month (for non-leap years)
public static int daysInMonths[]
= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Returns true if the given year is a leap year
public static boolean isLeapYear(int year) { ...... }

// Return true if the given year, month, day is a valid date
// year: 1-9999
// month: 1(Jan)-12(Dec)
// day: 1-28|29|30|31. The last day depends on year and month
public static boolean isValidDate(int year, int month, int day) { ...... }

// Return the day of the week, 0:Sun, 1:Mon, ..., 6:Sat
public static int getDayOfWeek(int year, int month, int day) { ...... }

// Return String "xxxday d mmm yyyy" (e.g., Wednesday 29 Feb 2012)
public static String printDate(int year, int month, int day) { ...... }

public static void main(String[] args) {
System.out.println(isLeapYear(1900)); // false
System.out.println(isLeapYear(2000)); // true
System.out.println(isLeapYear(2011)); // false
System.out.println(isLeapYear(2012)); // true

System.out.println(isValidDate(2012, 2, 29)); // true
System.out.println(isValidDate(2011, 2, 29)); // false
System.out.println(isValidDate(2099, 12, 31)); // true
System.out.println(isValidDate(2099, 12, 32)); // true

System.out.println(getDayOfWeek(1982, 4, 24)); // 6:Sat
System.out.println(getDayOfWeek(2000, 1, 1)); // 6:Sat
System.out.println(getDayOfWeek(2054, 6, 19)); // 5:Fri
System.out.println(getDayOfWeek(2012, 2, 17)); // 5:Fri

System.out.println(toString(2012, 2, 14)); // Tuesday 14 Feb 2012
}
}
You can compare the day obtained with the Java's Calendar class as follows:
// Construct a Calendar instance with the given year, month and day
Calendar cal = new GregorianCalendar(year, month - 1, day); // month is 0-
based
// Get the day of the week number: 1 (Sunday) to 7 (Saturday)
int dayNumber = cal.get(Calendar.DAY_OF_WEEK);
String[] calendarDays = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
// Print result
System.out.println("It is " + calendarDays[dayNumber - 1]);
The calendar we used today is known as Gregorian calendar, which came into effect in October
15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days
were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15,
1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the
"leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap
year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the
Gregorian calendar omits century years which are not divisible by 400. Furthermore, Julian
calendar considers the first day of the year as march 25th, instead of January 1st.
This above algorithm work for Gregorian dates only. It is difficult to modify the above algorithm
to handle pre-Gregorian dates. A better algorithm is to find the number of days from a known
date.
8. Exercises on Number Theory
Exercise (Perfect and Deficient Numbers): A positive integer is called a perfect number if the
sum of all its factors (excluding the number itself, i.e., proper divisor) is equal to its value. For
example, the number 6 is perfect because its proper divisors are 1, 2, and 3, and 6=1+2+3; but the
number 10 is not perfect because its proper divisors are 1, 2, and 5, and 101+2+5.
A positive integer is called a deficient number if the sum of all its proper divisors is less than its
value. For example, 10 is a deficient number because 1+2+5<10; while 12 is not because
1+2+3+4+6>12.
Write a method called isPerfect(int posInt) that takes a positive integer, and return true if
the number is perfect. Similarly, write a method called isDeficient(int posInt) to check for
deficient numbers.
Using the methods, write a program called PerfectNumberList that prompts user for an upper
bound (a positive integer), and lists all the perfect numbers less than or equal to this upper
bound. It shall also list all the numbers that are neither deficient nor perfect. The output shall
look like:
Enter the upper bound: 1000
These numbers are perfect:
6 28 496
[3 perfect numbers found (0.30%)]

These numbers are neither deficient nor perfect:
12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 ......
[246 numbers found (24.60%)]

Exercise (Primes): A positive integer is a prime if it is divisible by 1 and itself only. Write a
method called isPrime(int posInt) that takes a positive integer and returns true if the
number is a prime. Write a program called PrimeList that prompts the user for an upper bound
(a positive integer), and lists all the primes less than or equal to it. Also display the percentage of
prime (up to 2 decimal places). The output shall look like:
Please enter the upper bound: 10000
1
2
3
......
......
9967
9973
[1230 primes found (12.30%)]
Hints: To check if a number n is a prime, the simplest way is try dividing n by 2 to n.

Exercise (Prime Factors): Write a method isProductOfPrimeFactors(int posInt) that takes
a positive integer, and return true if the product of all its prime factors (excluding 1 and the
number itself) is equal to its value. For example, the method returns true for 30 (30=235) and
false for 20 (2025). You may need to use the isPrime() method in the previous exercise.
Write a program called PerfectPrimeFactorList that prompts user for an upper bound. The
program shall display all the numbers (less than or equal to the upper bound) that meets the
above criteria. The output shall look like:
Enter the upper bound: 100
These numbers are equal to the product of prime factors:
1 6 10 14 15 21 22 26 30 33 34 35 38 39 42 46 51 55 57 58 62 65 66 69 70 74
77 78 82 85 86 87 91 93 94 95
[36 numbers found (36.00%)]

Exercise (Greatest Common Divisor): One of the earlier known algorithms is the Euclid
algorithm to find the GCD of two integers (developed by the Greek Mathematician Euclid
around 300BC). By definition, GCD(a, b) is the greatest factor that divides both a and b.
Assume that a and b are positive integers, and ab, the Euclid algorithm is based on these two
properties:
GCD(a, 0) = a
GCD(a, b) = GCD(b, a mod b), where (a mod b) denotes the remainder of a
divides by b.
For example,
GCD(15, 5) = GCD(5, 0) = 5
GCD(99,88) = GCD(88,11) = GCD(11,0) = 11
GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) =
GCD(9,0) = 9
The pseudocode for the Euclid algorithm is as follows:
GCD(a, b) // assume that a b
while (b != 0) {
// Change the value of a and b: a b, b a mod b, and repeat until b is
0
temp b
b a mod b
a temp
}
// after the loop completes, i.e., b is 0, we have GCD(a, 0)
GCD is a
Write a method called gcd() with the following signature:
public static int gcd(int a, int b)
Your methods shall handle arbitrary values of a and b, and check for validity.
TRY: Write a recursive version called gcdRecursive() to find the GCD.
Latest version tested: JDK 1.7.3
Last modified: May, 2012
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan
(ehchua@ntu.edu.sg) | HOME


import java.util.*;
class Assignment
{
String name;
int totalMarks;

Assignment(String name, int totalMarks){
this.name=name;
this.totalMarks=totalMarks;
}
public String getName(){
return name;
}

public int getTotalMarks(){
return totalMarks;
}
public static void main(String[] args)
{
ArrayList<Assignment> list=new ArrayList<Assignment>();
String names[]=new String[4];
int marks[]=new int[4];
Scanner input=new Scanner(System.in);
for(int i=0;i<marks.length;i++){
System.out.print("Enter Name:");
String n=input.next();
System.out.print("Enter marks in test1:");
int t1=input.nextInt();
System.out.print("Enter marks in test2:");
int t2=input.nextInt();
int m=t1+t2;
names[i]=n;
marks[i]=m;
list.add(new Assignment(names[i],marks[i]));
}
int lowest = marks[0];
int highest = marks[0];

for(int i=1; i< marks.length; i++)
{
if(marks[i] > highest)
highest = marks[i];
else if (marks[i] < lowest)
lowest = marks[i];
}
for(Assignment a: list){
if(a.getTotalMarks()==highest){
System.out.println(a.getName() + " get the highest marks");
}
if(a.getTotalMarks()==lowest){
System.out.println(a.getName() + " get the lowest marks");
}
}


}
}

Вам также может понравиться