Ch-2 Overview of Java

download Ch-2 Overview of Java

of 69

Transcript of Ch-2 Overview of Java

  • 7/29/2019 Ch-2 Overview of Java

    1/69

  • 7/29/2019 Ch-2 Overview of Java

    2/69

    Topics1.Brief History of Java

    2.What is Java?

    3.Differences to C++

    4.Java Development Tools

    5.The First Simple Program

    6.Structure of a Class

    7.Variables7.1.Declaration

    7.2.Scope7.3Constants

    8.Data Types8.1.Primitive Data Types

    8.2.Reference Data Types

    9.Operators

    9.1.Arithmetic9.2.Comparison and Conditional

    9.3.Assignment

    9.4.Others

    10.Type Conversions and Casting

    11.Mathematical FunctionsChapter 2

    Comp321: Object Oriented

    Programming2

  • 7/29/2019 Ch-2 Overview of Java

    3/69

    1.Brief History of Java0 Java was originally developed by Sun Microsystems, a US company,

    in 1991. Its first name was Oakand it was designed for the

    development of software for consumer electronic devices such astelevisions and video recorders. As such, one of the main goals forthe language was that it is simple, portable and highly reliable.

    0 The team based the new language on the existing C and C++

    languages, but they removed features of C and C++ that were seenas being the sources of problems.

    0 In 1993, the WWW (World Wide Web) was starting to be used,transforming the previously text-based internet into a more

    graphic-rich environment. The team developing the Oak languagecame up with the idea of creating small programs, called applets,that would be able to run on any computer that was connected tothe internet.

    Chapter 2Comp321: Object Oriented

    Programming3

  • 7/29/2019 Ch-2 Overview of Java

    4/69

    cont0 In 1995, Oak was renamed Java due to some legal issues the

    name does not have any particular meaning. Java was supported bymany IT companies, including the big internet browser developers,Netscape and Microsoft.

    0 Since then, Java has become one of the main languages used forinternet programming and also as a general-purpose object-oriented language for stand-alone applications.

    Chapter 2Comp321: Object Oriented

    Programming4

  • 7/29/2019 Ch-2 Overview of Java

    5/69

    2.What is Java?0 Java technology consists of a programming language and a

    platform on which programmes can be run.

    0 Java is different from other programming languages because a Javaprogram is both compiledand interpreted but in many otherlanguages, the program is either compiled or interpreted.

    0 The Java language is object-orientedand programs written in Java

    areportable that is, they can be run on many different platforms(e.g. Windows, Mac, Linux, Solaris).

    0 Mac, short for Macintosh, is an operating system owned by theApple Corporation. The Mac OS has a GUI that looks like Windows

    but has a different underlying architecture. It is a competitor toWindows. The Mac OS has to be run on Apple Mac computers,which, again, have a different underlying architecture to PCs likeIBM, Acer etc.

    Chapter 2Comp321: Object Oriented

    Programming5

  • 7/29/2019 Ch-2 Overview of Java

    6/69

    ...cont0 Solaris is a platform from Sun Microsystems. Like Windows, Solaris

    has server and workstation operating systems.0 The Java compiler translates the program into an intermediate

    language calledJava bytecodes.

    0 Java bytecodes are platform-independent this means they can

    be run on different operating systems (e.g. Windows and Mac).0 There are different Java interpreters for different platforms. The

    interpreter parses and runs each of the Java bytecode instructions.

    Chapter 2Comp321: Object Oriented

    Programming6

  • 7/29/2019 Ch-2 Overview of Java

    7/69

    Compiling and Interpreting of a Java program

    Chapter 2Comp321: Object Oriented

    Programming7

  • 7/29/2019 Ch-2 Overview of Java

    8/69

    Compiling and Interpreting of a Java program0 Compilation only needs to happen one time, whereas

    interpretation happens every time the program is executed.

    0 The source code for a Java program is saved to one or more .javafiles.

    0 The compiler generates a .class file for each .java file.

    0 A .java file can be opened and viewed in any text editor, but a .class

    file is bytecode so it cannot be viewed in the same way.0 Every Java interpreter is actually an implementation of somethingcalled theJava VM(Virtual Machine).

    0 It is called a Virtual Machine because it is like a computer that doesnot physically exist

    0 The VM exists only within the memory of the computer. The Javabytecodes are like a set of machine code instructions for the JavaVM. A web browser that is Java-enabled is an example of aninterpreter.

    Chapter 2Comp321: Object Oriented

    Programming8

  • 7/29/2019 Ch-2 Overview of Java

    9/69

    cont0 The big benefit of the Java way of doing things is that the program

    code can be written once, compiled and then run on many differentplatforms.

    0 See the figure below for an illustration of this concept. There is oneJava VM, but many different implementations of it i.e. manydifferent interpreters for the Java bytecodes.

    Chapter 2Comp321: Object Oriented

    Programming9

  • 7/29/2019 Ch-2 Overview of Java

    10/69

    cont0 Figure - a Java program can be compiled once and then run on

    different platforms

    Chapter 2Comp321: Object Oriented

    Programming10

  • 7/29/2019 Ch-2 Overview of Java

    11/69

    cont0 As mentioned above, Java includes a programming language and a

    platform.

    0 A platform refers to the hardware (PCs, servers, printers etc) andsoftware (operating systems, application software etc) in which aprogram is run. So, for example, the platform we use here in yourcomputer laboratory is Windows XP/7 running on IBM-compatible

    PCs.0 The Java platform is a bit different to other platforms, in that it

    consists of software only that means it is hardware-independent.This is what makes it possible to run compiled Java programs ondifferent platforms.

    0 The Java platform consists of:0 The Java VM

    0 The Java API (Application Programming Interface).

    Chapter 2Comp321: Object Oriented

    Programming11

  • 7/29/2019 Ch-2 Overview of Java

    12/69

    cont0 The API provides libraries of pre-written, ready-to-use

    components that provide standard functionality.

    0 A library groups a number of related classes and interfacestogether into what is called a Javapackage. You can choose whatpackages you want to use in your program.

    0 In order to write Java programs, you need to have the Java SDK

    (Software Development Kit) installed on your PC. This includes theAPI and the VM, as well as compilers and debuggers for Java.

    0 Java is a programming language which is based on the OOP (object-oriented paradigm).

    0 'Paradigm' means a set of ideas, a concept or hypothesis.0 You should already be familiar with some OO concepts from your

    study of C++. However, there are some differences between Javaand C++.

    Chapter 2Comp321: Object Oriented

    Programming12

  • 7/29/2019 Ch-2 Overview of Java

    13/69

    3.Differences to C++0 Java is a true OO language, while C++ is C with an object-oriented

    extension (C is not an OO language).

    0 The following is a list of some major C++ features that wereintentionally omitted from Java or significantly modified. You maynot have covered all of these C++ features in your C++programming course, but you should be familiar with some of

    them.

    0 There are, of course, other differences between Java and C++,which you will discover as we go through the course.

    Chapter 2Comp321: Object Oriented

    Programming13

  • 7/29/2019 Ch-2 Overview of Java

    14/69

    ...cont0 The differences are:

    0 Java does not support operator overloading .

    0 Java does not have template classes.0 Java does not directly support multiple inheritance of classes, but it

    does allow this to be achieved using a feature called an interface.

    0 Java does not support global variables every variable and method

    is declared within a call and forms part of that class (this relates tothe scope of variables.

    0 Java does not use pointers (but similar functionality is achievedusing implicit references to objects).

    0 Java has replaced the destructor function with a finalize() function.0 There are no header files in Java (but there is a way to import all

    the classes from another package or library).

    Chapter 2Comp321: Object Oriented

    Programming14

  • 7/29/2019 Ch-2 Overview of Java

    15/69

    4.Java Development Tools0 To get started with writing Java programs, you need to have the

    Java SDK installed on your PC.

    0 The current version of the Java itself is Java 2; the current versionof the SDK is 6.9. The latest version of the SDK can be downloadedfor free from the Sun web site (http://java.sun.com).

    0 The SDK provides various tools for working with Java code, as wellas the Java VM and the API.

    0 Some of the tools are:

    0 Javac (Java compiler)

    0 Java (Java interpreter i.e. to run a Java program)

    0 Javadoc (for creating HTML-format documentation from Java sourcecode)

    0 Jdb (Java Debugger)

    Chapter 2Comp321: Object Oriented

    Programming15

    http://java.sun.com/http://java.sun.com/
  • 7/29/2019 Ch-2 Overview of Java

    16/69

    ...cont0 The Java API consists of many built-in classes and methods that

    you can use in your code. This reflects the fact that the Java

    technology is built using Java itself.0 Some of the most commonly used packages are the following:

    0 Language support package (java.lang) classes required forimplementing basic features of Java.

    0 Utilities package (java.util) classes that provide various utilityfunctions such as date and time functions.

    0 Input/Output package (java.io) classes required for manipulation ofinput/output to/from programs

    0 Networking Package (java.net) classes for communicating with otherprograms/PCs over networks and internet

    0 Applet Package (java.applet) classes that are used to create Javaapplets.

    Chapter 2Comp321: Object Oriented

    Programming16

  • 7/29/2019 Ch-2 Overview of Java

    17/69

    5.The first simple Program1. /* This is a simple Java program. */

    2. class Example {3. // Your program begins with a call to main().

    4. publicstaticvoid main(String args[]) {

    5. System.out.println(Hello comps!");

    6. }

    7. }

    0 When the program is run, the following output is displayed:

    Hello comps!

    Chapter 2Comp321: Object Oriented

    Programming17

  • 7/29/2019 Ch-2 Overview of Java

    18/69

    cont0 Line 1: is multiple line comment which is like in C++.

    /*multiple line comment*/

    0 Line 2: class Example {0 This line uses the keyword class to declare that a new class is being

    defined.

    0 Example is an identifier that is the name of the class. The entire classdefinition, including all ofits members, will be between the openingcurly brace ({) and the closing curly brace (}).

    0 The use of the curly braces in Java is identical to the way they are usedin C, C++, and C#.

    0 For the moment, dont worry too much about the details of a classexcept to note that in Java, all program activity occurs within one. Thisis one reason why all Java programs are (at least a little bit) object-oriented.

    0 Line 3: is the single-line comment which is like in C++.

    // single line commentChapter 2

    Comp321: Object Oriented

    Programming18

  • 7/29/2019 Ch-2 Overview of Java

    19/69

    cont0 Line 4:public static void main(String args[]) {

    0 This line begins the main( ) method. As the comment preceding itsuggests, this is the line at which the program will begin executing.All Java applications begin execution by calling main( ). (This isjust like C/C++.)

    0 The public keyword is an access specifier, which allows the

    programmer to control the visibility of class members. When aclass member is preceded by public, then that member may beaccessed by code outside the class in which it is declared. (Theopposite ofpublic is private, which prevents a member from

    being used by code defined outside of its class.)0 In this case, main( ) must be declared as public, since it must be

    calledby code outside of its class when the program is started.

    Chapter 2Comp321: Object Oriented

    Programming19

  • 7/29/2019 Ch-2 Overview of Java

    20/69

    cont0 The keyword static allows main( ) to be called without having to

    instantiate a particular instance of the class. This is necessary since

    main( ) is called by the Java interpreter before any objects are made.0 The keyword void simply tells the compiler thatmain() does not

    return a value.

    0 In main( ), there is only one parameter, albeit a complicated one.

    String args[ ] declares a parameter named args, which is an array ofinstances of the class String. (Arrays are collections of similar objects.)Objects of type String store character strings.

    0 In this case, args receives anycommand-line argumentspresent when

    the program is executed. This program does not make use of thisinformation, but other programs which well see later will do.

    Chapter 2Comp321: Object Oriented

    Programming20

  • 7/29/2019 Ch-2 Overview of Java

    21/69

    cont0 Line:5

    System.out.println(Hello Comps!");

    0 This line outputs the string Hello Comps! followed by a new lineon the screen.

    0 Output is actually accomplished by the built-in println() method.In this case, println( ) displays the string which is passed to it.

    0 As you will see, println( ) canbe used to display other types ofinformation, too.

    0 The line begins with System.out. - System is a predefined classthat provides access to the system, and outis the output stream

    that is connected to the console

    Chapter 2Comp321: Object Oriented

    Programming21

  • 7/29/2019 Ch-2 Overview of Java

    22/69

    6.Structure of a Class0 All Java code is written inside classes.

    0 The class definition is the first part of the code that appears. Thisconsists of the access modifier for the class (public or private), theclass keyword and the name of the class.

    0 By convention, class names begin with an upper case letter.Forexample, to define a class called Circle :

    public class Circle

    {

    }

    Chapter 2Comp321: Object Oriented

    Programming

    22

  • 7/29/2019 Ch-2 Overview of Java

    23/69

  • 7/29/2019 Ch-2 Overview of Java

    24/69

    cont0 The methods implement the behaviour of the objects belonging to

    the class. Generally, methods return information about the state of

    an object or they change the state of an object. These aresometimes called accessorand mutatormethods.

    0 The order of these parts of a class is generally not important, butplacing the fields and then the constructors at the beginning does

    make the class readable and easy to get around for programmers.Of course, comment blocks should also be used to document thecode.

    Chapter 2Comp321: Object Oriented

    Programming

    24

    (E )

  • 7/29/2019 Ch-2 Overview of Java

    25/69

    cont (Eg)public class Circle{

    //data

    private double radius;

    //constructors

    public void Circle ()

    { radius = 1.0;}

    public void Circle (double r)

    { radius = r; }

    //methods

    public double calcArea()

    {

    return 3.14* radius * radius;

    }

    public void draw()

    {

    }

    }Chapter 2

    Comp321: Object Oriented

    Programming

    25

    7 1 V i bl D l i

  • 7/29/2019 Ch-2 Overview of Java

    26/69

    7.1.Variables Declaration0 Remember that a variable is like a storage location to store a data value

    and that a variable can take different values at different times during the

    execution of a program.0 Some Java variable declarations include:

    int x;

    FirstJava myObject = new FirstJava ();

    int sum = 0;0 A variable must be given an explicit name and data type.

    0 The name must be a legal identifier(an identifier is simply a name givento an item used in a Java program). A legal identifier begins with a letterand can consist of alpha-numeric characters (letters and digits) and canalso include the underscore (_) and dollar ($) characters. Identifiers arecase-sensitive and cannot have spaces in them.

    0 Some data types have default values that are used for initialisation if avariable is not explicitly initialised in code. For example, the integer data

    type has a default value of 0.Comp321: Object Oriented

    Programming

    26

    7 1 V i bl D l ti ( t)

  • 7/29/2019 Ch-2 Overview of Java

    27/69

    7.1.Variables Declaration(cont)0 A convention used in Java programming is that variable names begin

    with a lowercase letter while class names begin with an uppercase letter.

    If a variable or class name has more than one word in it, the words arejoined together and the first letter of each word after the first will beginwith a capital letter. This convention makes code easier to read andunderstand.

    0 A variable declaration is used to give a variable a name and a data type

    the format is to put the type followed by the name i.e. type name

    0 A variable must be initialised before it is used (the compiler will notallow an uninitialized variable to be used). Initialisation simply meansassigning some initial value to a variable e.g.

    0 int i ;0 i = 0; //to initialise an integer variable to the value 0.

    0 However, declaration and initialisation are often combined into onestatement e.g.

    0 int i = 0;

    Comp321: Object Oriented

    Programming

    27

    7 2 V i bl S

  • 7/29/2019 Ch-2 Overview of Java

    28/69

    7.2.Variables Scope0 A variable has scope.

    0 Scope refers to the parts of the code in which the variable name

    can be used without prefixing it with the class or object name. Thescope is determined by where in the class definition a variable isdeclared.

    0 Generally, Java variables have either class scope or local scope.

    0 Static variables or fields , which is another way of saying 'classvariable have class scope because they can be referenced withinthe class and its subclasses without prefixing with the class name.

    0 Instance variables are variables that belong to instances (objects)

    of a class. These also have class scope, because they must beprefixed with the instance name when used outside the class or itssubclasses.

    Chapter 2Comp321: Object Oriented

    Programming

    28

    7 2 V i bl S ( t)

  • 7/29/2019 Ch-2 Overview of Java

    29/69

    7.2.Variables Scope(cont)0 The difference between static, or class, variables and instance

    variables is that an instance variable can take different values for

    each objectwhile a class variable has the same value for all objectsof that class.

    0 Class and instance variables are declared at the class level notwithin methods. But they can be used within methods in the class,

    without prefixing with the class or instance name.0 Variables that are declared within a method or within a block of

    code have localor lexical scope, that is, they can be used only withinthe enclosing block of statements or method. For example, in thefollowing block of code, the variable i is out of scope in the line thatbegins 'System.out.println' because it was declared within theblock of statements following the if statement, so its scope is thatblock. Thus the last line will not compile:

    Chapter 2Comp321: Object Oriented

    Programming

    29

    7 2 V i bl S ( t)

  • 7/29/2019 Ch-2 Overview of Java

    30/69

    7.2.Variables Scope(cont)0 if (...) { int i = 17; ...}

    System.out.println("The value of i = " + i); // error

    0 The scope of parameters to a method or cannot be used outside themethod or constructor.

    0 Local variables do not have the public or private modifiers in frontof them. The lifetime of a local variable is only the time of themethod execution they are created when a method is called and

    destroyed when the method finishes.To summarise:

    0 Class variables are used to store data that is common to all objectsof the class.

    0 Instance variables are used to store data that persists through thelifetime of an object.

    0 Local variables are often used as temporary storage locationswhile a method or constructor completes its task.

    Chapter 2Comp321: Object Oriented

    Programming

    30

    7 3 V i bl C t t

  • 7/29/2019 Ch-2 Overview of Java

    31/69

    7.3.Variables Constants0 In Java, a variable declaration can begin with thefinalkeyword.

    This means that once an initial value is specified for the variable,that value is never allowed to change.

    0 This is the equivalent of a constantin C++ or other languages.

    0 For example, to declare a constant for the value of the maximumnumber of students allowed on a course:

    finalintMAX_STUDENTS = 100;

    0 The variable can be initialised after the declaration but if thedeclaration includes the final modifier, the initial value is the lastvalue that can be assigned.

    finalintMAX_STUDENTS;

    MAX_STUDENTS = 100;0 Note that the convention in Java programming is to use all

    uppercase letters for constant names, so that they stand out in thecode. Underscores are used to separate the words if there is morethan one word in the constant's name.

    Chapter 2 Comp321: Object OrientedProgramming

    31

    8 D t T

  • 7/29/2019 Ch-2 Overview of Java

    32/69

    8.Data Types0 Every variable must have a data type the data type

    determines the values that a variable can contain and also

    what operations can be performed on it.

    0 Java has two types of data type

    0primitive and

    0 reference.

    Chapter 2Comp321: Object Oriented

    Programming

    32

    8 1 P i iti D t T

  • 7/29/2019 Ch-2 Overview of Java

    33/69

    8.1.Primitive Data Type0 A variable ofprimitivetype contains a single value of the

    appropriate size and format for its type: a number, a character, or

    a boolean value. For example, an integer value is 32 bits of data ina format known as two's complement, the value of a char is 16 bitsof data formatted as a Unicode character, and so on.

    0 A variable ofreferencetype has as its value an address, or a

    pointer to the values or set of values that the variable represents.Classes, interfaces and arrays are reference types.

    0 The primitive types can be divided into numeric and non-numeric types.

    0 Numeric types can further be divided into integer and realnumber (or floating-point) types. Integer types hold wholenumbers, positive and negative. Real number types can holddecimal values e.g. 1.234, -6.754.

    Chapter 2Comp321: Object Oriented

    Programming

    33

    Numeric data types in Java

  • 7/29/2019 Ch-2 Overview of Java

    34/69

    Numeric data types in JavaType Description Storage Size

    Integer types byte Byte-length integer; -128 to 127 8 bits (1 byte)

    short Short integer; -32768 to 32767 16 bits (2 bytes)

    int Integer; -231 to (2311) 32 bits (4 bytes)

    long Long integer; -263 to +(263-1) 64 bits (8 bytes)

    Real number/floating-point types

    float IEEE 754 floating point;+/- 1.4E-45 to +/- 3.4028235E+38

    32 bits

    double IEEE 754 floating point;

    +/- 4.9E-324 to +/- 1.7976931348623157E+308

    64 bits

    Chapter 2Comp321: Object Oriented

    Programming

    34

    cont

  • 7/29/2019 Ch-2 Overview of Java

    35/69

    cont0 The bigger storage size types take up more memory (i.e. short takes more

    memory than byte). So, you should select a data type appropriate to thevalues that will be held in a variable e.g. if the values will be in the range

    30000 to +30000, use short rather than int. All Java number values aresigned which means they can be positive or negative.

    0 Non-numeric data types are boolean and character.

    0 The boolean type has only two possible values, representing the twoBoolean states true and false. Java reserves the words true andfalse forthese values.

    0 Comparison operators (e.g. >,

  • 7/29/2019 Ch-2 Overview of Java

    36/69

    cont0 Literal primitive values can be used directly in code e.g.char myChar = 'A'; //to assign the character A to a char variable

    int myInt = 5; // to assign the value 5 to an integer variable

    0 The declarations above also show how a value can be assigned to avariable as part of the variable declaration e.g. the myChar variableis initially given the value of 'A'.

    0 For the char type, there are escape sequences for special characterse.g. \b for a backspace, \n for a newline, \t for a tab, \\ for abackslash, \', \.

    0 Generally speaking, a series of digits with no decimal point is typedas an integer. A long integer can be specified by putting an 'L' or 'l'after the number. 'L' is preferred as it cannot be confused with the

    digit '1'.0 A series of digits with a decimal point is of type double (e.g. 34.543).

    0 But you can specify that the number is a float by putting an 'f ' or 'F'after the number (e.g. 34.543f).

    Chapter 2Comp321: Object Oriented

    Programming

    36

    cont

  • 7/29/2019 Ch-2 Overview of Java

    37/69

    cont0 A literal character value is any single Unicode character b/n single

    quote marks. The two boolean literals are simply true and false.

    0 Java has wrapper classes for each of the integer types these areByte, Short, Integer and Long. These classes define MIN_VALUE andMAX_VALUE constants that describe the range of each type. Theyalso have useful static methods that can be used to convert strings

    to integer values e.g. Integer.parseInt() to convert a string to aninteger. The exercise below demos these wrapper classes.

    0 The primitive types have default values so if a variable is notexplicitly initialised, it is automatically initialised to its

    corresponding default value. These are 0 for int, 0.0 for floating-point values, and an empty string for char.

    Chapter 2Comp321: Object Oriented

    Programming

    37

    * Uses the wrapper classes to get the min// display them all

  • 7/29/2019 Ch-2 Overview of Java

    38/69

    Chapter 2Comp321: Object Oriented

    Programming

    38

    Uses the wrapper classes to get the minand max values for each number type.*/public class MaxVariablesDemo {

    public static void main(String args[]) {

    // integersbyte largestByte = Byte.MAX_VALUE;short largestShort = Short.MAX_VALUE;int largestInteger = integer.MAX_VALUE;

    long largestLong = Long.MAX_VALUE;

    // real numbersfloat largestFloat = Float.MAX_VALUE;double

    largestDouble=Double.MAX_VALUE;

    // other primitive typeschar aChar = 'S';boolean aBoolean = true;

    System.out.println("The largest bytevalue is" + largestByte);

    System.out.println("The largest shortvalue is " + largestShort);

    System.out.println("The largest integer

    value is " + largestInteger);System.out.println("The largest long

    value is " + largestLong);System.out.println("The largest float

    value is " + largestFloat);System.out.println("The largest double

    value is " + largestDouble);

    if (Character.isUpperCase(aChar)) {System.out.println("The character "

    + aChar + " is upper case.");} else {

    System.out.println("The character "+ aChar + " is lower case.");

    }System.out.println("The value of

    aBoolean is " + aBoolean);}

    }

  • 7/29/2019 Ch-2 Overview of Java

    39/69

    0 The output will be

    The largest byte value is127

    The largest short value is 32767

    The largest short value is 2147483647

    The largest float value is 9223372036854775807

    The largest float value is 3.4028235E38

    The largest float value is 1.7976931348623157E308

    The character S is upper case.

    The value of aBoolean is true

    Chapter 2Comp321: Object Oriented

    Programming

    39

    8 2 R f D T

  • 7/29/2019 Ch-2 Overview of Java

    40/69

    8.2.Reference Data Types

    0 Arrays and classes are reference data types in Java.

    0 While a variable that has a primitive data type holds exactly onevalue, a variable that has a reference data type is a reference to thevalue or set of values represented by the variable.

    Classes

    0 When a class is defined, it can then be used as a data type. Thevariable declaration for a reference data type is the same as for aprimitive data type. For example, if a program has a class namedCustomer, a new variable, myCustomer1, to hold an object of type

    Customer can be declared like this:Customer myCustomer1;

    Chapter 2Comp321: Object Oriented

    Programming

    40

    C

  • 7/29/2019 Ch-2 Overview of Java

    41/69

    Cont0 However, to assign a reference to the variable, the newkeyword

    must be used new creates a new object from the specified class.

    The class name is followed by parentheses in which anyarguments required by the class constructor are passed e.g.

    Customer myCustomer1 = new Customer();

    0 The above line creates a new object from the Customer class; the

    constructor for the Customer class in this case does not take anyarguments.

    0 This is the same as the following lines where the object iscreated by a separate assignment:

    Customer myCustomer1;

    MyCustomer1 = new Customer();

    Chapter 2Comp321: Object Oriented

    Programming

    41

    Arrays

  • 7/29/2019 Ch-2 Overview of Java

    42/69

    Arrays0 An array is also a reference type, a structure that can hold multiple values

    but all the values must be of the same type. That type can be a primitivedata type or an object type, or it can be other arrays.

    0 In Java, an array is actually an object but one that has specialised syntaxand behaviour.

    0 An array is declared by specifying the data type of the values it will hold,followed by [] to indicate that it is an array. For example:

    byte[] arrayOfBytes; //array of values of type byte

    byte[][] arrayOfArrayOfBytes ; //an array of arrays of byte[] type

    Customer[] arrayOfCustomers; //array of objects of the class//Customer

    0 The C++ syntax for declaring a variable of array type is also supported byJava i.e.

    Byte arrayOfBytes[]; //array of values of type byte

    0 However, this syntax can be confusing, so it should be avoided in Java.Chapter 2

    Comp321: Object Oriented

    Programming

    42

    Arrays(cont)

  • 7/29/2019 Ch-2 Overview of Java

    43/69

    Arrays(cont)0 In the above examples, we can say that byte[] and Customer[] are types.

    0 After an array has been declared, it must be created. Because an array isactually an object in Java, the newkeyword must be used to create thearray (new is used to create any object). The size of the array i.e. howmany elements it can hold must be specified. For example, to declare anarray called 'arrayOfBytes' that will hold 1024 bytes and to create it:

    byte[] arrayOfBytes = newbyte[1024];

    0 To declare an array of 50 strings:String[] lines = newString[50];

    0 When the array is created in this way, each of the values in the array isinitialised to the corresponding default value for the data type of the

    value (the default value for an object type is null, meaning the object hasan empty reference).

    0 In Java, arrays have a 0-based index, that is, the first element is at index 0.The elements are accessed by the array name followed by the index insquare brackets.

    Chapter 2Comp321: Object Oriented

    Programming

    43

    Arrays(cont)

  • 7/29/2019 Ch-2 Overview of Java

    44/69

    Arrays(cont)0 For example, to declare an array named 'responses', with two

    elements whose values are 'Yes' and 'No':

    String[] responses = new String[2];responses[0] = "Yes";

    responses[1] = "No";

    //to read the elements

    System.out.println ("The answer should be " + responses[0] + " or "+ responses[1] + "!");

    0 If the size of an array is n, then the highest index for it is (n-1) e.g.an array of size 5 holds 5 elements, with the last one being

    accessed at index [4].0 If the code tries to read an element past the end of the array e.g. to

    read index [5] in an array of size 5, the interpreter throws anArrayIndexOutOfBoundsException at runtime.

    Chapter 2Comp321: Object Oriented

    Programming

    44

    Arrays cont

  • 7/29/2019 Ch-2 Overview of Java

    45/69

    Arrays cont0 The size, or length, of an array can be accessed in code by reading the

    value of the length property of the array object e.g.

    int sizeOfResponsesArray = responses.length;

    0 This is commonly used to loop through all the values in an array e.g.int[] valuesArray; //assume this array is created and initialised

    //somewhere else

    int totalValue = 0; //store the sum of the array elements

    for (int i = 0; i < valuesArray.length; i++)

    totalValue += valuesArray [i];

    0 The above example creates an array of values and then uses a for loop toiterate through the values and add them up. As the index for the array is0-based, the last element is at the index [array.length-1].

    0 Throwing an exception is part of the runtime error handling of Java. Wewill look at how to properly handle exceptions later in the course.

    0 The for syntax includes the initialisation, test and update steps for theloop initialise the counter to 0, loop until i reaches the size of the array,increment i by 1 for each iteration.

    Chapter 2Comp321: Object Oriented

    Programming

    45

    Assigning Values to Arrays

  • 7/29/2019 Ch-2 Overview of Java

    46/69

    Assigning Values to Arrays0 The nullliteral can be used to indicate that an object that is of a

    reference data type does not yet exist i.e. to initialise an object to

    be empty or null. For example:char[] password = null; //sets the password array of

    //characters to be null

    0 Literal values can also be used to specify the values of an array, asin the String array example given above:

    String[] responses = new String[2];

    responses[0] = "Yes";

    responses[1] = "No";

    0 An array can also be initialised by the following syntax, where thearray object is created and the elements initialised in onestatement. The element values are separated by commas.

    int[] someNumbers = {1, 2, 3, 4}

    Chapter 2Comp321: Object Oriented

    Programming

    46

    Assigning Values to Arrays(cont)

  • 7/29/2019 Ch-2 Overview of Java

    47/69

    Assigning Values to Arrays(cont)0 The newkeyword is not used but the object is implicitly created.

    0 The length of this array is now 4 again, this is implicit from thespecified elements.

    0 The statement above could also be written as:int[] someNumbers = new int[4];

    someNumbers[0] = 1;

    someNumbers[1] = 2;

    someNumbers[2] = 3;someNumbers[3] = 4;

    0 In fact, the Java compiler compiles the single statement into Java bytecodes that are equivalent to the above. The implication of this is that ifyour program needs to include a large amount of data into an array, it

    may not be most efficient to include the data literally in the array, as theexamples above do. This is because the compiler has to create a lot ofJava byte codes to initialise the array, and then the interpreter has toexecute all that code.

    0 It may be more efficient to store the data in an external file and read it

    into the program at runtime.

    Comp321: Object Oriented

    Programming

    47

    9 O t

  • 7/29/2019 Ch-2 Overview of Java

    48/69

    9.Operators

    0 This section covers arithmetic, comparison, conditional andassignment operators.

    0 Java also has a group of operators called shift or bitwiseoperators these operate on the individual bits (1s and 0s) of

    integer values. We will not cover these at this point.

    Chapter 2Comp321: Object Oriented

    Programming

    48

    9 1 A ith ti

  • 7/29/2019 Ch-2 Overview of Java

    49/69

    9.1. Arithmetic0 Java supports the standard arithmetic operators for all integer

    and floating-point numbers. These are:

    0 + (addition), - (subtraction), * (multiplication), / (division), %(modulo).

    0 All of these are binary operators i.e. they take two operands andthe operator appears between the two operands (this is calledinfix notation), as follows:

    Operand1 operator operand2

    0 The subtraction operator can also be used as a unary operator when it is placed in front of a number e.g. 5. When used inthis way, it effectively multiplies the single operand by 1.

    Chapter 2Comp321: Object Oriented

    Programming

    49

    9 1 Arithmetic(cont)

  • 7/29/2019 Ch-2 Overview of Java

    50/69

    9.1. Arithmetic(cont)

    0 The addition operator can also be used to concatenate twostrings. If either one of the two operands is a string, then theother one is converted to a string and the strings areconcatenated. Try the following code in a main method to seethe addition operator operating on numbers and on strings.

    System.out.println (3+4); //prints out 7

    System.out.println ("The value is: " + 4); //prints out 'Thevalue is: 4'

    System.out.println ("The value is: " + 3 + 4); //prints out 'Thevalue is: 34', because there is at least one string operand

    System.out.println ("The value is: " + (3+4)); //prints out 'Thevalue is 7' because the parentheses indicate that the sum of3+4 is evaluated first, resulting in the value 7

    Chapter 2Comp321: Object Oriented

    Programming

    50

    9 1 Arithmetic(cont)

  • 7/29/2019 Ch-2 Overview of Java

    51/69

    9.1. Arithmetic(cont)0 The division operator divides the first operand by the second e.g.

    12/4 evaluates to 3.

    0 If both operands are integers, the result is an integer and anyremainder is lost. If you want to do division and get the remainder,at least one of the operands should be typed as a floating-pointnumber the result will then be a floating-point.

    0 When an integer and a floating-point number are used as operandsto any arithmetic operator, the result is a floating-point number.This is because the integer is implicitly converted to a floating-point value before the operation takes place.

    0 The table below summarises the data types for the results ofarithmetic operations, based on what the data types of theoperands are.

    Chapter 2Comp321: Object Oriented

    Programming

    51

  • 7/29/2019 Ch-2 Overview of Java

    52/69

    9.1. Arithmetic(cont)

    Data Type of Result Data Type of Operands

    longNeither operand is a floator a double (integer

    arithmetic); at least one operand is a long.

    int Neither operand is a floator a double (integerarithmetic); neither operand is a long.

    double At least one operand is a double.

    Float At least one operand is a float; neither operand isa double.

    Chapter 2Comp321: Object Oriented

    Programming

    52

    9 1 Arithmetic(cont)

  • 7/29/2019 Ch-2 Overview of Java

    53/69

    9.1. Arithmetic(cont)0 There are also shortcut arithmetic operators, to easily increment

    and decrement a value by 1. These are + + and - -. Where the

    operator is placed relative to the operand i.e. before or after itaffects the behaviour of the operator.

    0 When the operator is placed before the operand, it increments ordecrements the operand and the operation evaluates to the

    incremented value of the operand. This is called apre-incrementoperator.

    0 When the operator is placed after the operand, it increments ordecrements the operand but the expression evaluates to the value

    of the operand before it was incremented/decremented. This iscalled apost-incrementoperator.

    Chapter 2Comp321: Object Oriented

    Programming

    53

    9 1 Arithmetic(cont)

  • 7/29/2019 Ch-2 Overview of Java

    54/69

    9.1. Arithmetic(cont)0 Consider the code sample below:

    int i,j;

    i = 1;j = ++i; //pre-increment - sets j to 2 and i to 2

    i = 1;

    j = i++; //post-increment sets j to 1 and i to 2

    0 These operators are useful as shortcuts for incrementing ordecrementing number values e.g. x++, x-- and are commonly usedto increment/decrement the counter that controls a loop e.g. a forloop that loops 10 times:

    for (int i=0; i

  • 7/29/2019 Ch-2 Overview of Java

    55/69

    9.2.Comparision and Conditional

    Operator Usage Returns true if

    > op1 > op2 op1 is greater than op2

    >= op1 >= op2 op1 is greater than or equal to op2

    < op1 < op2 op1 is less than op2

  • 7/29/2019 Ch-2 Overview of Java

    56/69

    9.2.Comparision and Conditional(cont)

    Operator Name Usage

    && Conditional AND op1 & op2

    Returns true if op1 and op2 are both trueonly evaluates op2 if

    op1 is true

    | | Conditional OR op1 | | op2

    returns true if op1 or op2 is trueonly evaluates op2 if op1 is

    false

    ! Boolean NOT !op

    Returns true if op is false i.e. changes the boolean value of the

    operand

    & Boolean AND op1 & op2Like && but always evaluates both operands

    | Boolean OR op1 | op2

    Like || but always evaluates both operands, even if the first one is

    true

    ^ Boolean XOR op1 ^op2

    Exclusive ORreturns true only if exactly one of the operands is

    true. Returns false if both are true or both are false

    Chapter 2 56

    Java also has conditional (logical) operators. These can be used tocombine multiple comparison expressions into a single, morecomplex expression. The operands for a conditional operator mustbe boolean and the result is also a boolean.

    9.2.Comparision and Conditional(cont)

  • 7/29/2019 Ch-2 Overview of Java

    57/69

    9.2.Comparision and Conditional(cont)0 Note the difference between && and &, and between | | and |.

    0 If the right-hand operand in a && or | | operation carries out some

    action, such as reading in some input or updating a value,remember that if the operand is not evaluated, the action will notbe carried out.

    0 For example, suppose there is an object named customer1 which

    has a method increaseBalance() which returns a Boolean true ifthe increase is successful and false if it is not. Take a statement thatchecks for the value of a variable (beingInt) being greater than agiven value AND the increaseBalance() method being successfullyinvoked. The statement can be written as follows, using aconditional AND:

    Chapter 2Comp321: Object Oriented

    Programming57

    9.2.Comparision and Conditional(cont)

  • 7/29/2019 Ch-2 Overview of Java

    58/69

    9.2.Comparision and Conditional(cont)someInt int = 8

    depositAmt int;

    depositAmt = 100;.

    if (someInt >= 10 && customer1.increaseBalance(depositAmt) )

    {

    }

    0 In this case, the value of someInt is 8, which is less than 10, so theexpression 'someInt>=10' is false. This means that the second

    expression, customer1.increaseBalance() will not be evaluated. So,the balance will not be increased. This could be a problem, if it isnecessary to ensure that the balance is increased. In that case, aboolean AND operator (&) should be used as it will evaluate bothexpressions, even if the first one is false.

    Chapter 2Comp321: Object Oriented

    Programming58

    9 3 Assignment

  • 7/29/2019 Ch-2 Overview of Java

    59/69

    9.3. Assignment0 The basic assignment operator is = e.g.

    int x = 5; //assigns the value of 5 to the integer variable x

    0 There are also several short-hand assignment operators. Theseare used to perform some operation on an operand and to assignthe result to a variable, all in one go.

    0 For example:

    int i;i = 2;

    i = i + 3;

    0 //the following statement is the same as the above twostatements

    i += 2;

    0 Any of the arithmetic operators can be used in this way i.e.

    +=, -=, *=, /=, %=.Chapter 2

    Comp321: Object Oriented

    Programming59

  • 7/29/2019 Ch-2 Overview of Java

    60/69

    9 4 Others(cont)

  • 7/29/2019 Ch-2 Overview of Java

    61/69

    9.4. Others(cont)Object Member Access (.)

    0 The dot (.) operator is used to access the data and methods of an object.The data fields and methods of an object are also known as members of

    the object.0 For example:

    Person aPerson = new Person();

    String theName = new String();

    theName = aPerson.name //evaluates to the value of the name data fieldof the Person object

    Method Invocation (( ))

    0 A method can be accessed using the dot operator, and it is invoked by

    using the ( ) operator after the method name. Any arguments orparameters to the method are placed inside the brackets. For example:

    Person aPerson = new Person();

    aPerson.increaseSalary(100); //invokes the method increaseSalary,

    passing 100 as the paramter)

    61

    9.4. Others(cont)

  • 7/29/2019 Ch-2 Overview of Java

    62/69

    9.4. Others(cont)Object Creation (new)

    0 As already seen, newis used to create a new object or array. The ne

    keyword is followed by the class name and a list of arguments to bepassed to the object constructor. The arguments are placed insidebrackets. For example, if the constructor for the Person class takesthe name and father's name as arguments:

    Person aPerson = new Person("Firstname", "Fathersname");

    Chapter 2Comp321: Object Oriented

    Programming62

    10. Type Conversions and Casting

  • 7/29/2019 Ch-2 Overview of Java

    63/69

    10. Type Conversions and Casting0 Java carries out implicit conversions between number types. For

    example, if a short literal value is assigned to an int data type, Java

    automatically converts the value to int:int x = 32767; //32767 is a literal value of type short, but isconverted to int

    0 This is called a widening conversionbecause the value is beingconverted to a type that has a wider range of legal values.

    0 A narrowing conversionoccurs when a value is converted to atype that is not wider than it. Sometimes this type of conversion isnot safe e.g. it is safe to convert the integer value 13 to a byte, butnot to convert 13000 to a byte, because the byte type can only hold

    numbers between 128 and 127.0 Because of this, the Java compiler produces a compile error when

    the code attempts a narrowing conversion. This happens even ifthe actual value being converted would fit into the narrower range.

    Chapter 2Comp321: Object Oriented

    Programming63

    10. Type Conversions and Casting(cont

  • 7/29/2019 Ch-2 Overview of Java

    64/69

    10. Type Conversions and Casting(cont0 For example:

    int i = 13;

    byte b = i; //not allowed by the compiler because byte is a narrower type

    (even though 13 is an allowed value for byte)0 There is, however, one exception to this rule: an integer literal (an int

    value) can be assigned to a byte or a short variable, but only if the literalfalls inside the range of the byte/short variable. So this line would beallowed:

    byte b = 13; //allowed because 13 is an integer literal0 The error produced by the compiler for a narrowing conversion includes

    the message 'possible loss of precision.

    0 The above are examples of implicit conversion Java carries out theconversion automatically, if it is ok to do so. However, a conversion from

    one type to another can be forced using a cast. This can be used when anarrowing conversion would occur, and if the programmer knows thatdata will not be lost.

    0 A cast is performed by putting the type to convert to in parenthesesbefore the value to be converted.Chapter 2 Comp321: Object Oriented

    Programming64

    10. Type Conversions and Casting(cont

  • 7/29/2019 Ch-2 Overview of Java

    65/69

    10. Type Conversions and Casting(cont0 Taking the example above, there the narrowing conversion of the

    int value to a byte is not allowed by the compiler, this can be forced

    using a cast as follows:int i = 13;

    byte b = (byte) i; //force the int value 13 to be converted to a byte

    0 A castis often used to convert a floating-point value to an integer.When this occurs, the fractional part of the floating-point value istruncated to leave an integer.

    0 For example:

    int i;

    i = (int) 13.456; //forces the double literal to the int value 13

    0 Casting can also be used with reference data types, but there aresome restrictions.

    0 As with primitive types, the Java interpreter automatically carriesout widening conversions. Narrowing conversions must be made

    explicit using a cast.

    Chapter 2Comp321: Object Oriented

    Programming65

    10. Type Conversions and Casting(cont

  • 7/29/2019 Ch-2 Overview of Java

    66/69

    0 ype Co ve s o s a d Cast g(co t0 When converting reference data types, the following rules apply:

    An object can be converted to the type of its superclass, or any ancestor

    class in its class hierarchy. This is a widening conversion.An object can be converted to the type of its own subclass. This is a

    narrowing conversion, so it requires a cast.

    An object cannot be converted to an unrelated type i.e. to a class that the

    object is not a subclass or superclass of.All Java classes automatically inherit from the Object superclass (this

    gives them special methods such as toString(), clone() and equals()).

    0 For example, the String class is a subclass of Object. So a string value canbe assigned to a variable of type Object. If assigning the value to a String

    variable, a cast is required.

    Object o = " a string"; //a widening conversion

    //later in the code, the value of o can be cast back to a String

    String s = (String) o; //a narrowing conversion, so requires a castChapter 2 Comp321: Object OrientedProgramming

    66

    11. Mathematical Functions

  • 7/29/2019 Ch-2 Overview of Java

    67/69

    11. Mathematical Functions0 In Java, mathematical functions such as square root and trigonometric

    functions are implemented as methods on the Math class (equivalent of

    the C functions). This class is part of the built-in java.langpackage because it is a built-in class, it does not have to be imported touse it. The Math class also provides constants for the mathematicalvalues PI and E.

    0 For example:

    double x,y;

    x = 9;

    y= Math.sqrt(x); //computes the square root of x

    //use PI to compute the area of a circle

    double radius;

    radius = 6;

    double circleArea = Math.PI * radius * radius;

    0 Some useful Math methods and constants are listed in the table below.Chapter 2 Comp321: Object OrientedProgramming

    67

    Note: x and y are parameters of type double; a and b can be of type int, long, float or double

  • 7/29/2019 Ch-2 Overview of Java

    68/69

    Method Description Method Description

    sin (x) Trigonometry Sin Log (x) Returns the natural logarithm of x

    cos (x) Trigonometry Cos sqrt (x) Returns the square root of x

    tan (x) Trigonometry Tan ceil (x) Returns the smallest whole numbergreater than or equal to x (rounding

    up)

    asin (x) Trigonometry aSin floor (x) Returns the greatest whole number

    less than or equal to x (rounding

    down)

    acos (x) Trigonometry aCos rint (x) Truncated value of x

    atan (x) Trigonometry aTan abs (a) Returns the absolute value of a

    pow (x, y) Returns x to the power of y (xy) max (a,b) Returns the maximum value of a

    and b

    exp (x) Returns e to the power of x (ex) min (a,b) Returns the minimum value of a

    and b

    Constant Value & Description

    PI Double, 3.141592653589793 (access

    using Math.PI)

    E Double, 2.718281828459045 (access

    using Math.E)Chapter 2Comp321: Object Oriented

    Programming68

  • 7/29/2019 Ch-2 Overview of Java

    69/69

    Questions?

    End of chapter 2

    Comp321: Object Oriented