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 -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. \u (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 , hence when we increment ‘ch’, we get character
number , 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