about this course? ee2e1 (ms) ee2e1 (ms) introduction to java programming basic ideas about...

36
About this course? EE2E1 (MS) EE2E1 (MS) Introduction to Java programming Introduction to Java programming Basic ideas about objects and classes Basic ideas about objects and classes We will also look at more advanced features We will also look at more advanced features of Java of Java Graphics Graphics Files and streams Files and streams Multi-threading Multi-threading Networks Networks EE2E2 (DP) EE2E2 (DP) Object Oriented Software Design Object Oriented Software Design

Upload: may-hart

Post on 28-Dec-2015

227 views

Category:

Documents


5 download

TRANSCRIPT

About this course? EE2E1 (MS)EE2E1 (MS)

Introduction to Java programmingIntroduction to Java programmingBasic ideas about objects and classesBasic ideas about objects and classesWe will also look at more advanced features of JavaWe will also look at more advanced features of Java

• GraphicsGraphics• Files and streamsFiles and streams• Multi-threadingMulti-threading• NetworksNetworks

EE2E2 (DP)EE2E2 (DP) Object Oriented Software DesignObject Oriented Software Design

Assessment

EE2E1 and EE2E2 are assessed jointly (making up EE2E1 and EE2E2 are assessed jointly (making up the EE2E module)the EE2E module)

EE2E1 is assessed through a classtest and EE2E1 is assessed through a classtest and programming exercises and a major programming programming exercises and a major programming assignmentassignment 15% through a 1 hour class test15% through a 1 hour class test 2 x 22.5% through 2 programming exercises2 x 22.5% through 2 programming exercises 40% through a major programming assignment 40% through a major programming assignment

carried out in semester 2carried out in semester 2

Java resources Sun’s Java home pageSun’s Java home page

http://java.sun.com/http://java.sun.com/ Java online tutorialJava online tutorial

http://java.sun.com/docs/books/tutorial/http://java.sun.com/docs/books/tutorial/ Comparing C++and JavaComparing C++and Java

http://www.compapp.dcu.ie/~renaat/projects/cvjava.htmlhttp://www.compapp.dcu.ie/~renaat/projects/cvjava.html TextbookTextbook

Core Java 2. Volume 1-FundamentalsCore Java 2. Volume 1-Fundamentals C.S.Horstmann, G. CornellC.S.Horstmann, G. Cornell

Amazon LinkAmazon Link My web pageMy web page

http://www.eee.bham.ac.uhttp://www.eee.bham.ac.uk/spannm/Courses/ee2e.htmk/spannm/Courses/ee2e.htm

Why should I learn Java?

Main reason, Java is Main reason, Java is object orientedobject oriented What is OOP good for?

Modelling asynchronously interacting objects• GUIs• Event simulation• Ray tracing visualisation• CAD simulation• Real-time control/embedded systems• Robotics• Image/Video processing• Client/Server systems• etc

OK, so what’s good about Java?

Java is free to download and is easy to learnJava is free to download and is easy to learn Java has powerful (and free!) development tools e.g. Eclipse , Java has powerful (and free!) development tools e.g. Eclipse ,

NetbeansNetbeans Excellent documentation support – JavadocsExcellent documentation support – Javadocs Great community supportGreat community support Rich collection of open source librariesRich collection of open source libraries Can develop Android apps in Java – supported by Eclipse and Can develop Android apps in Java – supported by Eclipse and

NetbeansNetbeans Android is a good platform for mobile apps because of Android is a good platform for mobile apps because of ease of

release, wide range of devices and its an open platform

EE2E1. JAVA Programming

Lecture 1Lecture 1

From C to JavaFrom C to Java

Contents

A simple Java programA simple Java program Data typesData types VariablesVariables Assignment/initializationAssignment/initialization OperatorsOperators Control FlowControl Flow StringsStrings ArraysArrays

Simple example Java program

public class firstProgram{

public static void main(String[] args){ System.out.println(“Java is fun!”);}

}

Main points EverythingEverything in a Java program is a class in a Java program is a class

Keyword Keyword publicpublic is an is an access modifieraccess modifier

Program starts execution from the Program starts execution from the mainmain method method

We will worry about what We will worry about what static voidstatic void means later means later

The program prints the string “Java is fun!”The program prints the string “Java is fun!”

System.out.println(“…”)System.out.println(“…”) means call the means call the println()println()

method of the object method of the object System.out System.out (which is part of the (which is part of the

class class System)System)

Data types

Like C, Java is strongly typedLike C, Java is strongly typed Java has 8 primitive data typesJava has 8 primitive data types Machine independent storage requirementsMachine independent storage requirements

Primitive data types

TypeType Storage requirementStorage requirement RangeRange

intint 4 bytes4 bytes -2,147,483,648 .. -2,147,483,648 ..

2,147,483,6472,147,483,647

shortshort 2 bytes2 bytes -32768 .. 32767-32768 .. 32767

longlong 8 bytes8 bytes Approx ± 9x10Approx ± 9x101818

bytebyte 1 byte1 byte -128 .. 127-128 .. 127

floatfloat 4 bytes4 bytes Approx ± 3.4x10Approx ± 3.4x103838

doubledouble 8 bytes8 bytes Approx ± 1.8x10Approx ± 1.8x10308308

charchar 2 bytes (Unicode)2 bytes (Unicode)

booleanboolean false, truefalse, true

The char datatype

char represented by a 2-byte Unicode valuechar represented by a 2-byte Unicode value Designed to represent all characters in the written Designed to represent all characters in the written

worldworld Allows 65536 characters (35000 are in use) Allows 65536 characters (35000 are in use)

whereas ascii only allows 255whereas ascii only allows 255 Expressed as hexidecimal ‘\u0000’ to ‘\uFFFF’ (‘\Expressed as hexidecimal ‘\u0000’ to ‘\uFFFF’ (‘\

u0000’ to ‘\u00FF’ is the ascii set)u0000’ to ‘\u00FF’ is the ascii set) \u indicates a Unicode value\u indicates a Unicode value

Check out www.unicode.org for more detailsCheck out www.unicode.org for more details

Variables

Variables must be declared before useVariables must be declared before use Variable names must begin with a letter but Variable names must begin with a letter but

can contain letters and digitscan contain letters and digits Variable names are case sensitiveVariable names are case sensitive

Assignment/initialization

Assignment and initialization are identical Assignment and initialization are identical to Cto C

int myVariable=20; // initialization int anotherVariable;anotherVariable=myVariable; // assignment

char yes=‘y’; // initializationchar cc;cc=yes; // assignment

Constant variables

final double electronicCharge=1.6E-19;final double electronicCharge=1.6E-19;

electronicCharge=1.6E-18;electronicCharge=1.6E-18; // illegal assignment!// illegal assignment!

In Java, the keyword In Java, the keyword finalfinal denotes a denotes a constantconstant

Constant variables cannot be assigned toConstant variables cannot be assigned to

Operators

Usual arithmetic operators + - * / are used Usual arithmetic operators + - * / are used in Java as in Cin Java as in C

Integer divide / and modulus % as in CInteger divide / and modulus % as in C Increment ++ and decrement --Increment ++ and decrement -- Exponentiation uses Exponentiation uses pow()pow() function which function which

is part of the is part of the MathMath class class

double y=Math.pow(x,a); // y=xdouble y=Math.pow(x,a); // y=xaa

Relational and boolean operators Java uses the same relational operators as CJava uses the same relational operators as C

== (equal to)== (equal to) != (not equal to)!= (not equal to) <, >, <=, >= (less, greater, less or equal, greater or equal)<, >, <=, >= (less, greater, less or equal, greater or equal)

Java uses the same bitwise operators as CJava uses the same bitwise operators as C & (and)& (and) | (or)| (or) ^ (xor)^ (xor) ~ (not)~ (not)

Boolean expressions

In Java the result of a boolean expression is a In Java the result of a boolean expression is a booleanboolean type (true or false) type (true or false)

This can’t be converted to an int (as in C)This can’t be converted to an int (as in C)

if (x == y) {…} // Result is a boolean Java eliminates a common C programming bugJava eliminates a common C programming bug

if (x = y) {…} // Ok in C, won’t compile in // Java

Control flow Java uses the same control structures as in CJava uses the same control structures as in C Selection (conditional) statementsSelection (conditional) statements

if (..) {…}if (..) {…} if (..) {…} else if (..) {…} …. else {…}if (..) {…} else if (..) {…} …. else {…} switch (..) { case 1: break; … default: break; }switch (..) { case 1: break; … default: break; }

Iteration statementsIteration statements for (..) {…}for (..) {…} while (..) {…}while (..) {…} do {…} while (..);do {…} while (..);

Example – a square root calculatorpublic class SquareRoot{

public static void main(String[] args){ double a,root; do { a=Console.readDouble("Enter a positive number : "); if (a<0)

{ System.out.println(“Please enter a positive number!);

….}

} while (a<0); root=a/2; double root_old;

do { root_old=root; root=(root_old+a/root_old)/2; } while (Math.abs(root_old-root)>1.0E-6);

System.out.println("The square root of " + a + " is " + root);}

}

Computes the square root of an inputted Computes the square root of an inputted number using a simple algorithmnumber using a simple algorithm

Same control structure as in CSame control structure as in C Note the use of indentation to indicate Note the use of indentation to indicate

controlcontrol In Java, keyboard input is not In Java, keyboard input is not

straightforwardstraightforward Done by theDone by the readDouble() readDouble() method in method in

class class ConsoleConsole

Strings Strings are sequences of characters as in CStrings are sequences of characters as in C The standard Java library has a predefined The standard Java library has a predefined

class class StringString

Strings are Strings are immutable immutable (unlike in C) – (unlike in C) – individual characters in the string cannot be individual characters in the string cannot be changedchanged

String name = “Mike”;

name[0] = ‘m’; // Not allowed!

Strings can be concatenated using the “+” Strings can be concatenated using the “+” operatoroperator

In Java, every object, even literals, can be In Java, every object, even literals, can be automatically converted to a stringautomatically converted to a string

String name1 = “Mike”;String name2 = “Spann”;String myName=name1+name2;

String postcode = “B”+15+” “+2+”TT”;

The The println(.)println(.) function makes use of string function makes use of string concatentationconcatentation

This works with any data typeThis works with any data type

int age = 25;System.out.println(“I am ” + age + “ years old!”);

final double pi = 3.14159;System.out.println(“The value of PI = ” + pi);

Other string facilities

A A substring(.)substring(.) method is provided to access method is provided to access a substring of a larger stringa substring of a larger string

A A charAt(int n)charAt(int n) method returns the method returns the character at position character at position nn in the string in the string

String java=“Java”;String s = java.substring(0,3); // Jav

String java=“Java”;char c= java.charAt(2) // v

An An equals(.)equals(.) method tests for string equality method tests for string equality

The == operator should not be used – it The == operator should not be used – it tests to see if the strings are stored in the tests to see if the strings are stored in the same location!same location!

intint length() length() returns the length of the stringreturns the length of the string

There are more than 50 methods in the Java There are more than 50 methods in the Java String class! (java.lang.String)String class! (java.lang.String)

if (s.equals(“Hello”)){…}

Arrays

Arrays created with the Arrays created with the newnew operator operator

Arrays can be created and initialized as in CArrays can be created and initialized as in C

The array length can be determined using The array length can be determined using name.lengthname.length

int[] intArray = new int[20]; // 20 int array

int[] evenNumbers = {2,4,6,8};

for (int j=0; j<evenNumbers.length; j++)

System.out.println(evenNumbers[j]);

Array variable is effectively a pointer to an Array variable is effectively a pointer to an array allocated on the heap (hence arrays array allocated on the heap (hence arrays passed by reference)passed by reference)

BUTBUT Can’t do pointer arithmetic (as in C)Can’t do pointer arithmetic (as in C)

int[] intArray = new int[20]; // creates a 20 int array

intArray++; // NOT ALLOWED!

Multi-dimensional arrays are defined as Multi-dimensional arrays are defined as follows :follows :

Its effectively a 1D array of pointers :Its effectively a 1D array of pointers :

int[][] a = new int[5][4]; // 5 x 4 int array

a[][]

a[3]

a[0]a[1]a[2]

a[4]

a[3][0]a[3][1]

a[3][2]

a[3][3]

Copying arrays

Copying 1 array variable to another is Copying 1 array variable to another is equivalent (in C) to copying pointersequivalent (in C) to copying pointers

int[] newArray = evenNumbers;

evenNumbers

newArray

22

44

66

88

The method The method System.arraycopy(…) System.arraycopy(…) should should be used to copy the array contentsbe used to copy the array contents System.arraycopy(from, fromIndex, to, System.arraycopy(from, fromIndex, to,

toIndex,n)toIndex,n)

int[] newArray = {0,0,0,0}

System.arraycopy(evenNumbers,0,newArray,0,4);

evenNumbers

newArray

22

44

66

88

22

44

66

88

Class Class java.utiljava.util..ArraysArrays has a number of has a number of convenience utility functions for arraysconvenience utility functions for arrays Arrays.sort(a)Arrays.sort(a) - sorts array - sorts array aa into into

ascending orderascending order Arrays.fill(a,val)Arrays.fill(a,val) – fills array – fills array aa with value with value

valval Arrays.binarySearch(a, key)Arrays.binarySearch(a, key) – searches – searches

for a value for a value keykey in array in array aa Arrays.equals(a1,a2)Arrays.equals(a1,a2) – test for – test for

equivalence of arrays equivalence of arrays a1a1 and and a2a2

And finally…

Basic Java programming is less error prone Basic Java programming is less error prone than Cthan C No pointers to worry aboutNo pointers to worry about There is a genuine There is a genuine booleanboolean type type

We have yet to think about object oriented We have yet to think about object oriented conceptsconcepts Classes are the subject of the next lectureClasses are the subject of the next lecture

Introduction to the Java lab All the Java programming assignments for this semester will All the Java programming assignments for this semester will

be available on the course web site and Canvasbe available on the course web site and Canvas http://www.eee.bham.ac.uk/spannm/Courses/ee2e.htm http://www.eee.bham.ac.uk/spannm/Courses/ee2e.htm Lab structureLab structure

Semester 1 (weeks 4-6, 9-10) Tuesday 2-5pm N122Semester 1 (weeks 4-6, 9-10) Tuesday 2-5pm N122 Lab intro. (1 week), Lab intro. (1 week), non-assessednon-assessed Classes (2 weeks), Classes (2 weeks), assessedassessed Inheritance (2 weeks), Inheritance (2 weeks), assessedassessed

Semester 2Semester 2 Major programming assignment, Major programming assignment, assessedassessed

Organisation of the labOrganisation of the lab You will work in pairsYou will work in pairs The programming assignments cover The programming assignments cover

material already done in lecturesmaterial already done in lectures Please carry out the preparatory work Please carry out the preparatory work

before the lab with your partnerbefore the lab with your partner You will need to put in some time outside You will need to put in some time outside

the lab slots to finish each exercisethe lab slots to finish each exercise

Assessment :Assessment : Makes up 85% of the 2E1 markMakes up 85% of the 2E1 mark There will be 2 programming assignments this There will be 2 programming assignments this

semestersemesterAssessed by submission of code + program Assessed by submission of code + program

outputs per lab groupoutputs per lab groupMore details will follow and submission will More details will follow and submission will

be at the end of the semesterbe at the end of the semester There will be 1 major programming assignment There will be 1 major programming assignment

next semesternext semesterAssessed by a formal lab report per lab groupAssessed by a formal lab report per lab group