EE2E1. JAVA Programming

advertisement
About this course?

EE2E1 (MS)
 Introduction to Java programming
 Basic ideas about objects and classes
 We will also look at more advanced features
of Java
• Graphics
• Files and streams
• Multi-threading
• Networks

EE2E2 (DP)
 Object Oriented Software Design
Assessment
EE2E1 and EE2E2 are assessed jointly
(making up the EE2E module)
 EE2E1 is assessed through a classtest and
programming exercises and a major
programming assignment
 15% through a 1 hour class test
 2 x 22.5% through 2 programming
exercises
 40% through a major programming
assignment carried out in semester 2

Java resources





Sun’s Java home page
 http://java.sun.com/
Java online tutorial
 http://java.sun.com/docs/books/tutorial/
Comparing C++and Java
 http://www.compapp.dcu.ie/~renaat/projects/cvjava.ht
ml
Textbook
 Core Java 2. Volume 1-Fundamentals
 C.S.Horstmann, G. Cornell
 Amazon Link
My web page

http://www.eee.bham.ac.uk/spannm/Courses/ee2e.h
tm
Why should I learn Java?

Main reason, Java is object 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 learn
Java has powerful (and free!) development tools
e.g. Eclipse , Netbeans
Excellent documentation support – Javadocs
Great community support
Rich collection of open source libraries
Can develop Android apps in Java – supported by
Eclipse and Netbeans
 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 1
From C to Java
Contents








A simple Java program
Data types
Variables
Assignment/initialization
Operators
Control Flow
Strings
Arrays
Simple example Java program
public class firstProgram
{
public static void main(String[] args)
{
System.out.println(“Java is fun!”);
}
}
Main points

Everything in a Java program is a class

Keyword public is an access modifier

Program starts execution from the main method

We will worry about what static void means later

The program prints the string “Java is fun!”

System.out.println(“…”) means call the println()
method of the object System.out (which is part of
the class System)
Data types
Like C, Java is strongly typed
 Java has 8 primitive data types
 Machine independent storage requirements

Primitive data types
Type
Storage requirement
Range
int
4 bytes
-2,147,483,648 ..
2,147,483,647
short
long
byte
float
double
char
boolean
2 bytes
8 bytes
1 byte
4 bytes
8 bytes
2 bytes (Unicode)
-32768 .. 32767
18
Approx ± 9x10
-128 .. 127
38
Approx ± 3.4x10
308
Approx ± 1.8x10
false, true
The char datatype





char represented by a 2-byte Unicode value
Designed to represent all characters in the written
world
Allows 65536 characters (35000 are in use)
whereas ascii only allows 255
Expressed as hexidecimal ‘\u0000’ to ‘\uFFFF’
(‘\u0000’ to ‘\u00FF’ is the ascii set)
 \u indicates a Unicode value
Check out www.unicode.org for more details
Variables
Variables must be declared before use
 Variable names must begin with a letter but
can contain letters and digits
 Variable names are case sensitive

Assignment/initialization

Assignment and initialization are identical
to C
int myVariable=20;
int anotherVariable;
anotherVariable=myVariable;
// initialization
char yes=‘y’;
char cc;
cc=yes;
// initialization
// assignment
// assignment
Constant variables
In Java, the keyword final denotes a
constant
 Constant variables cannot be assigned to

final double electronicCharge=1.6E-19;
electronicCharge=1.6E-18;
// illegal assignment!
Operators
Usual arithmetic operators + - * / are used
in Java as in C
 Integer divide / and modulus % as in C
 Increment ++ and decrement - Exponentiation uses pow() function which
is part of the Math class

double y=Math.pow(x,a); // y=x
a
Relational and boolean operators

Java uses the same relational operators as C




== (equal to)
!= (not equal to)
<, >, <=, >= (less, greater, less or equal, greater or equal)
Java uses the same bitwise operators as C




& (and)
| (or)
^ (xor)
~ (not)
Boolean expressions


In Java the result of a boolean expression is a
boolean type (true or false)
This can’t be converted to an int (as in C)
if (x == y) {…}

// Result is a boolean
Java 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 C
Selection (conditional) statements




if (..) {…}
if (..) {…} else if (..) {…} …. else {…}
switch (..) { case 1: break; … default: break; }
Iteration statements



for (..) {…}
while (..) {…}
do {…} while (..);
Example – a square root calculator
public 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);
Computes the square root of an inputted
number using a simple algorithm
 Same control structure as in C
 Note the use of indentation to indicate
control
 In Java, keyboard input is not
straightforward
 Done by the readDouble() method in
class Console

Strings
Strings are sequences of characters as in C
 The standard Java library has a predefined
class String

String name = “Mike”;

Strings are immutable (unlike in C) –
individual characters in the string cannot be
changed
name[0] = ‘m’;
// Not allowed!

Strings can be concatenated using the “+”
operator
String name1 = “Mike”;
String name2 = “Spann”;
String myName=name1+name2;

In Java, every object, even literals, can be
automatically converted to a string
String postcode = “B”+15+” “+2+”TT”;

The println(.) function makes use of string
concatentation
int age = 25;
System.out.println(“I am ” + age + “ years old!”);

This works with any data type
final double pi = 3.14159;
System.out.println(“The value of PI = ” + pi);
Other string facilities

A substring(.) method is provided to access
a substring of a larger string
String java=“Java”;
String s = java.substring(0,3);

// Jav
A charAt(int n) method returns the
character at position n in the string
String java=“Java”;
char c= java.charAt(2)
// v

An equals(.) method tests for string equality
if (s.equals(“Hello”))
{…}

The == operator should not be used – it tests
to see if the strings are stored in the same
location!

int length() returns the length of the string

There are more than 50 methods in the Java
String class! (java.lang.String)
Arrays

Arrays created with the new operator
int[] intArray = new int[20];

// 20 int array
Arrays can be created and initialized as in C
int[] evenNumbers = {2,4,6,8};

The array length can be determined using
name.length
for (int j=0; j<evenNumbers.length; j++)
System.out.println(evenNumbers[j]);
Array variable is effectively a pointer to an
array allocated on the heap (hence arrays
passed by reference)
BUT
 Can’t do pointer arithmetic (as in C)

int[] intArray = new int[20];
intArray++;
// creates a 20 int array
// NOT ALLOWED!

Multi-dimensional arrays are defined as
follows :
int[][] a = new int[5][4]; // 5 x 4 int array

Its effectively a 1D array of pointers :
a[][]
a[0]
a[1]
a[2]
a[3]
a[4]
a[3][0]
a[3][1]
a[3][2]
a[3][3]
Copying arrays

Copying 1 array variable to another is
equivalent (in C) to copying pointers
int[] newArray = evenNumbers;
evenNumbers
newArray
2
4
6
8

The method System.arraycopy(…) should
be used to copy the array contents

System.arraycopy(from, fromIndex, to,
toIndex,n)
int[] newArray = {0,0,0,0}
System.arraycopy(evenNumbers,0,newArray,0,4);
evenNumbers
2
4
6
8
2
4
6
8
newArray

Class java.util.Arrays has a number of
convenience utility functions for arrays
 Arrays.sort(a) - sorts array a into
ascending order
 Arrays.fill(a,val) – fills array a with value
val
 Arrays.binarySearch(a, key) – searches
for a value key in array a
 Arrays.equals(a1,a2) – test for
equivalence of arrays a1 and a2
And finally…
Basic Java programming is less error prone
than C
 No pointers to worry about
 There is a genuine boolean type
 We have yet to think about object oriented
concepts
 Classes are the subject of the next lecture

Introduction to the Java lab



All the Java programming assignments for this semester
will be available on the course web site and Canvas
http://www.eee.bham.ac.uk/spannm/Courses/ee2e.htm
Lab structure
 Semester 1 (weeks 4-6, 9-10) Tuesday 2-5pm N122
 Lab intro. (1 week), non-assessed
 Classes (2 weeks), assessed
Inheritance (2 weeks), assessed
Semester 2
 Major programming assignment, assessed



Organisation of the lab
 You will work in pairs
 The programming assignments cover
material already done in lectures
 Please carry out the preparatory work
before the lab with your partner
 You will need to put in some time outside
the lab slots to finish each exercise

Assessment :
 Makes up 85% of the 2E1 mark
 There will be 2 programming assignments this
semester
 Assessed by submission of code + program
outputs per lab group
 More details will follow and submission will
be at the end of the semester
 There will be 1 major programming assignment
next semester
 Assessed by a formal lab report per lab
group
Download