JAVA For Beginners: 2 Edition
JAVA For Beginners: 2 Edition
JAVA For Beginners: 2 Edition
JAVA for
Beginners
An introductory course for Advanced IT Students and those who would Riccardo
like to learn the Java programming language.
Flask
JAVA for Beginners
Contents
Introduction ............................................................................................................................................................ 5
About JAVA ............................................................................................................................................................. 5
OOP – Object Oriented Programming .................................................................................................................... 5
Part 1 - Getting Started ........................................................................................................................................... 6
The Java Development Kit – JDK ........................................................................................................................ 6
My first Java program......................................................................................................................................... 6
Using an IDE ....................................................................................................................................................... 7
Variables and Data Types ....................................................................................................................................... 8
Variables ............................................................................................................................................................. 8
Test your skills – Example3................................................................................................................................ 8
Mathematical Operators .................................................................................................................................... 9
Logical Operators ............................................................................................................................................... 9
Character Escape Codes ................................................................................................................................... 11
Test your skills – Example7............................................................................................................................... 12
Data Types ........................................................................................................................................................ 13
Introducing Control Statements ....................................................................................................................... 16
Blocks of Code .................................................................................................................................................. 18
Test your skills – Example14 ................................................................................................................................. 18
The Math Class ................................................................................................................................................. 19
Scope and Lifetime of Variables ....................................................................................................................... 20
Type Casting and Conversions .......................................................................................................................... 21
Console Input ................................................................................................................................................... 24
Using the Keyboard Class ............................................................................................................................. 24
Using the Scanner Class ............................................................................................................................... 33
Using Swing Components ............................................................................................................................ 34
Part 2 - Advanced Java Programming ................................................................................................................... 35
Control Statements - The if Statement ................................................................................................................. 35
Guessing Game (Guess.java) ............................................................................................................................ 36
Nested if ............................................................................................................................................................... 37
Guessing Game v.3 ........................................................................................................................................... 37
if-else-if Ladder ..................................................................................................................................................... 38
Ternary (?) Operator ............................................................................................................................................. 39
switch Statement (case of) ................................................................................................................................... 41
Nested switch ....................................................................................................................................................... 45
Mini-Project – Java Help System (Help.java) ........................................................................................................ 45
Complete Listing .......................................................................................................................................... 46
Introduction
About JAVA
“Java refers to a number of computer software products and specifications from Sun Microsystems
(the Java™ technology) that together provide a system for developing and deploying cross-platform
applications. Java is used in a wide variety of computing platforms spanning from embedded devices
and mobile phones on the low end to enterprise servers and super computers on the high end. Java
is fairly ubiquitous in mobile phones, Web servers and enterprise applications, and somewhat less
common in desktop applications, though users may have come across Java applets when browsing
the Web.
Writing in the Java programming language is the primary way to produce code that will be deployed
as Java bytecode, though there are compilers available for other languages such as JavaScript,
Python and Ruby, and a native Java scripting language called Groovy. Java syntax borrows heavily
from C and C++ but it eliminates certain low-level constructs such as pointers and has a very simple
memory model where every object is allocated on the heap and all variables of object types are
references. Memory management is handled through integrated automatic garbage collection
performed by the Java Virtual Machine (JVM).”1
OOP is a particular style of programming which involves a particular way of designing solutions to
particular problems. Most modern programming languages, including Java, support this paradigm.
When speaking about OOP one has to mention:
Inheritance
Modularity
Polymorphism
Encapsulation (binding code and its data)
However at this point it is too early to try to fully understand these concepts.
This guide is divided into two major sections, the first section is an introduction to the language and
illustrates various examples of code while the second part goes into more detail.
1
http://en.wikipedia.org/wiki/Java_%28Sun%29
Once you download and install this JDK you are ready to get started. You need a text editor as well
and Microsoft’s Notepad (standard with all Windows versions) suits fine.
/*
This is known as a Block Comment.
My first program These lines are useful to the
programmer and are ignored by the
Version 1 Compiler
*/
Save the file as Example1.java2. The name of the program has to be similar to the filename.
Programs are called classes. Please note that Java is case-sensitive. You cannot name a file
“Example.java” and then in the program you write “public class example”. It is good practice to
insert comments at the start of a program to help you as a programmer understand quickly what the
particular program is all about. This is done by typing “/*” at the start of the comment and “*/”
when you finish. The predicted output of this program is:
In order to get the above output we have to first compile the program and then execute the
compiled class. The applications required for this job are available as part of the JDK:
In order to compile and execute the program we need to switch to the command prompt. On
windows systems this can be done by clicking Start>Run>cmd
2
Ideally you should create a folder on the root disk (c:\) and save the file there
At this point one needs some basic DOS commands in order to get to the directory (folder), where
the java class resides:
When you get to the required destination you need to type the following:
The above command will compile the java file and prompt the user with any errors. If the
compilation is successful a new file containing the bytecode is generated: Example1.class
Using an IDE
Some of you might already be frustrated by this point. However there is still hope as one can forget
about the command prompt and use an IDE (integrated development environment) to work with
Java programming. There are a number of IDE’s present, all of them are fine but perhaps some are
easier to work with than others. It depends on the user’s level of programming and tastes! The
following is a list of some of the IDE’s available:
Beginners might enjoy BlueJ and then move onto other IDE’s like JCreator, NetBeans, etc. Again it’s
just a matter of the user’s tastes and software development area.
Variables
A variable is a place where the program stores data temporarily. As the name implies the value
stored in such a location can be changed while a program is executing (compare with constant).
class Example2 {
var2 = var1 / 2;
System.out.println(var2);
Predicted Output:
The above program uses two variables, var1 and var2. var1 is assigned a value directly while var2 is
filled up with the result of dividing var1 by 2, i.e. var2 = var1/2. The words int refer to a particular
data type, i.e. integer (whole numbers).
Hints:
Mathematical Operators
As we saw in the preceding example there are particular symbols used to represent operators when
performing calculations:
class Example4 {
iresult = 10 / 3;
irem = 10 % 3;
Predicted Output:
The difference in range is due to the data type since ‘double’ is a double precision 64-bit floating
point value.
Logical Operators
These operators are used to evaluate an expression and depending on the operator used, a
particular output is obtained. In this case the operands must be Boolean data types and the result is
also Boolean. The following table shows the available logical operators:
Operator Description
& AND gate behaviour (0,0,0,1)
| OR gate behaviour (0,1,1,1)
^ XOR – exclusive OR (0,1,1,0)
&& Short-circuit AND
|| Short-circuit OR
! Not
class Example5 {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
if(d != 0 && (n % d) == 0)
*/
if(d != 0 & (n % d) == 0)
Predicted Output:
*Note if you try to execute the above program you will get an error (division by zero). To be able to
execute it, first comment the last two statements, compile and then execute.
2 is a factor of 10
Riccardo Flask 10 | P a g e
JAVA for Beginners
Trying to understand the above program is a bit difficult, however the program highlights the main
difference in operation between a normal AND (&) and the short-circuit version (&&). In a normal
AND operation, both sides of the expression are evaluated, e.g.
if(d != 0 & (n % d) == 0) – this returns an error as first d is compared to 0 to check inequality and then
the operation (n%d) is computed yielding an error! (divide by zero error)
The short circuit version is smarter since if the left hand side of the expression is false, this mean
that the output has to be false whatever there is on the right hand side of the expression, therefore:
if(d != 0 && (n % d) == 0) – this does not return an error as the (n%d) is not computed since d is
equal to 0, and so the operation (d!=0) returns false, causing the output to be false. Same applies for
the short circuit version of the OR.
Code Description
\n New Line
\t Tab
\b Backspace
\r Carriage Return
\\ Backslash
\’ Single Quotation Mark
\” Double Quotation Mark
\* Octal - * represents a number or Hex digit
\x* Hex
\u* Unicode, e.g. \u2122 = ™ (trademark symbol)
class Example6 {
System.out.println("A\tB\tC");
System.out.println("D\tE\tF") ;
Predicted Output:
First Line
Second Line
A B C
D E F
Riccardo Flask 11 | P a g e
JAVA for Beginners
You need two Boolean type variables which you will initially set both to false
Use character escape codes to tabulate the results
class LogicTable {
boolean p, q;
System.out.println("P\tQ\tPANDQ\tPORQ\tPXORQ\tNOTP");
p = true; q = true;
p = true; q = false;
p = false; q = true;
p = false; q = false;
Riccardo Flask 12 | P a g e
JAVA for Beginners
Predicted Output:
Data Types
The following is a list of Java’s primitive data types:
The ‘String’ type has not been left out by mistake. It is not a primitive data type, but strings (a
sequence of characters) in Java are treated as Objects.
class Example8 {
Riccardo Flask 13 | P a g e
JAVA for Beginners
var = var / 4;
x = x / 4;
Predicted output:
One here has to note the difference in precision of the different data types. The following example
uses the character data type. Characters in Java are encoded using Unicode giving a 16-bit range, or
a total of 65,537 different codes.
class Example9 {
char ch;
ch = 'X';
ch++; // increment ch
Riccardo Flask 14 | P a g e
JAVA for Beginners
Predicted Output:
ch is now X
ch is now Y
ch is now Z
The character ‘X’ is encoded as the number 88, hence when we increment ‘ch’, we get character
number 89, or ‘Y’.
The Boolean data type can be either TRUE or FALSE. It can be useful when controlling flow of a
program by assigning the Boolean data type to variables which function as flags. Thus program flow
would depend on the condition of these variables at the particular instance. Remember that the
output of a condition is always Boolean.
class Example10 {
boolean b;
b = false;
b = true;
b = false;
Predicted output:
b is false
b is true
This is executed
10 > 9 is true
Riccardo Flask 15 | P a g e
JAVA for Beginners
class Example11 {
int a,b,c;
a = 2;
b = 3;
c = a - b;
System.out.println();
c = b - a;
Predicted output:
c is a negative number
c is a positive number
The ‘if’ statement evaluates a condition and if the result is true, then the following statement/s are
executed, else they are just skipped (refer to program output). The line System.out.println() simply
inserts a blank line. Conditions use the following comparison operators:
Operator Description
< Smaller than
> Greater than
<= Smaller or equal to, (a<=3) : if a is 2 or 3, then result of comparison is TRUE
>= Greater or equal to, (a>=3) : if a is 3 or 4, then result of comparison is TRUE
== Equal to
!= Not equal
Riccardo Flask 16 | P a g e
JAVA for Beginners
The for loop is an example of an iterative code, i.e. this statement will cause the program to repeat a
particular set of code for a particular number of times. In the following example we will be using a
counter which starts at 0 and ends when it is smaller than 5, i.e. 4. Therefore the code following the
for loop will iterate for 5 times.
class Example12 {
int count;
System.out.println("Done!");
Predicted Output:
This is count: 0
This is count: 1
This is count: 2
This is count: 3
This is count: 4
Done!
Instead of count = count+1, this increments the counter, we can use count++
Riccardo Flask 17 | P a g e
JAVA for Beginners
Blocks of Code
Whenever we write an IF statement or a loop, if there is more than one statement of code which has
to be executed, this has to be enclosed in braces, i.e. ‘, …. -’
class Example13 {
double i, j, d;
i = 5;
j = 10;
if(i != 0) {
d = j / i; Block of
Code
System.out.print("j / i is " + d);
System.out.println();
Predicted Output:
j/i is 2
Hints:
The Euro Converter has been provided for you for guidance. Note loop starts at 1 and finishes at 100
(<101). In this case since the conversion rate does not change we did not use a variable, but assigned
it directly in the print statement.
class EuroConv {
Riccardo Flask 18 | P a g e
JAVA for Beginners
double eu;
System.out.println();
for (eu=1;eu<101;eu++)
class Example15 {
double x, y, z;
x = 3;
y = 4;
z = Math.sqrt(x*x + y*y);
Predicted Output:
Hypotenuse is 5.0
Please note that whenever a method is called, a particular nomenclature is used where we first
specify the class that the particular method belongs to, e.g. Math.round( ); where Math is the class
name and round is the method name. If a particular method accepts parameters, these are placed in
brackets, e.g. Math.max(2.8, 12.9) – in this case it would return 12.9 as being the larger number. A
Riccardo Flask 19 | P a g e
JAVA for Beginners
useful method is the Math.random( ) which would return a random number ranging between 0.0
and 1.0.
class Example16 {
x = 10;
x = y * 2;
Predicted Output:
x and y: 10 20
x is 40
If we had to remove the comment marks from the line, y = 100; we would get an error during
compilation as y is not known since it only exists within the block of code following the ‘if’
statement.
The next program shows that y is initialized each time the code belonging to the looping sequence is
executed; therefore y is reset to -1 each time and then set to 100. This operation is repeated for
three (3) times.
Riccardo Flask 20 | P a g e
JAVA for Beginners
class Example17 {
int x;
y = 100;
Predicted Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
long L;
double D;
L = 100123285L;
D = L; // L = D is impossible
Riccardo Flask 21 | P a g e
JAVA for Beginners
Predicted Output:
The general formula used in casting is as follows: (target type) expression, where target type could
be int, float, or short, e.g. (int) (x/y)
double x, y;
byte b;
int i;
char ch;
x = 10.0;
y = 3.0;
i = 100;
b = (byte) i;
i = 257;
b = (byte) i;
ch = (char) b;
Riccardo Flask 22 | P a g e
JAVA for Beginners
Predicted Output:
Integer outcome of x / y: 3
Value of b: 100
Value of b: 1
ch: X
In the above program, x and y are doubles and so we have loss of precision when converting to
integer. We have no loss when converting the integer 100 to byte, but when trying to convert 257 to
byte we have loss of precision as 257 exceeds the size which can hold byte. Finally we have casting
from byte to char.
class Example20 {
byte b;
int i;
b = 10;
b = 10;
Predicted Output:
The above program illustrates the difference between automatic conversion and casting. When we
are assigning a byte to integer, i = b * b, the conversion is automatic. When performing an arithmetic
operation the byte type are promoted to integer automatically, but if we want the result as byte, we
have to cast it back to byte. This explains why there is the statement: b = (byte) (b * b). Casting has
to be applied also if adding variables of type char, as result would else be integer.
Riccardo Flask 23 | P a g e
JAVA for Beginners
Console Input
Most students at this point would be wondering how to enter data while a program is executing.
This would definitely make programs more interesting as it adds an element of interactivity at run-
time. This is not that straight forward in Java, since Java was not designed to handle console input.
The following are the three most commonly used methods to cater for input:
import java.io.*;
import java.util.*;
return errorCount;
}
errorCount = 0;
return printErrors;
Riccardo Flask 24 | P a g e
JAVA for Beginners
printErrors = flag;
// if appropriate.
errorCount++;
if (printErrors)
System.out.println (str);
(new InputStreamReader(System.in));
// Gets the next input token, which may already have been
//read.
String token;
if (current_token == null)
Riccardo Flask 25 | P a g e
JAVA for Beginners
else {
token = current_token;
current_token = null;
return token;
// Gets the next token from the input, which may come from
try {
if (reader == null)
while (!reader.hasMoreTokens())
(in.readLine(), delimiters,true);
token = reader.nextToken();
token = null;
Riccardo Flask 26 | P a g e
JAVA for Beginners
return token;
return !reader.hasMoreTokens();
String str;
try {
str = getNextToken(false);
while (! endOfLine()) {
str = null;
return str;
// standard input.
String token;
Riccardo Flask 27 | P a g e
JAVA for Beginners
try {
token = getNextToken();
token = null;
return token;
boolean bool;
try {
if (token.toLowerCase().equals("true"))
bool = true;
else if (token.toLowerCase().equals("false"))
bool = false;
else {
bool = false;
Riccardo Flask 28 | P a g e
JAVA for Beginners
bool = false;
return bool;
char value;
try {
if (token.length() > 1) {
value = Character.MIN_VALUE;
return value;
int value;
try {
Riccardo Flask 29 | P a g e
JAVA for Beginners
value = Integer.MIN_VALUE;
return value;
long value;
try {
value = Long.MIN_VALUE;
return value;
float value;
try {
Riccardo Flask 30 | P a g e
JAVA for Beginners
value = Float.NaN;
return value;
double value;
try {
value = Double.NaN;
return value;
Riccardo Flask 31 | P a g e
JAVA for Beginners
o Reads and returns a boolean value from standard input. Returns false if an exception
occurs during the read.
public static char readChar ()
o Reads and returns a character from standard input. Returns MIN_VALUE if an
exception occurs during the read.
public static int readInt ()
o Reads and returns an integer value from standard input. Returns MIN_VALUE if an
exception occurs during the read.
public static long readLong ()
o Reads and returns a long integer value from standard input. Returns MIN_VALUE if
an exception occurs during the read.
public static float readFloat ()
o Reads and returns a float value from standard input. Returns NaN if an exception
occurs during the read.
public static double readDouble ()
o Reads and returns a double value from standard input. Returns NaN if an exception
occurs during the read.
public static int getErrorCount()
o Returns the number of errors recorded since the Keyboard class was loaded or since
the last error count reset.
public static void resetErrorCount (int count)
o Resets the current error count to zero.
public static boolean getPrintErrors ()
o Returns a boolean indicating whether input errors are currently printed to standard
output.
public static void setPrintErrors (boolean flag)
o Sets the boolean indicating whether input errors are to be printed to standard input.
Let’s try it out by writing a program which accepts three integers and working the average:
System.out.println("Enter a number:");
Riccardo Flask 32 | P a g e
JAVA for Beginners
After printing a statement, the program will wait for the use r to enter a number and store it in the
particular variable. It utilizes the readInt( ) method. Finally it will display the result of the average.
import java.util.Scanner;
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
By examining the code we see that first we have to import the java.util.Scanner as part of the
java.util package. Next we create an instance of Scanner and name it as we like, in this case we
named it “input”. We have to specify also the type of input expected (System.in). The rest is similar
to the program which uses the Keyboard class, the only difference is the name of the method used,
in this case it is called nextInt ( ) rather than readInt( ). This time the method is called as part of the
instance created, i.e. input.nextInt( )
Riccardo Flask 33 | P a g e
JAVA for Beginners
int b = Integer.parseInt(temp);
int c = Integer.parseInt(temp);
One has to note that the input is stored as a string, temp, and then parsed to integer using the
method parseInt( ). This time the method accepts a parameter, temp, and returns an integer. When
the above program is executed, a dialog box will appear on screen with a field to accept input from
user via keyboard (JOptionPane.showInputDialog). This is repeated three times and finally the result
is again displayed in a dialog box (JOptionPane.showMessageDialog).
JOptionPane.showInputDialog JOptionPane.showMessageDialog
Riccardo Flask 34 | P a g e
JAVA for Beginners
if(condition) statement;
else statement;
Note:
if(condition)
statement sequence
else
statement sequence
If the conditional expression is true, the target of the if will be executed; otherwise, if it exists,
the target of the else will be executed. At no time will both of them be executed. The conditional
Riccardo Flask 35 | P a g e
JAVA for Beginners
The program asks the player for a letter between A and Z. If the player presses the correct letter on
the keyboard, the program responds by printing the message **Right **.
class Guess {
throws java.io.IOException {
class Guess2 {
throws java.io.IOException {
Riccardo Flask 36 | P a g e
JAVA for Beginners
Nested if
The main thing to remember about nested ifs in Java is that an else statement always refers to the
nearest if statement that is within the same block as the else and not already associated with an
else. Here is an example:
if(i == 10) {
class Guess3 {
throws java.io.IOException {
else {
// a nested if
Riccardo Flask 37 | P a g e
JAVA for Beginners
if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The conditional expressions are evaluated from the top downward. As soon as a true condition is
found, the statement associated with it is executed, and the rest of the ladder is bypassed. If none of
the conditions is true, the final else statement will be executed. The final else often acts as a default
condition; that is, if all other conditional tests fail, the last else statement is performed. If there is no
final else and all other conditions are false, no action will take place.
class Ladder {
int x;
if(x==1)
System.out.println("x is one");
else if(x==2)
System.out.println("x is two");
Riccardo Flask 38 | P a g e
JAVA for Beginners
else if(x==3)
System.out.println("x is three");
else if(x==4)
System.out.println("x is four");
else
x is one
x is two
x is three
x is four
Declared as follows:
Exp1 would be a boolean expression, and Exp2 and Exp3 are expressions of any type other than
void. The type of Exp2 and Exp3 must be the same, though. Notice the use and placement of the
colon. Consider this example, which assigns absval the absolute value of val:
Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval
will be assigned the negative of that value (which yields a positive value).
Riccardo Flask 39 | P a g e
JAVA for Beginners
The same code written using the if-else structure would look like this:
e.g. 2 This program divides two numbers, but will not allow a division by zero.
100 / -5 is -20
100 / -4 is -25
100 / -3 is -33
100 / -2 is -50
100 / -1 is -100
100 / 1 is 100
100 / 2 is 50
100 / 3 is 33
100 / 4 is 25
100 / 5 is 20
Please note:
result = i != 0 ? 100 / i : 0;
result is assigned the outcome of the division of 100 by i. However, this division takes place only if i
is not zero. When i is zero, a placeholder value of zero is assigned to result. Here is the preceding
program rewritten a bit more efficiently. It produces the same output as before.
Notice the if statement. If i is zero, then the outcome of the if is false, the division by zero is
prevented, and no result is displayed. Otherwise the division takes place.
Riccardo Flask 40 | P a g e
JAVA for Beginners
The switch provides for a multi-way branch. Thus, it enables a program to select among several
alternatives. Although a series of nested if statements can perform multi-way tests, for many
situations the switch is a more efficient approach.
switch(expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
...
default:
statement sequence
The switch expression can be of type char, byte, short, or int. (Floating-point expressions,
for example, are not allowed.)
Frequently, the expression controlling the switch is simply a variable.
The case constants must be literals of a type compatible with the expression.
No two case constants in the same switch can have identical values.
The default statement sequence is executed if no case constant matches the expression.
The default is optional; if it is not present, no action takes place if all matches fail. When a
match is found, the statements associated with that case are executed until the break is
encountered or, in the case of default or the last case, until the end of the switch is reached.
Riccardo Flask 41 | P a g e
JAVA for Beginners
class SwitchDemo {
int i;
switch(i) {
case 0:
System.out.println("i is zero");
break;
case 1:
System.out.println("i is one");
break;
case 2:
System.out.println("i is two");
break;
case 3:
System.out.println("i is three");
break;
case 4:
System.out.println("i is four");
break;
default:
Riccardo Flask 42 | P a g e
JAVA for Beginners
i is zero
i is one
i is two
i is three
i is four
i is five or more
i is five or more
i is five or more
i is five or more
i is five or more
The break statement is optional, although most applications of the switch will use it. When
encountered within the statement sequence of a case, the break statement causes program flow to
exit from the entire switch statement and resume at the next statement outside the switch.
However, if a break statement does not end the statement sequence associated with a case, then all
the statements at and following the matching case will be executed until a break (or the end of the
switch) is encountered. For example,
class NoBreak {
int i;
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
Riccardo Flask 43 | P a g e
JAVA for Beginners
System.out.println();
Output:
Execution will continue into the next case if no break statement is present.
switch(i) {
case 1:
case 2:
break;
break;
Riccardo Flask 44 | P a g e
JAVA for Beginners
Nested switch
switch(ch1) {
switch(ch2) {
case 'A':
break;
break;
Help on:
1. if
2. switch
Choose one:
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.print("Choose one:
Once the selection has been obtained, the display the syntax for the selected statement.
Riccardo Flask 45 | P a g e
JAVA for Beginners
switch(choice) {
case '1':
System.out.println("The if:\
System.out.println("if(condition)
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\
System.out.println("switch(
System.out.println(" case
System.out.println("}");
break;
default:
Complete Listing
/*
Project 3-1
*/
class Help {
throws java.io.IOException {
Riccardo Flask 46 | P a g e
JAVA for Beginners
char choice;
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
default:
Riccardo Flask 47 | P a g e
JAVA for Beginners
Sample run:
Help on:
1. if
2. switch
Choose one: 1
The if:
if(condition) statement;
else statement;
Loops are structures used to make the program repeat one or many instructions for ‘n’ times as
specified in the declaration of the loop.
statement sequence
Initialization = assignment statement that sets the initial value of the loop control variable,
(counter)
Condition = Boolean expression that determines whether or not the loop will repeat
Iteration = amount by which the loop control variable will change each time the loop is
repeated.
Riccardo Flask 48 | P a g e
JAVA for Beginners
Example: using a ‘for’ loop to print the square roots of the numbers between 1 and 99. (It also
displays the rounding error present for each square root).
class SqrRoot {
sroot = Math.sqrt(num);
System.out.println();
‘For’ loop counters (loop control variables) can either increment or decrement,
System.out.println(x);
Riccardo Flask 49 | P a g e
JAVA for Beginners
int i, j;
Expected output:
i and j: 0 10
i and j: 1 9
i and j: 2 8
i and j: 3 7
i and j: 4 6
class ForTest {
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
Riccardo Flask 50 | P a g e
JAVA for Beginners
class Empty {
int i;
class Empty2 {
int i;
Initialising the loop out of the ‘for’ statement is only required when the value needs to be a result of
another complex process which cannot be written inside the declaration.
Riccardo Flask 51 | P a g e
JAVA for Beginners
Infinite Loops
Sometimes one needs to create an infinite loop, i.e. a loop which never ends! (However it can be
stopped using the break statement). An example of an infinite loop declaration is as follows:
for(;;)
// … statements
N.B. Using break to terminate an infinite loop will be discussed later on in the course.
No ‘Body’ Loops
Loops can be declared without a body. This can be useful in particular situations, consider the
following example:
class Empty3 {
Predicted Output:
Sum is 15
Riccardo Flask 52 | P a g e
JAVA for Beginners
class ForVar {
int sum = 0;
int fact = 1;
fact *= i;
Riccardo Flask 53 | P a g e
JAVA for Beginners
The condition could be any valid Boolean expression. The loop will function only if the condition is
true. If false it will move on to the next line of code.
class WhileDemo {
char ch;
ch = 'a';
System.out.print(ch);
ch++;
The above program will output the alphabet. As can be seen in the code the while loop will result
false when the character is greater than ‘z’. The condition is tested at the beginning of the program.
class Power {
int e;
int result;
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
Riccardo Flask 54 | P a g e
JAVA for Beginners
Predicted Output:
2 to the power of 0 is 1
2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
do {
statements;
} while(condition);
Braces are used if there is more than one statements and to improve program readability.
class DWDemo {
throws java.io.IOException {
char ch;
do {
} while(ch != 'q');
Riccardo Flask 55 | P a g e
JAVA for Beginners
class Guess4 {
throws java.io.IOException {
do {
do {
The function ch = (char) System.in.read(); // get a char
of this
} while(ch == '\n' | ch == '\r');
statement is
to skip if(ch == answer) System.out.println("** Right **");
carriage else {
return and line
System.out.print("...Sorry, you're ");
feed
characters if(ch < answer) System.out.println("too low");
System.out.println("Try again!\n");
} while(answer != ch);
Predicted Output:
Try again!
Riccardo Flask 56 | P a g e
JAVA for Beginners
Try again!
** Right **
Riccardo Flask 57 | P a g e
JAVA for Beginners
We are going to work on our previous project. Copy all the code and add the following code:
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while\n");
do {
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
Riccardo Flask 58 | P a g e
JAVA for Beginners
break;
case '3':
System.out.println("The for:\n");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
The default statement has been removed as the loop ensures that a proper response is entered or
else the program will continue to execute.
Complete listing
/*
Project 3-2
*/
class Help2 {
throws java.io.IOException {
char choice;
Riccardo Flask 59 | P a g e
JAVA for Beginners
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while\n");
do {
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition)
statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The for:\n");
Riccardo Flask 60 | P a g e
JAVA for Beginners
System.out.print("for(init; condition;
iteration)");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition)
statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
Riccardo Flask 61 | P a g e
JAVA for Beginners
One can use the ‘break’ command to terminate voluntarily a loop. Execution will continue from the
next line following the loop statements,
class BreakDemo {
public static void main(String args[]) {
int num;
num = 100;
for(int i=0; i < num; i++) {
if(i*i >= num) break; // terminate loop if i*i >= 100
System.out.print(i + " ");
}
System.out.println("Loop complete."); When i = 10, i*i = 100. Therefore
} the ‘if’ condition is satisfied and
}
the loop terminates before i = 100
Expected Output:
0 1 2 3 4 5 6 7 8 9 Loop complete.
class Break2 {
public static void main(String args[])
throws java.io.IOException {
char ch;
for( ; ; ) {
ch = (char) System.in.read(); // get a char
if(ch == 'q') break;
}
System.out.println("You pressed q!");
}
}
In the above program there is an infinite loop, for( ; ; ) . This means that the program will
never terminate unless the user presses a particular letter on the keyboard, in this case ‘q’.
If we have nested loops, i.e. a loop within a loop, the ‘break’ will terminate the inner loop. It is not
recommended to use many ‘break’ statement in nested loops as it could lead to bad programs.
However there could be more than one ‘break’ statement in a loop. If there is a switch statement in
a loop, the ‘break’ statement will affect the switch statement only. The following code shows an
example of nested loops using the ‘break’ to terminate the inner loop;
Riccardo Flask 62 | P a g e
JAVA for Beginners
class Break3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.println("Outer loop count: " + i);
System.out.print(" Inner loop count: ");
int t = 0;
while(t < 100) {
if(t == 10) break; // terminate loop if t is 10
System.out.print(t + " ");
t++;
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Predicted Output:
Programmers refer to this technique as the GOTO function where one instructs the program to jump
to another location in the code and continue execution. However Java does not offer this feature but
it can be implemented by using break and labels. Labels can be any valid Java identifier and a colon
should follow. Labels have to be declared before a block of code, e.g.
class Break4 {
public static void main(String args[]) { One, two and three are
int i; labels
for(i=1; i<4; i++) {
one: {
two: {
three: {
System.out.println("\ni is " + i);
if(i==1) break one;
if(i==2) break two;
if(i==3) break three;
// the following statement is never executed
System.out.println("won't print");
}
Riccardo Flask 63 | P a g e
JAVA for Beginners
Predicted Output:
i is 1
After block one.
i is 2
After block two.
After block one.
i is 3
After block three.
After block two.
After block one.
After for.
Interpreting the above code can prove to be quite tricky. When ‘i’ is 1, execution will break after the
first ‘if’ statement and resume where there is the label ‘one’. This will execute the statement
labelled ‘one’ above. When ‘i’ is 2, this time execution will resume at the point labelled ‘two’ and
hence will also execute the following statements including the one labelled ‘one’.
The following code is another example using labels but this time the label marks a point outside the
loop:
class Break5 {
public static void main(String args[]) {
done:
for(int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
for(int k=0; k<10; k++) {
System.out.println(k);
if(k == 5) break done; // jump to done
}
System.out.println("After k loop"); // skipped
}
System.out.println("After j loop"); // skipped
}
System.out.println("After i loop");
}
}
Riccardo Flask 64 | P a g e
JAVA for Beginners
Predicted Output:
0
1
2
3
4
5
After i loop
The ‘k’ loop is terminated when ‘k’ = 5. However the ‘j’ loop is skipped since the break operation
cause execution to resume at a point outside the loops. Hence only the ‘i’ loop terminates and thus
the relevant statement is printed.
The next example shows the difference in execution taking care to where one puts the label:
class Break6 {
public static void main(String args[]) {
int x=0, y=0;
stop1: for(x=0; x < 5; x++) {
for(y = 0; y < 5; y++) {
if(y == 2) break stop1;
System.out.println("x and y: " + x + " " + y);
}
}
System.out.println();
for(x=0; x < 5; x++)
stop2: {
for(y = 0; y < 5; y++) {
if(y == 2) break stop2;
System.out.println("x and y: " + x + " " + y);
}
}
}
}
In the first part the inner loop stops when ‘y’ = 2. The
Predicted Output: break operation forces the program to skip the outer
x and y: 0 0 ‘for’ loop, print a blank line and start the next set of
x and y: 0 1 loops. This time the label is placed after the ‘for’ loop
declaration. Hence the break operation is only
x and y: 0 0
x and y: 0 1 operating on the inner loop this time. In fact ‘x’ goes
x and y: 1 0 all the way from 0 to 4, with ‘y’ always stopping
x and y: 1 1
x and y: 2 0
when it reaches a value of 2.
x and y: 2 1
x and y: 3 0
x and y: 3 1
x and y: 4 0
x and y: 4 1
Riccardo Flask 65 | P a g e
JAVA for Beginners
The break – label feature can only be used within the same block of code. The following code is an
example of misuse of the break – label operation:
The ‘continue’ feature can force a loop to iterate out of its normal control behaviour. It is regarded
as the complement of the break operation. Let us consider the following example,
class ContDemo {
public static void main(String args[]) {
int i;
for(i = 0; i<=100; i++) {
if((i%2) != 0) continue;
System.out.println(i);
}
}
}
Predicted Output:
100
The program prints on screen the even numbers. This happens since whenever the modulus results
of ‘i’ by 2 are not equal to ‘0’, the ‘continue’ statement forces loop to iterate bypassing the following
statement (modulus refers to the remainder of dividing ‘i’ by 2).
Riccardo Flask 66 | P a g e
JAVA for Beginners
In ‘while’ and ‘do-while’ loops, a ‘continue’ statement will cause control to go directly to the
conditional expression and then continue the looping process. In the case of the ‘for’ loop, the
iteration expression of the loop is evaluated, then the conditional expression is executed, and then
the loop continues.
Continue + Label
It is possible to use labels with the continue feature. It works the same as when we used it before in
the break operation.
class ContToLabel {
public static void main(String args[]) {
outerloop:
for(int i=1; i < 10; i++) {
System.out.print("\nOuter loop pass " + i +
", Inner loop: ");
for(int j = 1; j < 10; j++) {
if(j == 5) continue outerloop;
System.out.print(j);
}
}
}
}
Predicted Output:
Note that the inner loop is allowed to execute until ‘j’ is equal to 5. Then loop is forced to outer loop.
Riccardo Flask 67 | P a g e
JAVA for Beginners
1. Copy all the code from Help2.java into a new file, Help3.java
2. Create an outer loop which covers the whole code. This loop should be declared as infinite but
terminate when the user presses ‘q’ (use the break)
3. Your menu should look like this:
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
System.out.print("Choose one (q to quit): ");
do {
choice = (char) System.in.read();
} while(choice == '\n' | choice == '\r');
} while( choice < '1' | choice > '7' & choice != 'q');
4. Adjust the switch statement to include the ‘break’ and ‘continue’ features.
Complete Listing
class Help3 {
throws java.io.IOException {
char choice;
for(;;) {
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
Riccardo Flask 68 | P a g e
JAVA for Beginners
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
do {
} while( choice < '1' | choice > '7' & choice != 'q');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
Riccardo Flask 69 | P a g e
JAVA for Beginners
System.out.println("The for:\n");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
case '6':
System.out.println("The break:\n");
break;
case '7':
System.out.println("The continue:\n");
break;
System.out.println();
Riccardo Flask 70 | P a g e
JAVA for Beginners
Nested Loops
A nested loop is a loop within a loop. The previous examples already included such loops. Another
example to consider is the following:
class FindFac {
public static void main(String args[]) {
for(int i=2; i <= 100; i++) {
System.out.print("Factors of " + i + ": ");
for(int j = 2; j < i; j++)
if((i%j) == 0) System.out.print(j + " ");
System.out.println();
}
}
}
The above code prints the factors of each number starting from 2 up to 100. Part of the output is as
follows:
Factors of 2:
Factors of 3:
Factors of 4: 2
Factors of 5:
Factors of 6: 2 3
Factors of 7:
Factors of 8: 2 4
Factors of 9: 3
Factors of 10: 2 5
…
Can you think of a way to make the above code more efficient? (Reduce the number of iterations in
the inner loop).
Riccardo Flask 71 | P a g e
JAVA for Beginners
Class Fundamentals
Definition
A class is a sort of template which has attributes and methods. An object is an instance of a class,
e.g. Riccardo is an object of type Person. A class is defined as follows:
class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}
The classes we have used so far had only one method, main(), however not all classes specify a main
method. The main method is found in the main class of a program (starting point of program).
class Vehicle {
int passengers; //number of passengers
int fuelcap; //fuel capacity in gallons
int mpg; //fuel consumption
}
Please note that up to this point there is no OBJECT. By typing the above code a new data type is
created which takes three parameters. To create an instance of the Vehicle class we use the
following statement:
Riccardo Flask 72 | P a g e
JAVA for Beginners
class VehicleDemo {
int range;
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
Till now we have created an instance of Vehicle called ‘minivan’ and assigned values to passengers,
fuel capacity and fuel consumption. Let us add some statements to work out the distance that this
vehicle can travel with a tank full of fuel:
class TwoVehicles {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
Riccardo Flask 73 | P a g e
JAVA for Beginners
Creating Objects
In the previous code, an object was created from a class. Hence ‘minivan’ was an object which was
created at run time from the ‘Vehicle’ class – vehicle minivan = new Vehicle( ) ; This statement
allocates a space in memory for the object and it also creates a reference. We can create a
reference first and then create an object:
We have created a new instance of type Vehicle named car1. However note that car2 is NOT
another instance of type Vehicle. car2 is the same object as car1 and has been assigned the same
properties,
System.out.println(car1.mpg);
System.out.println(car2.mpg);
Riccardo Flask 74 | P a g e
JAVA for Beginners
car1 and car2 are not linked. car2 can be re-assigned to another data type:
car2 = car3; // now car2 and car3 refer to the same object.
Methods
Methods are the functions which a particular class possesses. These functions usually use the data
defined by the class itself.
class Vehicle {
void range() {
Note that ‘fuelcap’ and ‘mpg’ are called directly without the dot (.) operator. Methods take the
following general form:
// body of method
‘ret-type’ specifies the type of data returned by the method. If it does not return any value we write
void. ‘name’ is the method name while the ‘parameter-list’ would be the values assigned to the
variables of a particular method (empty if no arguments are passed).
class AddMeth {
Riccardo Flask 75 | P a g e
JAVA for Beginners
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
}
}
void myMeth() {
int i;
System.out.println();
}
}
Riccardo Flask 76 | P a g e
JAVA for Beginners
Hence the method will exit when it encounters the return statement or the closing curly bracket ‘ } ‘
There can be more than one exit point in a method depending on particular conditions, but one
must pay attention as too many exit points could render the code unstructured and the program will
not function as desired (plan well your work).
void myMeth() {
// ...
if(done) return;
// ...
if(error) return;
Returning a Value
Most methods return a value. You should be familiar with the sqrt( ) method which returns the
square root of a number. Let us modify our range method to make it return a value:
class Vehicle {
int range() {
Please note that now our method is no longer void but has int since it returns a value of type
integer. It is important to know what type of variable a method is expected to return in order to set
the parameter type correctly.
Riccardo Flask 77 | P a g e
JAVA for Beginners
Main program:
class RetMeth {
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
range1 = minivan.range();
range2 = sportscar.range();
Study the last two statements, can you think of a way to make them more efficient, eliminating the
use of the two statements located just above them?
Riccardo Flask 78 | P a g e
JAVA for Beginners
// Using Parameters.
The method accepts a
class ChkNum { value of type integer, the
parameter is x, while the
// return true if x is even argument would be any
value passed to it
boolean isEven(int x) {
class ParmDemo {
Predicted Output:
10 is even.
8 is even.
A method can accept more than one parameter. The method would be declared as follows:
// ...
Riccardo Flask 79 | P a g e
JAVA for Beginners
class Factor {
class IsFact {
Predicted Output:
2 is a factor.
If we refer back to our ‘vehicle’ example, we can now add a method which works out the fuel
needed by a particular vehicle to cover a particular distance. One has to note here that the result of
this method, even if it takes integers as parameters, might not be a whole number.
Therefore one has to specify that the value that the method returns, in this case we can use
‘double’:
Riccardo Flask 80 | P a g e
JAVA for Beginners
class Vehicle {
int range() {
Main Program:
class CompFuel {
double gallons;
minivan.passengers = 7;
Riccardo Flask 81 | P a g e
JAVA for Beginners
minivan.fuelcap = 16;
minivan.mpg = 21;
sportscar.passengers = 2;
sportscar.fuelcap = 14;
sportscar.mpg = 12;
gallons = minivan.fuelneeded(dist);
Predicted Output:
Riccardo Flask 82 | P a g e
JAVA for Beginners
In order to carry out this task we must examine the Help3.java and identifies ways how we can break
down the code into classes and methods. The code can be broken down as follows:
Method helpon( )
void helpon(int what) {
switch(what) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The for:\n");
System.out.println(" statement;");
break;
Riccardo Flask 83 | P a g e
JAVA for Beginners
case '4':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
case '6':
System.out.println("The break:\n");
break;
case '7':
System.out.println("The continue:\n");
break;
System.out.println();
Method showmenu( )
void showmenu() {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
Riccardo Flask 84 | P a g e
JAVA for Beginners
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
Method isvalid( )
Class Help
class Help {
switch(what) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
Riccardo Flask 85 | P a g e
JAVA for Beginners
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The for:\n");
System.out.print("for(init; condition;
iteration)");
System.out.println(" statement;");
break;
case '4':
System.out.println("The while:\n");
System.out.println("while(condition)
statement;");
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
break;
case '6':
System.out.println("The break:\n");
break;
case '7':
System.out.println("The continue:\n");
Riccardo Flask 86 | P a g e
JAVA for Beginners
System.out.println("continue; or continue
label;");
break;
System.out.println();
void showmenu() {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. for");
System.out.println(" 4. while");
System.out.println(" 5. do-while");
System.out.println(" 6. break");
System.out.println(" 7. continue\n");
Main Program:
class HelpClassDemo {
throws java.io.IOException {
char choice;
Riccardo Flask 87 | P a g e
JAVA for Beginners
for(;;) {
do {
hlpobj.showmenu();
do {
} while( !hlpobj.isvalid(choice) );
System.out.println("\n");
hlpobj.helpon(choice);
Constructors
In previous examples when working with the vehicle class we did assign values to the class variables
by using statements like: minivan.passengers = 7;
To accomplish this task Java programmers use constructors. A constructor is created by default and
initializes all member variables to zero. However we can create our constructors and set the values
the way we want, e.g.
class MyClass {
int x;
MyClass() {
This is the constructor
x = 10;
Riccardo Flask 88 | P a g e
JAVA for Beginners
class ConsDemo {
Predicted Output:
10 10
MyClass(int i) {
x = i;
If we edit the main program, by changing the statements which initiate the two objects:
10 88
The values 10 and 88 are first passed on to ‘i’ and then are assigned to ‘x’.
passengers = p;
fuelcap = f;
mpg = m;
Riccardo Flask 89 | P a g e
JAVA for Beginners
class VehConsDemo {
double gallons;
gallons = minivan.fuelneeded(dist);
gallons = sportscar.fuelneeded(dist);
Method Overloading
class Overload {
void ovlDemo() {
System.out.println("No parameters");
void ovlDemo(int a) {
Riccardo Flask 90 | P a g e
JAVA for Beginners
return a + b;
return a + b;
Main Program:
class OverloadDemo {
int resI;
double resD;
ob.ovlDemo();
System.out.println();
ob.ovlDemo(2);
System.out.println();
Riccardo Flask 91 | P a g e
JAVA for Beginners
resI);
System.out.println();
Predicted Output:
No parameters
One parameter: 2
Two parameters: 4 6
class Overload2 {
void f(int x) {
void f(double x) {
Riccardo Flask 92 | P a g e
JAVA for Beginners
Main Program:
class TypeConv {
int i = 10;
double d = 10.1;
byte b = 99;
short s = 10;
float f = 11.5F;
Predicted Output:
Inside f(int): 10
Inside f(int): 99
Inside f(int): 10
Even though “f” had been defined with two parameters, ‘int’ and ‘double’, it is possible to pass a
different data type and automatic conversion occurs. ‘byte’ and ‘short’ are converted to ‘int’ while
‘float’ is converted to ‘double’ and the respective methods are called.
Riccardo Flask 93 | P a g e
JAVA for Beginners
Overloading Constructors
// Overloading constructors.
class MyClass {
int x;
MyClass() {
System.out.println("Inside MyClass().");
x = 0;
MyClass(int i) {
System.out.println("Inside MyClass(int).");
x = i;
MyClass(double d) {
System.out.println("Inside MyClass(double).");
x = (int) d;
MyClass(int i, int j) {
x = i * j;
Main Program:
class OverloadConsDemo {
Riccardo Flask 94 | P a g e
JAVA for Beginners
Predicted Output:
Inside MyClass().
Inside MyClass(int).
Inside MyClass(double).
t1.x: 0
t2.x: 88
t3.x: 17
t4.x: 8
class Summation {
int sum;
Summation(int num) {
sum = 0;
sum += i;
Riccardo Flask 95 | P a g e
JAVA for Beginners
Summation(Summation ob) {
sum = ob.sum;
Main Program:
class SumDemo {
Predicted Output:
s1.sum: 15
s2.sum: 15
In the above example, when s2 is constructed, it takes the value of the summation of s1. Hence
there is no need to recompute the value.
class MyClass {
Riccardo Flask 96 | P a g e
JAVA for Beginners
*/
void setAlpha(int a) {
alpha = a;
int getAlpha() {
return alpha;
Main Program:
class AccessDemo {
ob.setAlpha(-99);
ob.beta = 88;
ob.gamma = 99;
Riccardo Flask 97 | P a g e
JAVA for Beginners
class FailSoftArray {
a = new int[size];
errval = errv;
length = size;
return errval;
if(ok(index)) {
a[index] = val;
return true;
return false;
Riccardo Flask 98 | P a g e
JAVA for Beginners
return false;
Main Program:
class FSDemo {
int x;
System.out.println("Fail quietly.");
fs.put(i, i*10);
x = fs.get(i);
System.out.println("");
if(!fs.put(i, i*10))
x = fs.get(i);
else
Riccardo Flask 99 | P a g e
JAVA for Beginners
Predicted Output:
Index 5 out-of-bounds
Index 6 out-of-bounds
Index 7 out-of-bounds
Index 8 out-of-bounds
Index 9 out-of-bounds
0 10 20 30 40 Index 5 out-of-bounds
Index 6 out-of-bounds
Index 7 out-of-bounds
Index 8 out-of-bounds
Index 9 out-of-bounds
Arrays
An array can be defined as a collection of variables of the same type defined by a common name,
e.g. an array called Names which stores the names of your class mates:
Arrays in Java are different from arrays in other programming languages because they are
implemented as objects.
One-dimensional Arrays
The following code creates an array of ten integers, fills it up with numbers using a loop and then
prints the content of each location (index) of the array:
class ArrayDemo {
int i;
sample[i] = i;
sample[i]);
Predicted Output:
This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9
The following program contains two loops used to identify the smallest and the largest value stored
in the array:
class MinMax {
nums[0] = 99;
nums[1] = -10;
nums[2] = 100123;
nums[3] = 18;
nums[4] = -978;
nums[5] = 5623;
nums[6] = 463;
nums[7] = -9;
nums[8] = 287;
nums[9] = 49;
Predicted Output:
class Bubble {
int a, b, t;
int size;
System.out.println();
// exchange elements
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
System.out.println();
Predicted Output:
Two-Dimensional Arrays:
This would create a table made up of 10 rows (index: 0 to 9) and 20 columns (index: 0 to 19). The
following code creates a table, 3 rows by 4 columns, and fills it up woth numbers from 1 to 12. Note
that at index [0][0] = 1, [0][1] = 2, [0][2] = 3, [0][3] = 4, [1][0] = 5, etc.
class TwoD {
int t, i;
table[t][i] = (t*4)+i+1;
System.out.println();
The square brackets follow the type specifier, not the name of the array variable. For example, the
following two declarations are equivalent:
This alternative declaration form offers convenience when declaring several arrays at the same time.
This creates three array variables of type int. It is the same as writing:
The alternative declaration form is also useful when specifying an array as a return type for a
method:
Array References:
Consider a particular array, nums1, and another array, nums2 and at one point in the code we assign
one array reference to the other, i.e. nums2 = nums1. Then every action on nums2 will be as if it
were on nums1 (nums2 reference is lost).
class AssignARef {
int i;
nums1[i] = i;
nums2[i] = -i;
System.out.println();
System.out.println();
System.out.println();
Riccardo Flask 106 |
Page
JAVA for Beginners
nums2[3] = 99;
System.out.println();
Predicted Output:
Here is nums1: 0 1 2 3 4 5 6 7 8 9
Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
This variable automatically keeps track of the number of items an array can hold and NOT the actual
items. When an array is declared to have ten items, even if one does not put actual data, the length
of the array is 10. Something to keep in mind is also when dealing with two dimensional arrays. As
already explained in the theory lessons, two dimensional arrays are considered to be an array of
arrays. Hence calling up the length of such array would return the number of sub-arrays. To access
the length of the particular sub-array, one has to write the ‘row’ index, e.g. arrayname [0].length
class LengthDemo {
int nums[] = { 1, 2, 3 };
Riccardo Flask 107 |
Page
JAVA for Beginners
};
System.out.println();
list[i] = i * i;
System.out.println();
Predicted Output:
length of list is 10
length of nums is 3
length of table is 3
length of table[0] is 3
length of table[1] is 2
length of table[2] is 4
Here is list: 0 1 4 9 16 25 36 49 64 81
Using the Length to copy elements from one array to another while previously checking for size to
prevent errors:
//copying an array
class ACopy {
int i;
nums1[i] = i;
nums2[i] = nums1[i];
Data structures are used to organize data. Arrays can be used to create Stacks and Queues. Imagine
a stack to be a pile of plates. Stacks implement a Last In First Out system (LIFO). Queues use a First In
First Out order (FIFO). We can implement this as a class and also two methods to PUT and GET data
to and from a queue. Therefore we put items at the end of the queue and get items from the front.
Once a data item is retrieved, it cannot be retrieved again (consumptive). A queue can also be full or
empty. The following code creates a noncircular queue (does not reuse locations once they are
emptied).
class Queue {
Queue(int size) {
putloc = getloc = 0;
if(putloc==q.length-1) {
return;
putloc++;
q[putloc] = ch;
char get() {
if(getloc == putloc) {
return (char) 0;
Riccardo Flask 110 |
Page
JAVA for Beginners
getloc++;
return q[getloc];
// MAIN PROGRAM
class QDemo {
char ch;
int i;
ch = bigQ.get();
System.out.println("\n");
System.out.println();
System.out.println();
ch = smallQ.get();
Predicted Output:
Attempting to store Z
Attempting to store Y
Attempting to store X
Attempting to store W
The type of itr-var should be similar or compatible to the type of the data items held in the array.
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
Enhanced:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Sample program:
class ForEach {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums) {
sum += x;
Predicted Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55
Strings
The string data type defines is used in Java to handle character strings. It is important to note that in
Java, strings are Objects. Every time we write an output statement, the characters we enclose within
the quotes are automatically turned into a String object,
System.out.println(“Hello World”);
// Introduce String.
class StringDemo {
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
Predicted Output:
class StrOps {
String str1 =
char ch;
System.out.print(str1.charAt(i));
System.out.println();
if(str1.equals(str2))
else
if(str1.equals(str3))
else
result = str1.compareTo(str3);
if(result == 0)
else
idx = str2.indexOf("One");
idx = str2.lastIndexOf("One");
}
Riccardo Flask 116 |
Page
JAVA for Beginners
Predicted Output:
Length of str1: 45
String Arrays
class StringArrays {
for(String s : strs)
System.out.println("\n");
// change a string
strs[1] = "was";
for(String s : strs)
Predicted Output:
Original array:
This is a test.
Modified array:
Strings are said to be ‘immutable’, i.e. they cannot be changed once they are created. However we
can use the method substring() to capture part of a string. The method is declared as follows:
Example:
// Use substring().
class SubStr {
// construct a substring
Note:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
J a v a m a k e s t h e W e b m o v e .
Predicted Output:
Understanding the “public static void main(String args[])” line of code – FYI only
This line really represents a method call, main, having ‘args’ (a string array) as parameter. This array
stores command-line arguments (CLI arguments), which is any information which follows the
program name. Consider the following examples:
Example 1:
class CLDemo {
If we execute this program in a DOS shell3 (not via IDE), we use the following syntax:
3
Put your file (*.class, after compilation) in root drive. Then Start > Run > cmd
Riccardo Flask 119 |
Page
JAVA for Beginners
They are:
arg[0]: one
arg[1]: two
arg[2]: three
Example 2:
class Phone {
String numbers[][] = {
{ "Tom", "555-3322" },
{ "Mary", "555-8976" },
{ "Jon", "555-1037" },
{ "Rachel", "555-1400" }
};
int i;
if(args.length != 1)
Riccardo Flask 120 |
Page
JAVA for Beginners
else {
if(numbers[i][0].equals(args[0])) {
numbers[i][1]);
break;
if(i == numbers.length)
Mary: 555-8976
vector.set( i, object );
vector.setElementAt( object, i );
Object o = vector.get( i );
Object o = vector.elementAt( i );
Object o = vector.getElementAt( i );
vector.add ( o );
vector.addElement( o );
As already stated in the previous page ArrayList have replaced Vector in versions of Java following
1.1. ArrayList are much faster than Vector. You can add items to an ArrayList either at a particular
index, ‘i', or simply at the end of the list. The methods used are as follows:
arrayList.add( object );
If one tries to add an element to a list, and this operation results in an error one would get an
ArrayIndexOutOfBoundsException. Possible sources of error include:
arrayList.remove( i, object );
To remove an item at an unknown index, one must first search for it (better if list is sorted). To
remove elements from the entire list one must work backwards since the list shrinks as we go.
arrayList.remove(i);
else
break;
To remove undesirable elements from the head end of a list one has to work forwards without
incrementing, always working on element 0. The list shrinks as we go.
arrayList.remove(0);
Riccardo Flask 123 |
Page
JAVA for Beginners
else
break;
To delete the last ‘n’ elements from the list one can use the following:
arrayList.setSize( arrayList.size() - n );
Once all the unwanted items have been removed, unless the list will grow again, it is best to use the
method ArrayList.trimToSize(). One has to note that some programmers prefer to convert ArrayLists
into arrays to perform certain functions as it is much faster. Once done the arrays can be converted
back to ArrayLists.
Sample code:
import java.util.ArrayList;
public class AraryListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
System.out.print("Initial size of al : " + al.size());
System.out.print("\n");
Predicted Output:
size of al after 7
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}
EmpID = i++;
Ename = ename;
Sal = sal;
}
ComparableDemo.java
import java.util.*;
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}
}
Predicted Output:
EmpID 1
Ename Harry
Sal20000.0
EmpID 0
Ename Tom
Sal40000.0
EmpID 2
Ename Maggie
Sal50000.0
EmpID 3
Ename Chris
Sal70000.0
The following is another example of sorting. Please note that this code is being presented for
reference. The term package is used to group related pieces of a program together. All the related
classes will be stored in a sort of folder:
package test;
import java.util.*;
String name;
int age;
long income;
this.name = name;
this.age = age;
this.name = name;
this.age = age;
this.income=income;
return name;
return age;
return getName().compareTo(((Farmer)o).getName());
Farmer p1 = (Farmer)o1;
Farmer p2 = (Farmer)o2;
else
return (int)(p1.getIncome() -
p2.getIncome());
Collections.sort(farmer);
System.out.println("t" + farmer);
Collections.sort(farmer,
Collections.reverseOrder());
System.out.println("t" + farmer);
System.out.println("t" + farmer);
System.out.println("t" + farmerIncome);
return income;
}
Riccardo Flask 130 |
Page
JAVA for Beginners
this.income = income;
this.age = age;
this.name = name;
Predicted Output:
import java.util.*;
4
Scanner is part of the java.util package and can be used for input (keyboard/file)
Riccardo Flask 131 |
Page
JAVA for Beginners
//creating instance
//read integer
int x = kb.nextInt();
import java.util.*;
while (in.hasNext()) {
words.add(in.next());
Collections.sort(words);
System.out.println("\n\nSorted words\n");
System.out.println(word);
Using the Scanner is the most suggested method compared to the Keyboard Class or the
System.in.read . Remember that the Keyboard class was created by you (or given) and is not a
standard in Java.
Through file handling, we can read data from and write data to files besides doing all sorts of other
operations. Java provides a number of methods for file handling through different classes which are
a part of the “java.io” package. The question can arise in the mind of a new programmer as to why
file-handling is required. The answer of this question would be in two parts, why do we need to read
data from the files and why do we need to save it (write it) to a file.
To answer the first part, Let us suppose that we have a very large amount of data which needs to be
input into a program, Something like a 1000 records, If we start inputting the data manually and
while we are in half-way through the process, there is a power-failure, then once power is restored,
the entire data has to be input again. This would mean a lot of extra work, an easier approach would
be to write all the records in a file and save the file after writing 10 or so records, in this case even if
there is a power-failure, only some records would be lost and once power is restored, there would
be only a few records that would need to be input again. Once all the records are saved in that file,
the file-name can be passed to the program, which can then read all the records from the file.
For the second part, consider a system which needs to record the time and name of any error that
occurs in the system, this can be achieved through saving the data into a file and the administrator
can view the file any time he/she wishes to view it.
Note that if you use a “/” in a path definition in Java in Windows, the path would still resolve
correctly and if you use the Windows conventional “\”, then you have to place two forward slashes
“\\” as a single “\” would be taken as an escape-sequence.
import java.io.*;
String s;
if(f1.exists())
if(f1.isFile())
System.out.println("File Name is
"+f1.getName());
s=f1.getParent();
f1.renameTo(new File("Folder/abc"));
f2.delete();
if (f3.isDirectory())
System.out.println(f2.getPath());
else
System.out.println("Not a File");
Folder
If successfully run , the ” FILE ” file inside the folder ” Folder ” will be renamed to ” abc ” and the ”
FILE1 ” file will be deleted.
Here is an example of a program that reads its own first six bytes, we have:
//0123
import java.io.*;
int s=6;
try
FileInputStream f = new
FileInputStream("read.java");
b[i] = f.read();
System.out.print(b[i]+" ");
System.out.println("nnFirst 6 Bytes as
characters :");
System.out.print(c[i]);
catch (Exception e)
System.out.println("Error");
Predicted Ouptut:
47 47 48 49 50 51
//0123
Notice that the FileInputStream object is created inside a try-catch block since if the specified-file
does not exist, an exception is raised. In the same way to write data to a file byte-by-byte, we have:
import java.io.*;
{
Riccardo Flask 137 |
Page
JAVA for Beginners
String s="Hello";
byte b[]=s.getBytes();
int i=0;
f.write(b[i]);
i++;
If the file called file.txt does not exist, it is automatically created. If we place a true in the constructor
for the FileOutputStream, then the file would be opened in append mode.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class _______________ {
throws FileNotFoundException {
________ = diskScanner.nextInt();
________ = diskScanner.nextDouble();
________ = diskScanner.nextLine();
________ = diskScanner.findInLine(“.”).charAt(0);
// etc
The following program reads item from a file on disk. You have to create the file using a text editor
(MS Notepad), and save the file in the same location as your classes. You can use the following
examples for the riddles file (save the file as riddles.txt):
An embarrassed zebra
A newspaper
LOGARITHM
Program Code:
question = q;
answer = a;
return question;
return answer;
Main Program:
import java.io.*;
import java.util.Scanner;
try
fileScan = fileScan.useDelimiter("\r\n");
} catch (IOException e)
{ e.printStackTrace();
} // catch()
} // RiddleFileReader() constructor
if (fileScan.hasNext())
ques = fileScan.next();
if (fileScan.hasNext())
{ ans = fileScan.next();
} // if
return theRiddle;
} // readRiddle()
{ System.out.println(aRiddle.getQuestion());
System.out.println(aRiddle.getAnswer());
System.out.println();
} // displayRiddle()
{ RiddleFileReader rfr =
new RiddleFileReader("riddles.txt");
{ rfr.displayRiddle(riddle);
riddle = rfr.readRiddle();
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class _______________ {
throws FileNotFoundException {
PrintStream diskWriter =
new PrintStream(“___________”);
diskWriter.print(_____);
diskWriter.println(_____);
// Etc.
Java GUIs were built with components from the Abstract Window Toolkit (AWT) in package
java.awt. When a Java application with an AWT GUI executes on different Java platforms, the
application's GUI components display differently on each platform. Consider an application that
displays an object of type Button (package java.awt). On a computer running the Microsoft
Windows operating system, the Button will have the same appearance as the buttons in other
Windows applications. Similarly, on a computer running the Apple Mac OS X operating system, the
Button will have the same look and feel as the buttons in other Macintosh applications.
Swing GUI components allow you to specify a uniform look-and-feel for your application across all
platforms or to use each platform's custom look-and-feel. An application can even change the look-
and-feel during execution to enable users to choose their own preferred look-and-feel. Swing
components are implemented in Java, so they are more portable and flexible than the original Java
GUI components from package java.awt, which were based on the GUI components of the
underlying platform. For this reason, Swing GUI components are generally preferred.
Swing advantages:
Swing is faster.
Swing is more complete.
Swing is being actively improved.
AWT advantages:
AWT is supported on older, as well as newer, browsers so Applets written in AWT will run on
more browsers.
The Java Micro-Edition, which is used for phones, TV set top boxes, PDAs, etc, uses AWT, not
Swing.
1. First we have to import all classes in the javax.swing package, although we use only the
JFrame class in the following example. "Windows" are implemented by the JFrame class.
2. Make the application quit when the close box is clicked.
3. After the window has been constructed in memory, display it on the screen. The setVisible
call also starts a separate thread to monitor user interaction with the interface.
4. When we are finished setting up and displaying the window, don't call System.exit(0). We
don't want to stop the program. Although main returns, execution continues because the
call to setVisible(true) created another execution thread, A GUI program builds the user
interface, then just "goes to sleep" until the user does something.
import javax.swing.*;
class FirstWindow {
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
The window created can be resized and dragged around. One can also minimize, maximize or close
the window. Now that we created a window we can set the text which appears in the title bar:
import javax.swing.*;
window.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
public MyWindow3 () {
content.setLayout(new FlowLayout());
content.add(greeting);
setContentPane(content);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
import java.awt.*;
import javax.swing.*;
public DogYears() {
content.add(_dogYearsTF);
content.add(convertBtn);
content.add(_humanYearsTF);
pack();
setLocationRelativeTo(null);
window.setVisible(true);
The final touch to our application is to set the action to perform while the user interacts with the
application:
import java.awt.*;
import javax.swing.*;
public DogYears2() {
convertBtn.addActionListener(new ConvertBtnListener());
_dogYearsTF.addActionListener(new ConvertBtnListener());
_humanYearsTF.setEditable(false);
content.setLayout(new FlowLayout());
content.add(_dogYearsTF);
content.add(convertBtn);
content.add(_humanYearsTF);
setContentPane(content);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_humanYearsTF.setText("" + humanYears);
window.setVisible(true);