Sei sulla pagina 1di 31

EE2E1.

JAVA Programming
Lecture 1 From C to Java a one way ticket!

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
-2,147,483,648 .. 2,147,483,647

int short long byte float double char boolean

4 bytes 2 bytes 8 bytes 1 byte 4 bytes 8 bytes 2 bytes (Unicode)

-32768 .. 32767 Approx 9x1018 -128 .. 127 38 Approx 3.4x10 308 Approx 1.8x10 false, true

The char datatype


   

char represented by a 2-byte Unicode value 2Designed 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; char yes=y; char cc; cc=yes; // initialization // assignment // initialization // 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.6EelectronicCharge=1.6EelectronicCharge=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

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) & (and) | (or) ^ (xor) ~ (not)

Java uses the same bitwise operators as C


   

Boolean expressions
 

In Java the result of a boolean expression is a boolean type (true or false) This cant be converted to an int (as in C)
if (x == y) {} // Result is a boolean // Ok in C, wont compile in // Java

Java eliminates a common C programming bug


if (x = y) {}

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; } for (..) {} while (..) {} do {} while (..);

Iteration statements
  

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); } System.out.println("The square root of " + a + " is " + root);

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 readDouble() 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) (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  Cant do pointer arithmetic (as in C)


int[] intArray = new int[20]; intArray++;

// creates a 20 int array

// NOT ALLOWED!

MultiMulti-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 java.util. 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 are now available on my web site http://www.eee.bham.ac.uk/spannm/Courses/ee2e.htm Lab structure


Semester 1  Lab intro. (1 week), non-assessed intro. non  

Classes (2 weeks), assessed Inheritance (2 weeks), assessed

Swing and GUIs (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 3 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

Potrebbero piacerti anche