Download Java Introduction

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
OOP in Java
OOP in Java : © W. Milner 2005 : Slide 1
Course outline
1. Getting started, primitive data types and control
structures
2. Classes and objects
3. Extending classes
4. Using some standard packages
5. OOP revisited
Sessions 1 to 3 introduce and sketch out the ideas of OOP.
Session 5 deals with these ideas in closer detail.
OOP in Java : © W. Milner 2005 : Slide 2
Recommended text
 The Java Programming Language Third Edition by
Arnold, Gosling and Holmes – Addison Wesley
 Gosling created the Java language
 In the spirit of The C Programming Language by K
& R, and the C++ Programming Language by
Stroustrup
 If you’ve never written a computer program
before, it won’t make much sense
OOP in Java : © W. Milner 2005 : Slide 3
What you need to know already
 What compiling and iterpreting mean
 Some knowledge of C
– Much Java syntax is like C, so
– We’ll say ‘it’s like C except that..’
OOP in Java : © W. Milner 2005 : Slide 4
Getting started
 Just follow these steps – explanations later
 Look at java.sun.com for what is available
 You need J2SE = Java 2 Standard Edition
 Download and install the JDK – currently 5.0
Update 5
 This will install software needed in
C:\Program files\java
 Create a directory where you will save your Java
programs – call the folder JavaProgs
OOP in Java : © W. Milner 2005 : Slide 5
Keeping Going
 Start NotePad and enter the program on the next
slide.
 Save it with the filename “First.java” – must be
this name. Put quotes around it – make sure
Notepad does not put .txt on the end.
 Note CAPITAL F.
 Save it in your JavaProgs folder:
OOP in Java : © W. Milner 2005 : Slide 6
The first program
public class First
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
OOP in Java : © W. Milner 2005 : Slide 7
Then..
 Switch to the command prompt (Start Programs
Accessories Command Prompt) and navigate to
your JavaProgs folder
 Use cd to change directory. Cd.. Moves ‘up’ a level.
 You should have something like:

OOP in Java : © W. Milner 2005 : Slide 8
Compile it
 The compiler is called javac. You’ll need to include
the path to it, so type in:

 After this, get this line back using the up and
down arrow keys.
 Then run it like this:
OOP in Java : © W. Milner 2005 : Slide 9
Explanations..
 All Java source code files are called
Something.java
 You give this to the javac compiler
 This produces a file called Something.class
 This is in bytecode
 This can be interpreted by the java interpreter
OOP in Java : © W. Milner 2005 : Slide 10
More explanations
 Each source code file defines a class
 The name of the class it defines (First in our case)
must match the filename – hence First.java
 This is compiled to a bytecode file named
First.class
 Java is case-sensitive (like C)
 Classes should start with a capital letter.
 So the file must be called First.java and not
first.java
OOP in Java : © W. Milner 2005 : Slide 11
Exercise
 Change the file First.java so it defines a class
called Second – and save it as Second.java
 Change it so it outputs ‘my second program’
instead of ‘Hello world’
 Compile and run it.
OOP in Java : © W. Milner 2005 : Slide 12
Features of Java
 Java is a general purpose high level language
 Core Java is well-defined and stable
 Versions are useful in many situations – desktop,
server, embedded, mobile etc
 Java is a trademark of Sun Microsystems
 Java is cross -platform
OOP in Java : © W. Milner 2005 : Slide 13
More features
 Java is a pure object-oriented language.
 No functions, no global variables
 Unlike C++, which is C with objects
 Java is designed to make it hard to write
programs which will crash
 No pointers
 Compiler will not compile doubtful code
 Programmer must write code that ‘catches
exceptions’
 Run-time checks eg array bounds exceptions
 Slower than C or C++ (not much), but less chance
of crash
OOP in Java : © W. Milner 2005 : Slide 14
Types
 Recall data type from C – int, char double etc
 Java has 2 kinds of types:
Primitive types
Reference types
OOP in Java : © W. Milner 2005 : Slide 15
Primitive types
 These are simple types like char, double, int
 Similar to C
 Main difference – the sizes of these types are
defined eg an int is 4 bytes
 Each hardware platform has its own 'virtual
machine'
 Which all look the same
 So can all have the same data sizes
 All chars use UNICODE character set - so
characters are 2 bytes long
OOP in Java : © W. Milner 2005 : Slide 16
Reference types
 Reference type variables are objects
 Objects belong to classes
 Objects made by a constructor
OOP in Java : © W. Milner 2005 : Slide 17
Primitive types first
 We will look at primitive types first
 and control structures (loops and ifs)
 Then look at classes and objects
OOP in Java : © W. Milner 2005 : Slide 18
Program format
public class Testing
{
public static void main(String[] args)
{
// find the area of a circle..
Use this format to start with
double radius = 5.0;
In file Testing.java
double area;
Code goes here
area = 3.1416 * radius * radius;
Explain rest later
System.out.println("Area = " + area);
}
}
OOP in Java : © W. Milner 2005 : Slide 19
Variables declaring and
assigning
public class Testing
{
public static void main(String[] args)
{
// find the area of a circle..
double radius = 5.0;
double area;
area = 3.1416 * radius * radius;
System.out.println("Area = " + area);
}
}
 // starts a line comment
 double area declares a variable called area of type double
 double radius = 5.0; declares and initializes a variable
 variables can be declared anywhere in a block { }
 statements end in ; like C and C++
OOP in Java : © W. Milner 2005 : Slide 20
Console output
 System.out.println("Area = " + area);
 This takes a single string argument – but..
 The + causes area to be converted to the
equivalent string, and
 concatenated with the left hand operand
 so we get
 "Area = 5.72" or whatever
 System.out.print stays on same line
OOP in Java : © W. Milner 2005 : Slide 21
Primitive data types - numeric
Name
Range
Size
byte
-27 to 27-1 (-128 to +127)
8 bits
short
-215 to 215-1 ( ± 32 000 )
16 bits
int
-231 to 231-1 ( ± 2 500 million )
32 bits
long
-263 to 263-1 (very big!!)
64 bits
float
about 1038, 6/7 sig digits
32 bits
double
10308, 14/15 sig digits
64 bits
Java data type sizes are platform independent
All are signed
Top four are integer, bottom two are floating point
Variables of these types declared like
short a,b,c;
double x = 1.502;
or initialised when declared
OOP in Java : © W. Milner 2005 : Slide 22
Numeric data types
 Can get overflow eg
– int i = 64000;
– int n = i * i ;
 Specify type of constant like
– x = 1000L;
– f = 1.0F;
– x = 0x1FF;
// defaults to integer
// force float - defaults to double
// hex
 Operators + - * /
 % is mod = remainder eg 13 % 4 is 1
 Short cut – same as C
+=
-=
*=
/=
%=
x+=8;
x-=8;
x*=8;
x/=8;
x%=8;
same as x = x + 8;
same as x = x - 8;
same as x = x * 8;
same as x = x / 8;
same as x = x % 8;
OOP in Java : © W. Milner 2005 : Slide 23
Overflow Exercise
 Use code to produce overflow as in the previous
slide
 Find out what happens when you compile/run it.
OOP in Java : © W. Milner 2005 : Slide 24
Two types of division
 float f = 1.0 / 2.0;
// floating point
 int i = 1 / 2;
// i is 0
 if both operands are integer, / is integer version it gives the quotient and discards the remainder
 So / is overloaded – different versions, same name
OOP in Java : © W. Milner 2005 : Slide 25
Increment and decrement
 x++; is the same as x = x + 1;
 y--; is the same as y = y - 1;
 post-increment is like
a = b++;
which first assigns b to a
then increments b
 pre-increment is
a = ++b;
which first increments b
then assigns the new value to a
OOP in Java : © W. Milner 2005 : Slide 26
Type casts
 Assigning a small type to a larger type is no
problem eg
 int i;
long x;
i = 32;
x = i;
OK because x more bits than i
 But reverse gives ‘possible loss of precision’ eg
 int i;
long x;
x = 32;
i = x;
// gives compile error
 Problem solved by a type cast ie
i = (int) x;
OOP in Java : © W. Milner 2005 : Slide 27
Type cast exercise
 Try out
 int i;
long x;
x = 32;
i = x;
In a program.
 Fix it as in the previous slide
OOP in Java : © W. Milner 2005 : Slide 28
Char type





char is for a single character, like
char c = ‘A’; note single quotes
c++;
makes c = ‘B’
Strings are different - see later
Java uses Unicode not ASCII - 16
bits per character eg
import java.applet.*;
import java.awt.*;
public class TestApplet extends Applet
{
public void paint(Graphics g)
{
char c;
Font f = new Font("Arial Unicode MS",Font.PLAIN,20);
g.setFont(f);
}
c = '\u098a';
// Unicode constant
g.drawString("Some Bengali: " + c,10,30 );
}
OOP in Java : © W. Milner 2005 : Slide 29
boolean type
 If a variable is declared to be boolean, it is
restricted to 2 values - true and false
 boolean result;
result = true;
 result = ( x > y );
result is true if x is greater than y
 also < <= >= == !=
== not the same as =
 && and
|| or ! not
 result = ( x > y ) && ( y < 5 );
result is true if x is greater than y and y is less
than 5
 && and || are short-cut operators
OOP in Java : © W. Milner 2005 : Slide 30
bitwise operators
 & is bitwise AND (like both)
| is bitwise OR (like either )
^ is XOR (like not equal)
~ is NOT
 eg if x = 9
1001
and y = 10
1010
 x & y is 8
1000
 x | y is 11
1011
 x ^ y is 3
0011
 ~ 0xFFFFFFFE is 1
inverting 11111111110
OOP in Java : © W. Milner 2005 : Slide 31
bit shift operators
 >> is shift right
eg if x = 7 or in binary 0000 0111
x >> 1 is 0000 0011
 << is shift left so
x << 1 is 0000 1110 = 14
OOP in Java : © W. Milner 2005 : Slide 32
Bit shift exercise
 Try out this code:
int i = 6;
System.out.println(i&1);
i>>=1;
System.out.println(i&1);
i>>=1;
System.out.println(i&1);
 Explain what you get
OOP in Java : © W. Milner 2005 : Slide 33
precedence
2 * 3 + 4 is 10 not 14
2*(3+4) is 14
Highest ++ -*/%
+< <= > >=
== !=
&&
||
Lowest
= += -= *= /= %=
Use brackets when in doubt
OOP in Java : © W. Milner 2005 : Slide 34
Control - if
 for example
if ( x== 5 )
{
y = 2;
a++;
}
else
c++;
 round brackets around boolean expression
 indentation
 no then as in Visual Basic
 block { } around several steps to do
 no block if just one step if (x<4)
a=4;
 else can be omitted if not needed
OOP in Java : © W. Milner 2005 : Slide 35
if example - validation
 for example
if ( ( age>0 ) && ( age < 130 ) )
System.out.println(‘age is valid’);
else
{
System.out.println(‘age is invalid’);
..
code to deal with error
..
}
 beware of
if ( x==5 );
y = 2;
OOP in Java : © W. Milner 2005 : Slide 36
switch - I
 used where many alternative actions are possible
 example switch (y)
{
case 5:
a = 7;
case 9:
b = 3;
case 4:
a = 8;
default:
z = 2;
}
 y can be expression (like x + 4) but must be integral
 the 5, 9, 4 etc must be constants
 default is optional
OOP in Java : © W. Milner 2005 : Slide 37
switch - II
 the action ‘falls through’ - when one case is triggered, all the
following options execute to the end of the switch
 so often combine with break - example switch (y)
{
case 5:
a = 7; break;
case 9:
b = 3; break;
case 4:
a = 8; break;
}
 include final break - not essential but good practice, since if
add further option do not need to go back and add break to
previous
OOP in Java : © W. Milner 2005 : Slide 38
Conditional operator ? ;
 example
x = ( y > 4 ) ? 7 : 3;
if y is greater than 4, x becomes 7, and otherwise,
it becomes 3
 in general
a?b:c
b is evaluated if a is true, c if it is not
 example
int x =9, y = 10 , a;
a = (x > 9) ? x++ : y++ ;
 after this a = 10, y is 11, x is still 9
OOP in Java : © W. Milner 2005 : Slide 39
loops - while
 loops repeat blocks of code - called iteration
 example - output the numbers 3, 6, 9, ... 99
x = 3;
while ( x<102 )
{
System.out.println( x );
x += 3;
}
 in general,
while (boolean expression)
statement or block to repeat
 need to initialise variables
 may loop zero times if false first time
 use indentation
OOP in Java : © W. Milner 2005 : Slide 40
loops - do while
 example - output the numbers 3, 6, 9, ... 99
x = 3;
do
{
System.out.println( x );
x += 3;
} while ( x<102 )
 in general,
do
statement or block to repeat
while (boolean expression)
 unlike a while, it will execute the loop at least once
OOP in Java : © W. Milner 2005 : Slide 41
loops - for
 example - output the numbers 3, 6, 9, ... 99
for ( x = 3; x<102; x+=3 )
System.out.println(x);
 in general
for ( <initialisation> ; <loop while true>; <change every time> )
< statement or block to repeat >
 may loop zero times
 add up the integers 1 + 2 + 3 + ...100
int t = 0;
int x;
for ( x = 1; x<101; x++)
t += x;
System.out.println( t );
OOP in Java : © W. Milner 2005 : Slide 42
loops - for - II
 can use statement list, like
int t;
int x;
for ( x = 1, t = 0; x<101; x++)
t+=x;
System.out.println(t);
 can omit any part, (retain separating ; ) like
int t = 0;
int x = 1;
for ( ; x<101; x++)
t+=x;
System.out.println(t);
 for (; ; ) loops forever
OOP in Java : © W. Milner 2005 : Slide 43
loops - for - III
 can declare variable in for, like
int t = 0;
for ( int x = 1; x<101; x++)
t+=x;
System.out.println(t);
in this case the scope of the variable is limited to the for
statement
do not do this for ( int x = 1; x<101; x++);
t+=x;
OOP in Java : © W. Milner 2005 : Slide 44
Arrays - I
 An array is a set of boxes (elements) each labelled
with a number (index)
 Arrays are declared and created as
int [ ] numbers = new int [ 100 ];
which makes an array of 100 integers called
numbers
 or do it in 2 steps
int [ ] numbers; //declare it
numbers = new int [ 100 ]; // create it
 or initialise it
int [ ] numbers = { 4, 2, 1, 3, 5 };
 can have arrays of anything
OOP in Java : © W. Milner 2005 : Slide 45
Arrays - II
 Array elements referred to like
numbers [4] = 18;
 Multi-dimensional arrays created and used like
int [ ] [ ] table = new int [5] [10];
table[3][4]=7;
 Array element numbering starts at 0
 so
int [ ] numbers = new int [ 100 ];
creates 100 elements, from numbers[0] to
numbers[99]
 array bounds are checked at compile time and run
time
OOP in Java : © W. Milner 2005 : Slide 46
int [ ] numbers = new int [5];
Arrays - sorting
//.. put some numbers in the array, then...sort them
// a bubble sort..
for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 4-i; j++ )
if ( numbers[ j ] > numbers[ j+1] )
{
// swap them
int temp;
temp = numbers[ j ];
numbers[ j ] = numbers[ j+1 ];
numbers[ j+1 ] = temp;
};
OOP in Java : © W. Milner 2005 : Slide 47
Array exercise
 Declare an array of 100 doubles
 Fill the array with random numbers (use
Math.random(); )
 Print them out
OOP in Java : © W. Milner 2005 : Slide 48