OOP in Java 1
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 Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail. 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 C and C++ Programming Languages 3
What you need to know already What compiling and interpreting mean Some knowledge of C or Python 4
Getting started at home Just follow these steps explanations later Look at java.sun.com for what is available Download and install the JDK currently version 8 This will install software needed Create a directory where you will save your Java programs call the folder JavaProgs 5
Keeping Going Start vim or NotePad and enter the program on the next slide. Save it with the filename First.java must be this name. Put quotes around it to make sure Notepad does not put.txt on the end. Note CAPITAL F. Save it in your JavaProgs folder: 6
The first program public class First { public static void main(string[] args) { System.out.println( Hugh Murrell ); System.out.println( 73156286554"); } } 7
Then.. In a terminal window, navigate to your JavaProgs folder Use cd to change directory. 8
Compile it The compiler is called javac, so type in: javac First.java Then run it like this: java First 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 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 11
Practical Exercise In your prac session on Friday you will have to, type in, compile and run a HelloWorld.java program that prints your name and student number. and then adapt your program to solve the Whiskey problem. see website for details. 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 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 Strongly typed, 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 14
Types Recall data type from C int, char double etc Java has 2 kinds of types: Primitive types Reference types 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 primitive types can all have the same data sizes All chars use UNICODE character set - so characters are 2 bytes long 16
Reference types Reference type variables are objects Objects belong to classes Objects made by a constructor 17
Primitive types first We will look at primitive types first and control structures (loops and ifs) Then look at classes and objects 18
Program format 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); } Use this format to start with In file Testing.java Code goes here Explain rest later 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++ 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 21
Primitive data types - numeric Name Range Size byte -2 7 to 2 7-1 (-128 to +127) 8 bits short -2 15 to 2 15-1 ( ± 32 000 ) 16 bits int -2 31 to 2 31-1 ( ± 2 500 million ) 32 bits long -2 63 to 2 63-1 (very big!!) 64 bits float about ± 10 38, 6/7 sig digits 32 bits double ± 10 308, 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; or initialised when declared double x = 1.502; 22
Numeric data types Can get overflow eg int i = 64000; int n = i * i ; Specify type of constant like x = 1000L; // defaults to integer f = 1.0F; // force float - defaults to double x = 0x1FF; // hex Operators + - * / % is mod = remainder eg 13 % 4 is 1 Short cut same as C += x+=8; same as x = x + 8; -= x-=8; same as x = x - 8; *= x*=8; same as x = x * 8; /= x/=8; same as x = x / 8; %= x%=8; same as x = x % 8; 23
Overflow Exercise Use code to produce overflow as in the previous slide Find out what happens when you compile/run it. 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 25
x++; is the same as x = x + 1; y--; is the same as y = y - 1; post-increment is like Increment and decrement 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 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; 27
Type cast exercise Try out int i; long x; x = 32; i = x; In a program. Fix it as in the previous slide 28
Char type char is for a single character, like char c = A ; c++; note single quotes makes c = B Strings are different - see later Java uses Unicode not ASCII - 16 bits per character. 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 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 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 32
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 Bit shift exercise 33
precedence 2 * 3 + 4 is 10 not 14 2*(3+4) is 14 Highest ++ -- * / % + - < <= > >= ==!= && Lowest = += -= *= /= %= Use brackets when in doubt 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 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; 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 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 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 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 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 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 ); 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 43
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; loops - for - III 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 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 46
int [ ] numbers = new int [5]; //.. put some numbers in the array, then...sort them Arrays - sorting // 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; }; 47
Array exercise Declare an array of 10 doubles Fill the array with random numbers (use Math.random(); ) Print them out Sort them Print them out 48