Lecture 4: Basics of Java

brazilianchubbySoftware and s/w Development

Jun 8, 2012 (5 years and 4 months ago)

286 views

Lecture 4:Basics of Java
Doina Precup
With many thanks to Prakash Panagaden and Mathieu Blanchette
September 12,2011
Today we turn our attention to Java,a state-of-art programming language that is easy to learn
and use (because,as we will see,it has many built-in checks which aim to help in writing correct
programs).For those who know C and C++,Java syntax is very similar.However,there are
important differences,especially in terms of memory management.
1 Creating and running Java programs
In class and assignments,we will be writing Java programs (i.e.source code).You can edit a
programin any plain text editor,or you can use a development environment (e.g.Eclipse,NetBeans
etc.).Once you have the source code,it needs to be translated into a language that is more directly
understandable by the computer.This process is called compilation.The program javac allows
you to translate the java source code into a representation called Java byte code.The byte code
represents one of the reasons why Java is so popular:it is independent of the architecture of the
computer you have at hand and the operating system.This feature made Java a perfect choice for
Internet programming,since byte code snippets can be embedded in a web page and can execute
on any machine.Byte code is interpreted by the Java Virtual Machine (JVM);because of this
step,Java code runs slightly slower (usually) than C or C++ code.The process looks as follows:
1
L
e
c
t
u
r
e

3


B
a
s
i
c
s

o
f

J
a
v
a
J
a
v
a

v
s

o
t
h
e
r

p
r
o
g
r
a
m
m
i
n
g

l
a
n
g
u
a
g
e
s

B
a
s
i
c

s
y
n
t
a
x

v
e
r
y

s
i
m
i
l
a
r

t
o

C
,

C
+
+

F
u
l
l
y

o
b
j
e
c
t
-
o
r
i
e
n
t
e
d
:

a
l
l

c
o
d
e

a
n
d

d
a
t
a

i
s

w
i
t
h
i
n

a

c
l
a
s
s

J
a
v
a

h
i
d
e
s

m
e
m
o
r
y

m
a
n
a
g
e
m
e
n
t

f
r
o
m

p
r
o
g
r
a
m
m
e
r
:

n
o

m
a
l
l
o
c
,

n
o

f
r
e
e
!

N
o

p
o
i
n
t
e
r
s
,

n
o

s
e
g
m
e
n
t
a
t
i
o
n

f
a
u
l
t
s
!
!

E
a
s
y

t
o

l
e
a
r
n

a
n
d

u
s
e
C
o
m
p
i
l
i
n
g

i
n

J
a
v
a
J
a
v
a

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e
a
n
i
n
g
f
u
l

n
a
m
e
s

f
o
r

m
e
t
h
o
d
s

a
n
d

v
a
r
i
a
b
l
e
s
.

S
t
i
c
k

t
o

y
o
u
r

c
o
n
v
e
n
t
i
o
n
.

e
.
g
.

i
n
t
n
b
S
i
d
e
s
;
g
e
t
P
l
a
y
e
r
s
L
i
s
t
(
m
o
n
t
r
e
a
l
E
x
p
o
s
)

A
d
d

t
e
x
t

t
o

c
l
a
r
i
f
y

a
n
y

p
i
e
c
e

o
f

c
o
d
e

w
h
o
s
e

f
u
n
c
t
i
o
n

i
s

n
o
t

o
b
v
i
o
u
s

G
i
v
e

a

s
h
o
r
t

d
e
s
c
r
i
p
t
i
o
n

o
f

e
a
c
h

m
e
t
h
o
d
:


w
h
a
t

d
o
e
s

i
t

d
o
?


w
h
a
t

a
r
g
u
m
e
n
t
s

d
o
e
s

i
t

e
x
p
e
c
t
?


w
h
a
t

a
s
s
u
m
p
t
i
o
n
s

a
r
e

m
a
d
e
?

w
h
a
t

d
o
e
s

i
t

r
e
t
u
r
n
?

S
i
d
e
-
e
f
f
e
c
t
s
?

D
o

n
o
t

o
v
e
r
c
o
m
m
e
n
t
!

W
h
y
?

M
a
k
e
s

r
e
-
u
s
e

e
a
s
i
e
r

(
e
v
e
n

f
o
r

y
o
u
!
)

M
a
k
e
s

f
i
n
d
i
n
g

a
n
d

s
o
l
v
i
n
g

b
u
g
s

e
a
s
i
e
r

A
l
l
o
w
s

o
t
h
e
r
s

t
o

u
s
e

y
o
u
r

c
o
d
e

E
a
s
i
e
r

t
o

c
o
n
v
i
n
c
e

y
o
u
r

b
o
s
s

(
o
r

T
A
!
)

t
h
a
t

y
o
u
r

c
o
d
e

i
s

w
o
r
k
i
n
g

E
a
s
i
e
r

t
o

a
n
a
l
y
z
e

t
h
e

e
f
f
i
c
i
e
n
c
y

o
f

t
h
e

s
o
l
u
t
i
o
n
To compile in a Linux environment (used in the labs) directly,you use to command:
javac [options] filename.java
The options allow you to specify various extra information,such as files that would need to be
recompiled,where files might be found,etc.(we will introduce themas needed).
After compilation,a file with name filename.class is created;this contains the Java byte code.
To run,use the command:
1
java [options] filename.java
from the directory of your file (again,we will discuss later how to specify where files might be
found).
2 The first program
Java is a fully object-oriented programming language,so all code and data has to be inside some
class.Any code that you might want to execute needs (in some class) a method called main,which
is the first one to be called.As a first example,consider the file Welcome.java,which simply prints
a message.Note that the “header” of the main method (i.e.the way we declare it) will be the same
for all programs.The statement:
System.out.println(“Welcome to COMP-250”);
prints the string:
Welcome to COMP-250
on the screen.This is actually calling a standard method defined in a library;we will talk more
about this use of pre-existing code soon.
Note that all statements end with “;”.Blocks of code are delimited by “f” and “g”.Comments
can be delimited with “/*” and “*/”,or,if they only take one line,they have to be prefaced with
“//”,as in:
//This is a comment
Comments are extremely important in well-written code,because they make it clear,which means
that it will be easier to debug and use,both by yourself and by others.You do not have to over-
comment,especially when the code is obvious.But it is useful,for example,to give a description
of any non-trivial method:
 What arguments does it expect?
 Are there any assumptions about the arguments (e.g.they have to be positive...)
 What does it do?
 What does it return?
 Does it have any “side effects”?E.g.does it change something in a data base,file,print to
screeen etc...
3 Variables and primitive types
You can think of a variable as a “container” that can hold a particular kind of value.A variable
has:
 A name,by which we can refer to it
 A type,which specifies what kinds of values it can hold
 A value,which can be changed during the course of the program.
2
For example:
int i = 5;
declares a variable called i,of type integer (keyword int in Java),and initializes it to 5.Note that a
variable has to be declared before it is initialized.However,not all declarations have to be made
at the beginning of the code - variables can be declared as needed.
In this lecture,we consider primitive (i.e.basic,pre-defined) types which are:charachers
(char),integer (int and long),reals (double and float) and booleans (boolean).Next time we will
talk about defining our own types.
Internally,a variable of a primitive type is associated with a particular memory location,in
which the value of the variable is stored.The mapping between variables and memory locations
is computed internally;you will find out more about this process in COMP-273.The value of a
variable (no matter what its type) is represented in memory through a set of bits (i.e.0s and 1s).
For example,consider the number 14.We can re-write it as:
14 = 1  2
3
+1  2
2
+1  2
1
+0  2
0
so its binary representation will be 1110.A character will be associated with a fixed binary code
(typically,characters are encoded using unicode),A real-valued number will be represented in
exponential form,e.g.1023 = 0:102310
4
.Internally,the exponent 4 and the part after the decimal
point (0.1023) will be stored separately.We will discuss later the details of these representations.
For now,the important thing to remember that each value is converted into a fixed number of bits.
This means,for example,that we cannot represent any arbitrary real number,and that the range of
integers or reals that can be represented is limited.The Java tutorial linked from the course web
page has details on the exact ranges of different variable types.
An assignment is an instruction that gives a value to a variable;it can be done when the
variable is declared,as well as at any other point after the declaration.Note that you must initialize
a variable before trying to use its value,otherwise you will get a compilation error.When you
make an assignment of the form:
j=i;
the value of variable i is copied into the memory location corresponding to variable j.Subsequent
assignments to i will not change the value of j.
Java allows you to use all the regular arithmetic operations on integers and reals.Additionally,
++ and  can be used for addition and subtraction by 1.For boolean variables,the operators
!,&& and k are used for not,logical “and” and “logical or” (if you do not know what these are,
please ask).
Several examples of variable declarations and assignments,as well as basic operations on vari-
ables,are given in the TestVariables.java file.I encourage you to experiment with the code you are
provided and see what happens (e.g.by commenting/uncommenting parts of it,adding variables
etc.
You can use a more specific type instead of a more general type without any problem,e.g.:
int i = 5;
double x = i;
In order to convert a more general type to a more specific one (or types that are not directly
comparable,like char and int),you need to do a specific type casting.This is because the conver-
sion can cause you to lose information,and Java wants to make sure you are aware of that.For
3
example,suppose that you are converting a double to an int.The double may have decimals,which
cannot be kept in an int.Instead,Java will do a truncation.So,to make you aware,you will need
to explicitly cast.If you try the following:
int i;
double x = 4.6;
i=x;
you will get a compilation error,alerting you that i and x are not of compatible type.Instead,you
need to say:
i = (int)x;
In this case,the value of x will be truncated (i.e.the decimals are thrown out),and the value 4 is
stored in i.
Note also that if you try to divide two int variables,you will obtain the result of integer division
- even if you are assigning the result to a double variable!If this is not what you intend,you
have to cast one of the int as a double,then the results will be double.In general,with arithmetic
operations,the type of the result is determined at each step.
Finally,note that f and g are used to delimit blocks of code.If a block contains more than one
instruction,you have to use these delinmiters.You can declare a variable inside such a block,in
which case it is only visible within the block.Once you get out of the block,the variable is not
visible anymore,and you cannot use it or access its content.
4 Conditionals
A conditional is a type of statement that allows us to branch off to different pieces of code,
depending on a logical condition.Most often we will use an if statement,whose syntax is:
if (boolean expression) f
instructions to execute if the expression evaluates to true
g
else f
instructions to execute if expression evaluates to false
g
The file TestIf.java contains a simple example of using an if statement to determine if a specified
point is inside a circle (given by its centre and radius).
5 Loops
Aloop is a type of statement that allows us to execute repeatedly a sequence of instructions.There
are three main types of loops:while,for and do-while.
A while loop has the following syntax:
while (boolean expression) f
body
g In this case,the boolean expression is tested,then the instructions in the body are executed,
the expression is checked again,etc.When the expression is false,the loop does not execute
anymore.File TestWhile.java illustrates the use of a while loop - what do you think it computes?
4
Afor loop is a very useful construction for going through arrays (as we shall see next time) and
other data structures.It has the following syntax:
for (initialization;boolean expression;update statement) f
body
g The “initialization” is executed only once,at the beginning of the loop.Then the boolean
expression is checked;if it is true,the instructions in the ‘body” are executed,then the update
statement is executed,and the condition is checked again.The execution terminates when the
condition becomes false.File TestFor.java uses two nested for loops (nested means one inside the
other) to print a triangle of stars,with 10 stars on the bottomedge.
The do-while loop is most natural to use when soliciting user input,so we will discuss it later.
5