Download presentation
Presentation is loading. Please wait.
Published byPosy Greene Modified over 9 years ago
1
OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java
2
OOP in Java : © W. Milner 2005 : Slide 2 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.
3
OOP in Java : © W. Milner 2005 : Slide 3 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
4
OOP in Java : © W. Milner 2005 : Slide 4 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..’
5
OOP in Java : © W. Milner 2005 : Slide 5 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
6
OOP in Java : © W. Milner 2005 : Slide 6 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:
7
OOP in Java : © W. Milner 2005 : Slide 7 The first program public class First { public static void main(String[] args) { System.out.println("Hello world"); }
8
OOP in Java : © W. Milner 2005 : Slide 8 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:
9
OOP in Java : © W. Milner 2005 : Slide 9 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:
10
OOP in Java : © W. Milner 2005 : Slide 10 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
11
OOP in Java : © W. Milner 2005 : Slide 11 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
12
OOP in Java : © W. Milner 2005 : Slide 12 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.
13
OOP in Java : © W. Milner 2005 : Slide 13 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
14
OOP in Java : © W. Milner 2005 : Slide 14 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
15
OOP in Java : © W. Milner 2005 : Slide 15 Types Recall data type from C – int, char double etc Java has 2 kinds of types: Primitive types Reference types
16
OOP in Java : © W. Milner 2005 : Slide 16 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
17
OOP in Java : © W. Milner 2005 : Slide 17 Reference types Reference type variables are objects Objects belong to classes Objects made by a constructor
18
OOP in Java : © W. Milner 2005 : Slide 18 Primitive types first We will look at primitive types first and control structures (loops and ifs) Then look at classes and objects
19
OOP in Java : © W. Milner 2005 : Slide 19 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
20
OOP in Java : © W. Milner 2005 : Slide 20 Variables - declaring and assigning // 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++ 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); }
21
OOP in Java : © W. Milner 2005 : Slide 21 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
22
OOP in Java : © W. Milner 2005 : Slide 22 Primitive data types - numeric 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;
23
OOP in Java : © W. Milner 2005 : Slide 23 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;
24
OOP in Java : © W. Milner 2005 : Slide 24 Overflow Exercise Use code to produce overflow as in the previous slide Find out what happens when you compile/run it.
25
OOP in Java : © W. Milner 2005 : Slide 25 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
26
OOP in Java : © W. Milner 2005 : Slide 26 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
27
OOP in Java : © W. Milner 2005 : Slide 27 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 type cast Problem solved by a type cast ie i = (int) x;
28
OOP in Java : © W. Milner 2005 : Slide 28 Type cast exercise Try out int i; long x; x = 32; i = x; In a program. Fix it as in the previous slide
29
OOP in Java : © W. Milner 2005 : Slide 29 Char type char is for a single character, like char c = ‘A’; note single quotes c++;makes c = ‘B’ Strings are different - see later Unicode 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 ); }
30
OOP in Java : © W. Milner 2005 : Slide 30 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
31
OOP in Java : © W. Milner 2005 : Slide 31 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 1inverting 11111111110
32
OOP in Java : © W. Milner 2005 : Slide 32 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
33
OOP in Java : © W. Milner 2005 : Slide 33 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
34
OOP in Java : © W. Milner 2005 : Slide 34 precedence 2 * 3 + 4 is 10 not 14 2*(3+4) is 14 Highest++ -- * / % + - >= == != && || Lowest= += -= *= /= %= Use brackets when in doubt
35
OOP in Java : © W. Milner 2005 : Slide 35 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
36
OOP in Java : © W. Milner 2005 : Slide 36 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;
37
OOP in Java : © W. Milner 2005 : Slide 37 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
38
OOP in Java : © W. Milner 2005 : Slide 38 switch - II the action ‘falls through’ - when one case is triggered, all the following options execute to the end of the switch break 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
39
OOP in Java : © W. Milner 2005 : Slide 39 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
40
OOP in Java : © W. Milner 2005 : Slide 40 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
41
OOP in Java : © W. Milner 2005 : Slide 41 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
42
OOP in Java : © W. Milner 2005 : Slide 42 loops - for example - output the numbers 3, 6, 9,... 99 for ( x = 3; x<102; x+=3 ) System.out.println(x); in general for ( ; ; ) 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 );
43
OOP in Java : © W. Milner 2005 : Slide 43 loops - for - II statement list 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
44
OOP in Java : © W. Milner 2005 : Slide 44 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 loops - for - III do not do this - for ( int x = 1; x<101; x++); t+=x;
45
OOP in Java : © W. Milner 2005 : Slide 45 Arrays - I elements index 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
46
OOP in Java : © W. Milner 2005 : Slide 46 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
47
OOP in Java : © W. Milner 2005 : Slide 47 Arrays - sorting int [ ] numbers = new int [5]; //.. 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; };
48
OOP in Java : © W. Milner 2005 : Slide 48 Array exercise Declare an array of 100 doubles Fill the array with random numbers (use Math.random(); ) Print them out
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.