You are on page 1of 33

REVIEWING Java

The Best Resource For Beginners

Alex Maureau

Visit:
www.cstutoringcenter.com/problems
for some fun programming challenges in Java.

Copyright 2009 by Alex Maureau


ISBN: 978-0-557-04355-2
All rights reserved, including the right of reproduction,
in whole or any part.

Special Thanks To
Department of Computer Science, CUNY Queens
College
Without them I would not be where I am today.

Raymond Law & Cristobal Sepulveda


My buddies and mentors.

Thanks for keeping me sane!

Chanel Orkopoulos
The true love of my love.

You are my angel!

Preface
As many students embark on learning Java, some find it a challenge,
others find it easy and others impossible. Ive learned that there are many
students who are willing to just give up at the drop of a hat or even after
they fail miserably on the first exam (i.e. the JOptionPane exam).
During my own experiences, I realized that there are quite a few
students who do not want to come into my office and ask me questions. To
this day I still do not know why. Perhaps it is the stigmatism of the tutor or
aide; too nerdy or geeky for some or not important to others. I was once
the latter but I quickly snapped out of it once embarking on my computer
science career.
This packet and its material is written to give hope to those lost
students who have to take a programming class due to by their degree
requirements or they are anxious to learn a new subject. I hope you find
this information helpful and understanding so you have a pleasant
experience with Java programming. The material contained in this packet is
a summary of the major topics of Java.

Table of Contents
Material

CHAPTER 1
Java Introduction

Hello World
Console Input/Output
Compiling Programs
Command line arguments
Documentation and Javadoc
Terminating Programs

CHAPTER 2
Variables

Declaring variables
Instance variables
Static variables
Final variables
Type casting
o Implicit casting
o Explicit casting
Overflow

CHAPTER 3
Operators

Assignment
Arithmetic
Relational / Equality
Logical
Increase / Decrease
Bitwise
Compound Assignment
Examples

CHAPTER 4
Strings in Java

Overview
String Equalities

CHAPTER 5
Wrapper Classes & Parsing

Wrapper classes

11
12
13
13
14
15
16

17
18
19
19
20
21
21
22

24
25
25
26
27
27
28
29
29

33
34
36

39
40

CHAPTER 6
Input/Output Techniques

Scanners
JOptionPanes

CHAPTER 7
Decisions & Logic

If statements
Nested if statements
Empty decisions
Conditional Logic
While statements
Switch / Case statements
More examples

CHAPTER 8
Looping

For loop
Nested loops
Do / While
Break / Continue keywords
Empty Loops
Infinite Loops

CHAPTER 9
Java Methods

Method basics
Calling
Types
Parameters
Overloading

CHAPTER 10
Recursion

Tracing
Factorial function
Fibonacci function
Other recursive functions

CHAPTER 11
Arrays

One dimensional arrays


Two dimensional arrays
Syntax
Arrays & methods

43
44
46

49
50
52
52
53
54
55
57

60
61
62
66
68
69
70

72
73
73
74
74
79

82
83
85
86
88

89
90
95
98
99

Length method
Object arrays
More Examples

CHAPTER 12
StringTokenizers & Characters

StringTokenizer class
Character Wrapper class

Chapter 13
Working with Classes & Objects

Rectangle class
Fraction class

CHAPTER 14
Inheritance

Super keyword
This keyword
getClass() and getName() methods
Inheritance Examples

CHAPTER 15
File Input/Output

BufferedReader for input


BufferedWriter for output

CHAPTER 16
Exceptions

Types of Exceptions
Exception List
Try/Catch blocks
Defining Exceptions
Practical Example

CHAPTER 17
Abstract Classes & Methods

Abstract classes
Abstract methods

CHAPTER 18
Interfaces

Overview
Interface constants

101
101
102

105
106
109

112
113
116

125
126
126
126
127

134
135
137

139
140
140
141
144
145

148
149
152

155
156
158

CHAPTER 19
Some Sorting Techniques

Selection sort
Bubble sort
Count sort

160
162
164

CHAPTER 20
Linked Lists

166

Nodes
Defining a Node
Singly Linked Lists
o Constructor
o Insert at start
o Insert at end
o Remove the head
o Transverse the list
o Full Implementation

CHAPTER 21
Stacks

Arrays
o
o
o
o
o
o

Arrays
o
o
o
o
o
o

167
168
169
169
169
170
170
171

173

Constructor
size() and empty()
Adding (pushing) data
Removing (popping) data
Printing the stack
Full Implementation

CHAPTER 22
Queues

159

175
175
176
176
176
177

179

Constructor
Auxiliary methods
Add data (enqueue)
Remove data (dequeue)
Printing the data
Full Implementation

180
181
181
182
182
182

Practice Questions

Topic A
Logic Practice
Solutions

185
191

TOPIC B
Looping Practice

193

Solutions

199

TOPIC C
Methods Practice
Solutions

204
207

TOPIC D
Debugging & Output Practice
Solutions

213
230

TOPIC E
Recursion Practice
Solutions

238
249

TOPIC F
Classes & Objects Practice
Solutions

254
257

TOPIC G
Inheritance & Polymorphism Practice
Solutions

263
270

TOPIC H
Writing Programs Practice
Solutions

272
278

Appendices

Appendix A
ASCII Chart

291

Appendix B
Random Numbers

292

Appendix C
Math Library

300

Appendix D
Number Conversions

302

Appendix E
Programming Challenges

310

CHAPTER 1

Java Introduction

This chapter will cover a basic introduction to the Java language including
the standard Hello World program including a breakdown of its parts. It
also covers the breakdown of a class in Java.

Java is a high level programming language that is strictly object oriented. That
means there is nothing but objects and classes that make up the language. So
what parts are there to a class?

Constructor
A constructor will build the class. A class or object does not exist until you
construct it. All classes are instantiated with the word new.
Instance variables (see chapter 2)
There are data variables that are part of each instance of a class. These can be
integers, Strings, characters etc or any other Object.
Methods (see chapter 9)
These are the most essential part of a class since these do work on a variable,
Object etc This is similar to the C++ function.

Much more on the above will be seen as this book progresses.


All Java programs, AT THE BARE MINIMUM, will look like this:

public class Name{


public static void main(String args[]){
//code here for program
}
}

Where in the above, Name is the useful name of the object (class) for the start of
the program and the main method always looks like that. The argument of the
main method is an array of Strings which represent command line arguments.
A lot has happened here in just a short time. Each part will become clear within
each chapter.

Hello World Program


Lets create the most simple program. The program is collectively called the Hello
World program that will simply print a message to the console.

public class Hello{


public static void main(String args[]){

System.out.println("Hello World!");
}
}

As stated, the above program will print the message to the console.

Console Input/Output
All basic input and output streams are contained in the System library. Here is
some description of some methods contained in that library:
System.out.print( things to print )
This will simply print something to the console. It can print a variable,
String, character, double, Object etc When attempting to print something,
it will look for a toString method that will handle the conversion needed. The
default toString method is contained in the java.lang default library. This
method does not print a new line character at the end.
System.out.println( things to print )
This will function the same as the above print but it now will print the new
line character at the end; hence the ln contained in the method name.
For console input, please see Scanners in chapter 4.

Compiling Java Programs


To compile a Java program, you need to use the built in compiler for the command
line called javac. That stands for java compiler. The general format for compiling
a program is:

javac FileName.java

where FileName is the name of the java file to compile. To compile a bunch of Java
programs all at once, you may do this:

javac *.java
where the * will compile all filenames with the java extension. So using the above
example of Hello World, here is how to compile it:

javac Hello.java

Command Line Arguments


A Java program can contain whats called a command line argument. When
compiling a program, you can give certain values to the main methods array of
arguments.

Example 1:
Command Line Arguments
Lets see an example that will allow you to enter your first and last name to the
command line.

public class HelloYourName{


public static void main(String args[]){
if(args.length != 2){
System.out.println("First + Last name needed");
System.exit(1);
}
System.out.println("Hello " + args[0] + " "
+ args[1]);
}
}

The above program will execute first by checking the number of command line
arguments. It then will print out the name entered by the user since we know the
arguments are correct. The users first name is contained in args[0] and the last
name is contained in args[1]. More on Strings and arrays will follow in this book.
Observe from the above the + operator is used to concatenate Strings. This is
similar to the C++ << operator when using it for output.
Here is the command line for compiling and executing. To compile the program:

javac HelloYourName.java

To run the program, simply replace the message in the quotes with your first and
last name respectively WITHOUT THE BRACKETS:

java HelloYourName [your first name] [your last name]

Also note that the arguments are separated by a space. This allows the array to
note the separate arguments. Say that we ran the program above with the
following command line:

java HelloYourName Alex

We will get an error message and the output would be:


First + Last name needed
We get the error message because the program did not contain the proper number
of command line arguments. Now if we ran the program with this command line:

java HelloYourName Alex Maureau

We get the output:


Hello Alex Maureau
Please see Chapter 5 (Wrapper Classes & Parsing) for more on command
line arguments and their use.

Documentation & Javadoc


An important part of programming is documentation. Without it, you can run into a
lot of trouble when trying to debug a program. There are three types of
documentation for a program in Java; in-line comments, block comments and
Javadoc comments.
The first type of comment is an in-line comment that may look like this in a code
snippet:

public static void main(String args[]){


//check for arguments here
}

The in-line comment is denoted by the two forward slashes. Anything appearing on
that line past those two markers is ignored by the compiler.
The second type of comment is the block comment that may look like this in a code
snippet:

public static void main(String args[]){


/*
*check for arguments here
*/
}

Note that to START the block comment, there is the /* while to END the block
comment, there is the */. They are different from each other so be careful.
The final piece of commenting is Javadoc. The Javadoc comments are denoted by
this:

/**
*
Javadoc writing here. The Javadoc will explain
*
and document a method.
*/
public static void main(String args[]){
//code here for main
}

One important note is to realize that there is a /** to begin the Javadoc and the */
to finish it. If you are using a fancy environment such as Eclipse, it will turn blue to
signify Javadoc. A block comment and in-line comment will turn green.
A good view of Javadoc is to view the current Java APIs online at
http://sun.java.com

Terminating programs
To terminate a program earlier than it should be, you can use the exit() method in
the System library. The syntax will be as follows:

System.exit(1);

You can of course replace the number 1 with any integer of your choosing. Mostly,
0 and 1 are used. One is used to denote a problem and signal to a debugger that
there is an early termination. Zero is used to state that there are no issues. Again,
it is not a requirement to just use 0 and 1.

CHAPTER 2
Variables

This chapter covers what a Java variable is and what it does. It also covers
the many types of variables you may have which include integers, decimals
or characters. The final part of the chapter discusses type casting which
deals with changing data types after they are defined.

In Java, a variable will be used to hold some form of data. That data can be of any
type, such as an integer, decimal or character, just to name a few.

Declaring variables
There are numerous ways to use and declare variables in Java. Here is one of the
ways to declare a variable:

[identifier] type var_name = initial_value;

where identifier is either public, private or protected (see later); type is the data
type of the variable; var_name is a useful name of the variable and initial_value
is the default value given to a variable.
As an example, lets say the user wants to declare an integer variable in the main
method of a program. Here is one way to do so:
public class Example{
public static void main(String args[]){
int x = 4;
System.out.println(x);
}
}
The output from above will simply be 4 since that is the variables initial value.
Below are the most common data types used in Java:
Type Name
char
short
int
long
boolean
float

Description
Character or small integer.
Signed range: -128 to 127
Unsigned range: 0 to 255
Short Integer.
Signed: -32768 to 32767
Unsigned: 0 to 65535
Integer.
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
Long Integer.
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
Boolean value. Either true or false.
Acceptable as 1 or 0 respectively.
Floating point number.

Size
1 byte
2 bytes
4 bytes
4 bytes
1 byte
4 bytes

double

3.4e +/- 38 (7 digits)


Double precision floating point number.
1.7e +/- 308 (15 digits)

8 bytes

Instance variables
A class or object can have it's own variables. In Java, these are called instance
variables. By its definition, an instance variable is unique to each instance of the
class; so in general, each time a class is "instantiated" with the new operator, there
is another variable associated with it.
These variables are declared outside any methods you may have. These variables
are declared either public, private or protected. They are global to the class or
object they appear in. Let's see a small example.

public class Variables{


private int x = 0;
public static void main(String args[]){
x++;
System.out.println("Welcome! " + x);
}
}

In this example, the instance variable x is declared private. In addition, it is global


to the Variables object and cannot be accessed from another object due to the
private identifier.
The program simply prints out "Welcome! 1" when the program starts.

Static variables
Static variables are quite a bit harder to understand. Do not be confused with a
static variable from C++. They are very different.
In java, a static variable (also called a class variable), is a variable that is given a
fixed block of memory. The static keyword tells the compiler that there is exactly
one copy of this variable in existence, no matter how many times the class has
been instantiated.
Let's just think of a real world example. Say you own a car. The car will always
have four wheels in the US. So if you made a class in java called Car, a variable
called numWheels can be made static since it will be the same for every car.

Let's see an example of a static variable.

public class SVariables{


private static int x = 0;
private int y = 3;
public SVariables(){
x++;
y += 5;
System.out.println(y + " -- Welcome -- " + x);
}
public static void main(String args[]){
SVariables s1 = new SVariables();
SVariables s1a = new SVariables();
SVariables s1b = new SVariables();
}
}

When you run the above program, this is the output:


8 -- Welcome -- 1
8 -- Welcome -- 2
8 -- Welcome -- 3
Here is why the output is this way. With the s1 instance of the object, the value of
x is 1 and the value of y is 8, as per the arithmetic operations in the constructor.
The next instance of the object SVariables is s1a. Here, the value of x is 2
BECAUSE OF THE STATIC while the value of y is again 8, BECAUSE OF THE NONSTATIC.
In the final instance of the object SVariables, the x is 2 while the y is 8.

Final variables
In C++, we can declare variables constant if we know their values will not change.
In Java, we do not use the keyword const but we use the keyword final. Final
variables cannot be changed and are made constant. They can be either instance
variables or local variables to a method.
A common practice is to make the final variables name all capital letters. So here is
what something may look like:

public class X{

static final int AREA = 25;


.
.
.
}

Type Casting
In Java, we can allow a variable to change its current data type by casting it to
another data type. There are two types of casting: implicit and explicit.
Implicit
Implicit casting is when the data type is changed automatically in the program.
We do not need to explicitly tell the program to cast.
Automatic casting
This occurs in the compiler as it tries to compile your program:
int x = 5.667;
float f = 7;

//automatically changed to 5
//automatically changed to 7.0

Promotion casting
This occurs when more space is given to a number (i.e. short to int):
int I = 6;
long u = I;

//promoted here to long.

Demotion casting
This occurs when less space is given to a number (i.e. int to short):
double d = 8.9;
float f = d;
//demoted here from double.
Explicit
Explicit casting is when we need to tell the program to change the type. This is
done by placing the data type in parenthesis next to the expression (see below).
Say we wanted to compute the average of some integers and just wanted to output
the whole number from the average, ignoring the decimal places. Here is a
program that will show this:
public class Example{
public static void main(String args[]){
int a = 5, b = 7, c = 10;
double avg = ((double) a+b+c) / 3.0;

//cast here

int ans = (int) avg; //cast here


System.out.println(ans);
}
}

We cast in two places with the above program. First, we cast the sum of the 3
integers to a double precision value and divide by 3.0. We need to do this
otherwise we get incorrect division.
We also cast in the final result changing the answer from the double precision value
to an int value. This program will output 7 when run.

Overflow
In Java, variables can overflow their capacity. For instance, if you were to declare
the following piece of code:

short z = 10000;
z = z + 40000;
System.out.println( z );
You would see something like this as the output:
-15536
The reason behind this is that you ran out of room to represent the number in its
binary form. That is a bit technical to discuss here but just know that if you see a
negative number when it is supposed to be positive, you overflowed the number!!!
The solution is to use a bigger data type.
Here is a program that will overflow some numbers.

public class Overflow{


public static void main(String args[]){
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(

(short)(10000) );
(short)(33000) );
(int)(10000000) );
(int)(123456789) );
(long)(101010101010101010) );
(long)(99999999999999999) );

} //main
} //class
The output from running the above program is:
10000
-32536
10000000
123456789
-714149102
1569325055
NOTE: Depending on the compiler you have, it may not even compile (for
instance in Eclipse). If you use command line Java, it may work out to the
output above.
The first number will work just fine (being the short(10000)) since that is in range.
The following short(33000) is just a bit out of range so it will give you the -32536
you see on screen.
Then, both the int values are still in range so they will be just fine however both the
long values are not! It may appear that a long holds more numbers but certainly
not numbers that big!!!

CHAPTER 3
Operators

This chapter covers how to use variables. Now that we know they are
already defined, we can now properly use them in a program. We may need
to perform arithmetic, manipulations or even logical testing (seeing if things
are equal or not). There are some example programs that showcase the use
of many different operators.

Now that we know a bit about Java variables and classes, we can now know how to
operate on them. An operator performs an action on a variable(s), methods etc...
It can assign values (the = operator), perform arithmetic (+, -, *, /), concatenate
Strings (the + operator) as well as many more things.
Below is a collection of operators and the category they fall under. Some of them
have been seen already.

Assignment operators
=

Assignment
This operator assigns a value to a variable(s). A simple example is:
X = 5;
This operator also can assign multiple values at once:
A=B=C=6
The above will assign the value 6 to all three variables A, B and C.

Arithmetic operators
+, -, *, /
Addition, Subtraction, Multiplication & Division respectively. These will
perform the appropriate operations on variables.
%

Modular division
The modulo division of two numbers is the remainder when the number on
the left is divided by the number on the right. Here are some examples
below:
3%5
evaluates to 3 since 5 goes into 3 ZERO times with a remainder of 3.
7%3
evaluates to 1 since 3 goes into 7 TWO times with a remainder of 1.
15 % 1
evaluates to 0 since any number MOD 1 is ZERO as 1 goes into that
number fully.
12 % 0
evaluates to a compiler error since you cannot divide by ZERO in
mathematics.

Relational/Equality operators
==

Logical Equals
Both sides of a statement must have the EXACT same truth value or regular
value in order for the entire thing to be TRUE.
(7 == 5)
false since 7 is not equal to 5.
(5 % 2 == 1)
true since the remainder when 5 is divided by 2 is 1.

!=

Logical Not Equal


Both sides of a statement must have different truth values or regular values
in order for the entire thing to be TRUE.
(8 != 8)
false since 8 is indeed 8.
(7 + 2 != 4)
true since 7+2 is 9.

>

Logical strictly greater than


An expression on the left hand side must be strictly greater than an
expression on the right hand side in order for this expression to be TRUE.
(19 > 6)
true since 19 is greater than 6.
(4 > 8)
false since 4 is not bigger than 8.

>=

Logical greater than or equal to


An expression on the left hand side must be strictly greater or equal to an
expression on the right hand side in order for this expression to be TRUE.
(9 >= 9)
true since 9 is greater than or equal to 9.
(18 >= 22)
false since 18 is not greater than or equal to 22.

<

Logical Strictly less than


An expression on the left hand side must be strictly less than an expression
on the right hand side in order for this expression to be TRUE.
(9 < 9)
false since 9 is not less than 9.

(18 < 22)


true since 18 is less than 22.
<=

Logical Less than or equal to


An expression on the left hand side must be strictly less than or equal to an
expression on the right hand side in order for this expression to be TRUE.
(9 <= 9)
true since 9 is less than or equal to 9.
(18 <= 22)
true since 18 is less than or equal to 22.

Logical operators
&&

Logical And
All elements of the statement must be TRUE in order for the whole
expression to be TRUE. Here is the truth table using booleans:
true && true
true && false
false && true
false && false

||

true
false
false
false

Logical Or
One or more elements of the statement must be TRUE in order for the whole
thing to be TRUE.
true || true
true || false
false || true
false || false

->
->
->
->

->
->
->
->

true
true
true
false

Logical Not
This will invert or negate the logic for a variable or an entire expression.
So TRUE becomes FALSE and FALSE becomes TRUE.
!(5 == 8)
true since the initial expression was false.
!(8 < 9)
false since the initial expression was true.

Increase/Decrease operators
++

Pre/Post increment

A variable can be incremented by 1 (one) using the increment operator. If


the ++ comes before the variable, the variable is incremented FIRST then
USED. If the ++ comes after the variable, the variable is USED first THEN
decremented.
k++ Use then increment
++k increment then use
--

Pre/Post decrement
A variable can be decremented by 1 (one) using the decrement operator. If
the -- comes before the variable, the variable is incremented FIRST then
USED. If the -- comes after the variable, the variable is USED first THEN
decremented.
k-- Use then decrement
--k decrement then use

Bitwise operators
All numbers in computers are represented in binary form, meaning they are a string
of 1s and 0s.
&

Bitwise And
Compares each bit of the binary representation of that number. Both bits
must be 1 in order for the resulting bit to be 1. Otherwise it is 0.
&

101001
000111
000001

(41)
(7)

The resulting decimal number is 1.


|

Bitwise Or
Compares each bit of the binary representation of that number. One or both
bits can be 1 in order for the resulting bit to be 1. Otherwise it is 0 if both
bits are zeroes.
|

101001
000111
101111

(41)
(7)

The resulting decimal number is 47.


|

Bitwise XOR
Compares each bit of the binary representation of that number. If one of the
bits for comparison are 1, the resulting bit is 1. The resulting bit is a 0 if the
bits are both 0 or both 1.

101001
000111
101110

(41)
(7)

The resulting decimal number is 46.

Compound Assignment operators


+=

-=

/= *= %= Compound arithmetic operators


All of the above are the shorthand equivalents of regular operators. In order
above, they are plus equals, minus equals, divides equals, times
equals, mod equals. Here are examples below:
a
a
a
a
a

+=
-=
/=
*=
%=

3
3
2
10
2

MEANS
MEANS
MEANS
MEANS
MEANS

a
a
a
a
a

=
=
=
=
=

a
a
a
a
a

/
*
%

3
3
2
10
2

Each operator above may have different meanings when dealing with different
topics. For example, the + operator relates to addition and concatenating strings.

Examples
Below are some examples that show the use of most of the above operators. Each
example is explained in detail following the code. NOTE: These 3 programs will be
modified in chapter 4 when dealing with wrapper classes and objects.

Example 1:
Arithmetic showcase
This program will perform, on two integers, addition, subtraction, multiplication and
division and modular division of those two numbers.

public class Example1{


public static void main(String args[]){
int a = 5, b = 4;
//addition
System.out.println("The sum is: " + (a+b));
//subtraction
System.out.println("The difference is: " + (a-b));
//multiplication
System.out.println("The product is: " + (a*b));

//division
System.out.println("The quotient is: " + (a/b));
//modular division
System.out.println("The a mod b is: " + (a%b));
} //main
} //class
A sample run of the program will produce the following output:
The
The
The
The
The

sum is: 9
difference is: 1
product is: 20
quotient is: 1
a mod b is: 1

Example 2:
Change in coins
This program will calculate the change needed in the number of quarters, dimes,
nickels and pennies. The value is entered from the command line.

public class Example2{


public static void main(String args[]){
int x = 90;
System.out.println("Change for " + x + " cents:");
int q, d, n, c; //quarters, dimes, nickels and cents wanted
q
x
d
x
n
c

=
=
=
=
=
=

x
x
x
x
x
x

/
%
/
%
/
%

25;
25;
10;
10;
5;
5;

System.out.println("Quarters: " + q + "\nDimes: " + d +


"\nNickels: " + n + "\nCents: " + c);
} //main
} //class
Say that the user needs 90 cents worth of change. The first thing that the program
needs to do is calculate the quarters. Here, 90 divided by 25 is 3. Note that the int

DOES NOT handle decimals and only looks at whole numbers. It then stores 3 into
the variable q.
Then, the new value of x is calculated by placing the remainder when 90 is divided
by 25, here it is 15.
Now, the dimes are calculated by taking 15 (since that is currently x) and dividing it
by 10 which produces 1 (again, the int ignores the decimals). Now, the new value
of x is 15 mod 10 which is 5.
The program will then calculate the nickels and cents accordingly. The final result
will be:
q = 3, d = 1, n = 1, c = 0
A sample run of this program from the above is:
Change for 90 cents:
Quarters: 3
Dimes: 1
Nickels: 1
Pennies: 0

Example 3:
Incrementing/Decrementing
This program will show the use of the operators for incrementing and decrementing
a number. This also shows the order of the operators.

public class Example3{


public static void main(String args[]){
int num = 5;
//allows user to enter an integer
System.out.println("The number 5:");
//once entered, use the operators
//"post" increment:
System.out.println(num++);
//"pre" increment:
System.out.println(++num);
//"post" decrement:
System.out.println(num--);
//"pre" decrement:

System.out.println(--num);
} //main
} //class
Lets see why the output is this way. First, the value of the variable num is 5. The
first operator that is used on the variable is the "post" increment operator. This
uses the variable first (for output) THEN increments it. So the output is 5 BUT THE
VARIABLE HOLDS THE VALUE 6.
Next, the variable is "pre" incremented so it is incremented FIRST, THEN outputted.
The output is 7 since it was already incremented.
The same applies for the decrementing.
A sample run of the above program looks like:
The number 5:
5
7
7
5

You might also like