Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

69
Overview of java principle Chapter 2 Chapter 2 Comp321: Object Oriented Programming 1

Transcript of Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Page 1: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

1

Overview of java principle

Chapter 2

Chapter 2

Comp321:

Object Oriented

Programming

Page 2: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

2

Topics 1.Brief History of Java2.What is Java?3.Differences to C++4.Java Development Tools5.The First Simple Program6.Structure of a Class7.Variables

7.1.Declaration7.2.Scope7.3Constants

8.Data Types8.1.Primitive Data Types8.2.Reference Data Types

9.Operators9.1.Arithmetic9.2.Comparison and Conditional9.3.Assignment9.4.Others

10.Type Conversions and Casting11.Mathematical FunctionsChapter 2

Page 3: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

3

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

in 1991. Its first name was Oak and it was designed for the development of software for consumer electronic devices such as televisions and video recorders. As such, one of the main goals for the 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 seen as 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 language came up with the idea of creating small programs, called applets, that would be able to run on any computer that was connected to the internet.

Chapter 2

Page 4: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

4

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

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

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

Chapter 2

Page 5: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

5

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 Java

program is both compiled and interpreted but in many other languages, the program is either compiled or interpreted.

0 The Java language is object-oriented and programs written in Java are portable – 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 the Apple Corporation. The Mac OS has a GUI that looks like Windows but has a different underlying architecture. It is a competitor to Windows. The Mac OS has to be run on Apple Mac computers, which, again, have a different underlying architecture to PCs like IBM, Acer etc.

Chapter 2

Page 6: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

6

...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 called Java 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 2

Page 7: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

7

Compiling and Interpreting of a Java program

Chapter 2

Page 8: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

8

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 .java

files. 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 something

called the Java VM (Virtual Machine). 0 It is called a Virtual Machine because it is like a computer that does

not physically exist0 The VM exists only within the memory of the computer. The Java

bytecodes are like a set of machine code instructions for the Java VM. A web browser that is Java-enabled is an example of an interpreter.Chapter 2

Page 9: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

9

…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 different platforms.

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

Chapter 2

Page 10: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

10

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

different platforms

Chapter 2

Page 11: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

11

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

platform. 0 A platform refers to the hardware (PCs, servers, printers etc) and

software (operating systems, application software etc) in which a program is run. So, for example, the platform we use here in your computer 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 on different platforms.

0 The Java platform consists of: 0 The Java VM0 The Java API (Application Programming Interface).

Chapter 2

Page 12: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

12

…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 interfaces

together into what is called a Java package. You can choose what packages 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 the API 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 Java and C++.

Chapter 2

Page 13: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

13

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 were

intentionally omitted from Java or significantly modified. You may not 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 2

Page 14: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

14

...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 to the scope of variables.

0 Java does not use pointers (but similar functionality is achieved using 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 2

Page 15: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

15

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 version

of the SDK is 6.9. The latest version of the SDK can be downloaded for free from the Sun web site (http://java.sun.com). 

0 The SDK provides various tools for working with Java code, as well as 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 source

code)0 Jdb (Java Debugger)

Chapter 2

Page 16: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

16

...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 for

implementing basic features of Java.0 Utilities package (java.util) – classes that provide various utility

functions such as date and time functions.0 Input/Output package (java.io) – classes required for manipulation of

input/output to/from programs0 Networking Package (java.net) – classes for communicating with other

programs/PCs over networks and internet0 Applet Package (java.applet) – classes that are used to create Java

applets.

Chapter 2

Page 17: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

17

5.The first simple Program1. /* This is a simple Java program. */2. class Example {3. // Your program begins with a call to main().4. public static void 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 2

Page 18: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

18

…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 class

definition, including all of its members, will be between the opening curly brace ({) and the closing curly brace (}).

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

0 For the moment, don’t worry too much about the details of a class except to note that in Java, all program activity occurs within one. This is 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 comment

Chapter 2

Page 19: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

19

…cont0 Line 4: public static void main(String args[]) { 0 This line begins the main( ) method. As the comment preceding it

suggests, this is the line at which the program will begin executing. All Java applications begin execution by calling main( ). (This is just like C/C++.)

0 The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public 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 called by code outside of its class when the program is started.

Chapter 2

Page 20: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

20

…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 that main() 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 of instances of the class String. (Arrays are collections of similar objects.) Objects of type String store character strings.

0 In this case, args receives any command-line arguments present when the program is executed. This program does not make use of this information, but other programs which we’ll see later will do.

Chapter 2

Page 21: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

21

…cont0 Line:5

System.out.println(“Hello Comps!");0 This line outputs the string “Hello Comps!” followed by a new line

on 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( ) can be used to display other types of

information, too. 0 The line begins with System.out. - System is a predefined class

that provides access to the system, and out is the output stream that is connected to the console

Chapter 2

Page 22: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

22

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. This

consists of the access modifier for the class (public or private), the class keyword and the name of the class.

0 By convention, class names begin with an upper case letter.For example, to define a class called Circle :public class Circle{ 

}

Chapter 2

Page 23: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

23

…cont0 Inside the class, the code can be divided into fields, constructors

and methods.0 The fields are the data members of the class. The data members

can be class variables or instance variables.0 The constructors are special methods that are called when an

object is instantiated from the class. There can be more than one constructor for a class – as long as each constructor has a different parameter list. For example, in a Circle class, the radius for a new object could be passed to the constructor, or if no radius is passed, a default value could be assigned for the radius. In fact, this also applies to methods. This feature of Java is called method overloading.

Chapter 2

Page 24: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

24

…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 are sometimes called accessor and mutator methods.

0 The order of these parts of a class is generally not important, but placing 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 the code.

Chapter 2

Page 25: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

25

…cont (Eg)public class Circle{

//dataprivate double radius; //constructorspublic void Circle (){ radius = 1.0;} public void Circle (double r){ radius = r; } //methodspublic double calcArea(){ return 3.14* radius * radius;} public void draw(){… …

} }

Chapter 2

Page 26: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

26

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

given to an item used in a Java program). A legal identifier begins with a letter and can consist of alpha-numeric characters (letters and digits) and can also include the underscore (_) and dollar ($) characters. Identifiers are case-sensitive and cannot have spaces in them.

0 Some data types have default values that are used for initialisation if a variable is not explicitly initialised in code. For example, the integer data type has a default value of 0.

Comp321: Object Oriented Programming

Page 27: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

27

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 are joined together and the first letter of each word after the first will begin with a capital letter. This convention makes code easier to read and understand.

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 not allow an uninitialized variable to be used). Initialisation simply means assigning 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 one

statement e.g.0 int i = 0;

Page 28: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

28

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. The scope is determined by where in the class definition a variable is declared.

0 Generally, Java variables have either class scope or local scope. 0 Static variables or fields , which is another way of saying 'class

variable’ have class scope – because they can be referenced within the 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 be prefixed with the instance name when used outside the class or its subclasses.

Chapter 2

Page 29: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

29

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 object while a class variable has the same value for all objects of that class.

0 Class and instance variables are declared at the class level – not within 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 local or lexical scope, that is, they can be used only within the enclosing block of statements or method. For example, in the following block of code, the variable i is out of scope in the line that begins 'System.out.println' because it was declared within the block of statements following the if statement, so its scope is that block. Thus the last line will not compile: 

Chapter 2

Page 30: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

30

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 the

method or constructor. 0 Local variables do not have the public or private modifiers in front

of them. The lifetime of a local variable is only the time of the method 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 objects

of the class.0 Instance variables are used to store data that persists through the

lifetime of an object.0 Local variables are often used as temporary storage locations

while a method or constructor completes its task.Chapter 2

Page 31: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

31

7.3.Variables Constants0 In Java, a variable declaration can begin with the final keyword.

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 constant in C++ or other languages.0 For example, to declare a constant for the value of the maximum

number of students allowed on a course: final int MAX_STUDENTS = 100; 

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

final int MAX_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 the code. Underscores are used to separate the words if there is more than one word in the constant's name.

Chapter 2Comp321: Object Oriented

Programming

Page 32: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

32

8.Data Types0Every 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.

0Java has two types of data type – 0primitive and0reference.

Chapter 2

Page 33: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

33

8.1.Primitive Data Type0 A variable of primitive type 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 in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on. 

0 A variable of reference type 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 real number (or floating-point) types. Integer types hold whole numbers, positive and negative. Real number types can hold decimal values e.g. 1.234, -6.754.

Chapter 2

Page 34: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

34

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 (231 –1) 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 2

Page 35: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

35

…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 the values 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 are signed – 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 two

Boolean states – true and false. Java reserves the words true and false for these values.

0 Comparison operators (e.g. >, <, = =) all return boolean type values.0 Unlike C/C++, boolean values in Java cannot be converted to or from other

data types e.g. 0 and 1 cannot be converted to true and false. 0 The character type, called char in Java, represents any Unicode character.

The char type takes up 16 bits (2 bytes) in memory and holds only a single character.

0 Java provides some built-in classes, such as String and StringBuffer, for working with strings of char values. Comp321: Object Oriented

Programming

Page 36: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

36

…cont0 Literal primitive values can be used directly in code e.g.

char myChar = 'A'; //to assign the character A to a char variableint myInt = 5; // to assign the value 5 to an integer variable 

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

0 For the char type, there are escape sequences for special characters e.g. \b for a backspace, \n for a newline, \t for a tab, \\ for a backslash, \', \“. 

0 Generally speaking, a series of digits with no decimal point is typed as 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 2

Page 37: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

37

…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 are

Byte, Short, Integer and Long. These classes define MIN_VALUE and MAX_VALUE constants that describe the range of each type. They also have useful static methods that can be used to convert strings to integer values e.g. Integer.parseInt() to convert a string to an integer. The exercise below demos these wrapper classes.  

0 The primitive types have default values – so if a variable is not explicitly 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 2

Page 38: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

38Chapter 2

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

public static void main(String args[]) {  // integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = integer.MAX_VALUE; long largestLong = Long.MAX_VALUE;  // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble=Double.MAX_VALUE;

// other primitive types char aChar = 'S'; boolean aBoolean = true; 

// display them all System.out.println("The largest byte value is"

+ largestByte); System.out.println("The largest short value 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); }}

Page 39: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

39

0 The output will beThe largest byte value is127The largest short value is 32767The largest short value is 2147483647The largest float value is 9223372036854775807The largest float value is 3.4028235E38The largest float value is 1.7976931348623157E308The character S is upper case.The value of aBoolean is true

Chapter 2

Page 40: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

40

8.2.Reference Data Types0 Arrays and classes are reference data types in Java.0 While a variable that has a primitive data type holds exactly one

value, a variable that has a reference data type is a reference to the value or set of values represented by the variable.Classes

0 When a class is defined, it can then be used as a data type. The variable declaration for a reference data type is the same as for a primitive data type. For example, if a program has a class named Customer, a new variable, myCustomer1, to hold an object of type Customer can be declared like this: 

Customer myCustomer1; 

Chapter 2

Page 41: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

41

Cont…0 However, to assign a reference to the variable, the new keyword

must be used – new creates a new object from the specified class. The class name is followed by parentheses in which any arguments 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 any arguments.

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

Customer myCustomer1;MyCustomer1 = new Customer();

Chapter 2

Page 42: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

42

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 primitive data 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 syntax and 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 by

Java 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

Page 43: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

43

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 is

actually an object in Java, the new keyword must be used to create the array (new is used to create any object). The size of the array i.e. how many elements it can hold must be specified. For example, to declare an array called 'arrayOfBytes' that will hold 1024 bytes and to create it:

byte[] arrayOfBytes = new byte[1024]; 0 To declare an array of 50 strings:

String[] lines = new String[50]; 0 When the array is created in this way, each of the values in the array is

initialised to the corresponding default value for the data type of the value (the default value for an object type is null, meaning the object has an 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 in square brackets.

Chapter 2

Page 44: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

44

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 elementsSystem.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 an ArrayIndexOutOfBoundsException at runtime. 

Chapter 2

Page 45: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

45

Arrays(cont)0 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 elseint totalValue = 0; //store the sum of the array elementsfor (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 to

iterate through the values and add them up. As the index for the array is 0-based, the last element is at the index [array.length-1].

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

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

Page 46: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

46

Assigning Values to Arrays0 The null literal 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, as in 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 the array object is created and the elements initialised in one statement. The element values are separated by commas.

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

Page 47: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

47

Assigning Values to Arrays(cont)0 The new keyword is not used – but the object is implicitly created.0 The length of this array is now 4 – again, this is implicit from the specified

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 byte codes that are equivalent to the above. The implication of this is that if your 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 the examples above do. This is because the compiler has to create a lot of Java byte codes to initialise the array, and then the interpreter has to execute 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

Page 48: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

48

9.Operators

0 This section covers arithmetic, comparison, conditional and assignment operators.

0 Java also has a group of operators called shift or bitwise operators – these operate on the individual bits (1s and 0s) of integer values. We will not cover these at this point.

Chapter 2

Page 49: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

49

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 and

the operator appears between the two operands (this is called infix 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 in this way, it effectively multiplies the single operand by –1.

Chapter 2

Page 50: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

50

9.1. Arithmetic(cont)0 The addition operator can also be used to concatenate two

strings. If either one of the two operands is a string, then the other one is converted to a string and the strings are concatenated. Try the following code in a main method to see the addition operator operating on numbers and on strings. System.out.println (3+4); //prints out 7System.out.println ("The value is: " + 4); //prints out 'The value is: 4'System.out.println ("The value is: " + 3 + 4); //prints out 'The value is: 34', because there is at least one string operandSystem.out.println ("The value is: " + (3+4)); //prints out 'The value is 7' – because the parentheses indicate that the sum of 3+4 is evaluated first, resulting in the value 7

Chapter 2

Page 51: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

51

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 any

remainder is lost. If you want to do division and get the remainder, at least one of the operands should be typed as a floating-point number – the result will then be a floating-point. 

0 When an integer and a floating-point number are used as operands to 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 of arithmetic operations, based on what the data types of the operands are.

Chapter 2

Page 52: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

52

9.1. Arithmetic(cont)Data Type of Result Data Type of Operands

long Neither operand is a float or a double (integer arithmetic); at least one operand is a long.

int Neither operand is a float or a double (integer arithmetic); neither operand is a long.

double At least one operand is a double.

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

Chapter 2

Page 53: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

53

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 it affects the behaviour of the operator. 

0 When the operator is placed before the operand, it increments or decrements the operand and the operation evaluates to the incremented value of the operand. This is called a pre-increment operator.

0 When the operator is placed after the operand, it increments or decrements the operand but the expression evaluates to the value of the operand before it was incremented/decremented. This is called a post-increment operator.

Chapter 2

Page 54: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

54

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 or decrementing number values e.g. x++, x-- and are commonly used to increment/decrement the counter that controls a loop e.g. a for loop that loops 10 times:for (int i=0; i<=10; i++;){

……} Chapter 2

Page 55: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

55

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

<= op1 <= op2 op1 is less than or equal to op2

== op1 == op2 op1 and op2 are equal

!= op1 != op2 op1 and op2 are not equal

Chapter 2

The comparison operators in Java are much like those in other languages. These are summarised in the table below. Comparison operators return a result of data type boolean i.e. true or false.

Page 56: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

56

9.2.Comparision and Conditional(cont)

Operator Name Usage

&& Conditional AND op1 & op2Returns true if op1 and op2 are both true – only evaluates op2 if op1 is true

| | Conditional OR op1 | | op2returns true if op1 or op2 is true – only evaluates op2 if op1 is false

! Boolean NOT !opReturns 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 | op2Like || but always evaluates both operands, even if the first one is true

^ Boolean XOR op1 ^op2Exclusive OR – returns true only if exactly one of the operands is true. Returns false if both are true or both are falseChapter 2

Java also has conditional (logical) operators. These can be used to combine multiple comparison expressions into a single, more complex expression.  The operands for a conditional operator must be boolean and the result is also a boolean.

Page 57: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

57

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 not be carried out. 

0 For example, suppose there is an object named customer1 which has a method increaseBalance() which returns a Boolean – true if the increase is successful and false if it is not. Take a statement that checks for the value of a variable (beingInt) being greater than a given value AND the increaseBalance() method being successfully invoked. The statement can be written as follows, using a conditional AND: 

Chapter 2

Page 58: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

58

9.2.Comparision and Conditional(cont)someInt int = 8depositAmt 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 the expression '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 is necessary to ensure that the balance is increased. In that case, a boolean AND operator (&) should be used – as it will evaluate both expressions, even if the first one is false.

Chapter 2

Page 59: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

59

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. These

are used to perform some operation on an operand and to assign the 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 two statementsi += 2; 

0 Any of the arithmetic operators can be used in this way i.e.+=, -=, *=, /=, %=.Chapter 2

Page 60: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

60

9.4. Othersinstanceof

0 The instanceof operator is a special operator that is used to check if a given object is an instance of a particular class. The left operand is the object being tested and the right operand is the class to check for. It returns true if the object is an instance of the class and false if not. For example:  person instanceof student //returns true if the object

//person belongs to the class Student 0 "a string" instanceof String //returns true because all strings are

instances of the String class0 "a string" instanceof Object //returns true because Strings are also

instances of the Object superclass0 null instanceof String //returns false because null is never an

instance of anything .

Chapter 2

Page 61: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

61

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 field of 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 or parameters 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) 

Page 62: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

62

9.4. Others(cont)Object Creation (new)

0 As already seen, new is used to create a new object or array. The new keyword is followed by the class name and a list of arguments to be passed to the object constructor. The arguments are placed inside brackets. For example, if the constructor for the Person class takes the name and father's name as arguments: 

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

Chapter 2

Page 63: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

63

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 is converted to int 

0 This is called a widening conversion because the value is being converted to a type that has a wider range of legal values. 

0 A narrowing conversion occurs when a value is converted to a type that is not wider than it. Sometimes this type of conversion is not safe e.g. it is safe to convert the integer value 13 to a byte, but not 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 if the actual value being converted would fit into the narrower range.Chapter 2

Page 64: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

64

10. Type Conversions and Casting(cont)0 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 literal falls inside the range of the byte/short variable. So this line would be allowed:byte b = 13; //allowed because 13 is an integer literal 

0 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 the conversion 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 a narrowing conversion would occur, and if the programmer knows that data will not be lost.

0 A cast is performed by putting the type to convert to in parentheses before the value to be converted.

Chapter 2

Page 65: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

65

10. Type Conversions and Casting(cont)0 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 cast is often used to convert a floating-point value to an integer. When this occurs, the fractional part of the floating-point value is truncated 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 are some restrictions.

0 As with primitive types, the Java interpreter automatically carries out widening conversions. Narrowing conversions must be made explicit using a cast.

Chapter 2

Page 66: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

66

10. Type Conversions and Casting(cont)0 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

can be 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 StringString s = (String) o; //a narrowing conversion, so requires a cast Chapter 2

Page 67: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

67

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 <math.h> functions). This class is part of the built-in java.lang package – because it is a built-in class, it does not have to be imported to use it. The Math class also provides constants for the mathematical values 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 circledouble radius;radius = 6;double circleArea = Math.PI * radius * radius;

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

Page 68: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

68

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

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 number greater 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 2

Page 69: Overview of java principle Chapter 2 Comp321: Object Oriented Programming 1.

Comp321: Object Oriented Programming

69

Questions?

End of chapter 2

Chapter 2