ee2e1 lecture 1

Upload: dharan0007

Post on 07-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 EE2E1 Lecture 1

    1/31

    EE2E1. JAVA Programming

    Lecture 1Lecture 1

    From C to JavaFrom C to Java a one way ticket!a one way ticket!

  • 8/4/2019 EE2E1 Lecture 1

    2/31

    Contents A simple Java programA simple Java program

    Data typesData types

    VariablesVariables

    Assignment/initializationAssignment/initialization

    OperatorsOperators

    Control FlowControl Flow StringsStrings

    ArraysArrays

  • 8/4/2019 EE2E1 Lecture 1

    3/31

    Simple example Java programpublic class firstProgram

    {

    public static void main(String[] args){

    System.out.println(Java is fun!);

    }

    }

  • 8/4/2019 EE2E1 Lecture 1

    4/31

    Main points

    EverythingEverythingin a Java program is a classin a Java program is a class

    KeywordKeywordpublicpublic is anis an access modifieraccess modifier

    Program starts execution from theProgram starts execution from the mainmain methodmethod We will worry about whatWe will worry about whatstatic voidstatic voidmeans latermeans 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 themeans call the println()println()

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

    the classthe class System)System)

  • 8/4/2019 EE2E1 Lecture 1

    5/31

    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

  • 8/4/2019 EE2E1 Lecture 1

    6/31

    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 .. 3276732768 .. 32767longlong 8 bytes8 bytes ApproxApprox 9x109x10

    1818

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

    floatfloat 4 bytes4 bytes ApproxApprox 3.4x103.4x10

    3838

    doubledouble 8 bytes8 bytes ApproxApprox 1.8x101.8x10308308

    charchar 2 bytes (Unicode)2 bytes (Unicode)

    booleanboolean false, truefalse, true

  • 8/4/2019 EE2E1 Lecture 1

    7/31

    The char datatype char represented by a 2char represented by a 2--byte Unicode valuebyte Unicode value

    Designed to represent all characters in the writtenDesigned 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 Expressed as hexidecimal \\u0000 to u0000 to \\uFFFFuFFFF

    ((\\u0000 to u0000 to \\u00FF is the ascii set)u00FF is the ascii set) \\u indicates a Unicode valueu indicates a Unicode value

    Check outCheck out www.unicode.orgwww.unicode.org for more detailsfor more details

  • 8/4/2019 EE2E1 Lecture 1

    8/31

    Variables

    Variables must be declared before useVariables must be declared before use

    Variable names must begin with a letter butVariable 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

  • 8/4/2019 EE2E1 Lecture 1

    9/31

    Assignment/initialization

    Assignment and initialization are identicalAssignment and initialization are identical

    to Cto C

    int myVariable=20; // initialization

    int anotherVariable;

    anotherVariable=myVariable; // assignment

    char yes=y; // initialization

    char cc;

    cc=yes; // assignment

  • 8/4/2019 EE2E1 Lecture 1

    10/31

    Constant variables

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

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

    In Java, the keywordIn Java, the keywordfinalfinaldenotes adenotes a

    constantconstant

    Constant variables cannot be assigned toConstant variables cannot be assigned to

  • 8/4/2019 EE2E1 Lecture 1

    11/31

    Operators

    Usual arithmetic operators +Usual arithmetic operators + -- * / are used* / 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 decrementIncrement ++ and decrement ----

    Exponentiation usesExponentiation uses pow()pow() function whichfunction which

    is part of theis part of theMathMath classclassdouble y=Math.pow(x,a); // y=xdouble y=Math.pow(x,a); // y=x

    aa

  • 8/4/2019 EE2E1 Lecture 1

    12/31

    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)

  • 8/4/2019 EE2E1 Lecture 1

    13/31

    Boolean expressions

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

    This cant be converted to an int (as in C)This cant be converted to an int (as in C)

    if (x == y) {} // Result is a boolean

    Java eliminates a commonC programming bugJava eliminates a commonC programming bug

    if (x = y) {} // Ok in C, wont compile in

    // Java

  • 8/4/2019 EE2E1 Lecture 1

    14/31

    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 (..);

  • 8/4/2019 EE2E1 Lecture 1

    15/31

    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

  • 8/4/2019 EE2E1 Lecture 1

    16/31

    Computes the square root of an inputtedComputes 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 indicateNote the use of indentation to indicate

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

    straightforwardstraightforward

    Done by theDone by the readDoublereadDouble()() method inmethod in

    classclass ConsoleConsole

  • 8/4/2019 EE2E1 Lecture 1

    17/31

    Strings

    Strings are sequences of characters as in CStrings are sequences of characters as in C

    The standard Java library has a predefinedThe standard Java library has a predefinedclassclass StringString

    Strings areStrings are immutableimmutable (unlike in C)(unlike in C)

    individual characters in the string cannot beindividual characters in the string cannot bechangedchanged

    String name = Mike;

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

  • 8/4/2019 EE2E1 Lecture 1

    18/31

    Strings can be concatenated using the +Strings can be concatenated using the +

    operatoroperator

    In Java, every object, even literals, can beIn 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;

  • 8/4/2019 EE2E1 Lecture 1

    19/31

    TheThe println(.)println(.) function makes use of stringfunction 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);

  • 8/4/2019 EE2E1 Lecture 1

    20/31

    Other string facilities

    AAsubstring(.)substring(.) method is provided to accessmethod is provided to access

    a substring of a larger stringa substring of a larger string

    AA charAt(int n)charAt(int n) method returns themethod returns the

    character at positioncharacter at position nn in the stringin the string

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

    String java=Java;

    char c= java.charAt(2) // v

  • 8/4/2019 EE2E1 Lecture 1

    21/31

    AnAn equals(.)equals(.) method tests for string equalitymethod tests for string equality

    The == operator should not be usedThe == operator should not be used it testsit tests

    to see if the strings are stored in the sameto see if the strings are stored in the samelocation!location!

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

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

    if (s.equals(Hello)){}

  • 8/4/2019 EE2E1 Lecture 1

    22/31

    Arrays

    Arrays created with theArrays created with the newnew operatoroperator

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

    The array length can be determined usingThe array length can be determined usingname.lengthname.length

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

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

    for (int j=0; j

  • 8/4/2019 EE2E1 Lecture 1

    23/31

    Array variable is effectively a pointer to anArray variable is effectively a pointer to an

    array allocated on the heap (hence arraysarray allocated on the heap (hence arrayspassed by reference)passed by reference)

    BUTBUT

    Cant do pointer arithmetic (as in C)Cant do pointer arithmetic (as in C)

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

    intArray++; // NOTALLOWED!

  • 8/4/2019 EE2E1 Lecture 1

    24/31

    MultiMulti--dimensional arrays are defined asdimensional 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]

  • 8/4/2019 EE2E1 Lecture 1

    25/31

    Copying arrays

    Copying 1 array variable to another isCopying 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

  • 8/4/2019 EE2E1 Lecture 1

    26/31

    The methodThe method System.arraycopy()System.arraycopy() shouldshould

    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

    4466

    88

    22

    4466

    88

  • 8/4/2019 EE2E1 Lecture 1

    27/31

    ClassClass java.utiljava.util..ArraysArrays has a number ofhas a number of

    convenience utility functions for arraysconvenience utility functions for arraysArrays.sort(a)Arrays.sort(a) -- sorts arraysorts array aa intointo

    ascending orderascending order

    Arrays.fill(a,val)Arrays.fill(a,val) fills arrayfills array aa with valuewith value

    valval

    Arrays.binarySearch(a, key)Arrays.binarySearch(a, key) searchessearches

    for a valuefor a value keykey in arrayin array aa

    Arrays.equals(a1,a2)Arrays.equals(a1,a2) test fortest for

    equivalence of arraysequivalence of arrays a1a1 andand a2a2

  • 8/4/2019 EE2E1 Lecture 1

    28/31

    And finally

    Basic Java programming is less error proneBasic Java programming is less error prone

    than Cthan C

    No pointers to worry aboutNo pointers to worry aboutThere is a genuineThere is a genuine booleanboolean typetype

    We have yet to think about object orientedWe have yet to think about object oriented

    conceptsconceptsClasses are the subject of the next lectureClasses are the subject of the next lecture

  • 8/4/2019 EE2E1 Lecture 1

    29/31

    Introduction to the Java lab

    All the Java programming assignments for this semesterAll the Java programming assignments for this semesterare now available on my web siteare now available on my web sitehttp://www.eee.bham.ac.uk/spannm/Courses/ee2e.htmhttp://www.eee.bham.ac.uk/spannm/Courses/ee2e.htm

    Lab structureLab structure

    SemesterSemester 11

    LabLab introintro.. ((11 week),week), nonnon--assessedassessed

    ClassesClasses ((22 weeks),weeks), assessedassessed

    InheritanceInheritance ((22 weeks),weeks), assessedassessed

    SwingSwing andand GUIsGUIs ((22 weeks),weeks), assessedassessed

    SemesterSemester 22

    MajorMajor programmingprogramming assignment,assignment, assessedassessed

  • 8/4/2019 EE2E1 Lecture 1

    30/31

    Organisation of the labOrganisation of the lab

    You will work in pairsYou will work in pairs

    The programming assignments coverThe programming assignments cover

    material already done in lecturesmaterial already done in lectures

    Please carry out the preparatory workPlease carry out the preparatory work

    before the lab with your partnerbefore the lab with your partner

    You will need to put in some time outsideYou will need to put in some time outside

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

  • 8/4/2019 EE2E1 Lecture 1

    31/31

    Assessment :Assessment :

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

    semestersemester

    Assessed by submission of code + programAssessed by submission of code + program

    outputs per lab groupoutputs per lab group

    More details will follow and submission willMore 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 assignmentThere will be 1 major programming assignmentnext semesternext semester

    Assessed by a formal lab report per labAssessed by a formal lab report per lab

    groupgroup