SSTAF MSc Tutorials - Java ProgrammingV2x › msc › tutorials › Materials...– Access Control...

Preview:

Citation preview

1

Java Programming

MSc Induction Tutorials 2011

Stefan Stafrace

PhD Student

Department of Computing

s.stafrace@surrey.ac.uk

2

Tutorial Objectives

• This is an example based tutorial for students who want to use the Java programming language.

• Introduction to basic Java programming, like classes and objects.

• We shall look at the main topics, that aim to give you a good understanding on how they can be used in Java based MSc modules and coursework.

3

Tutorial structure

• Overview• Java Basics• Objects and Classes• Data, Variable and Modifier Types• Basic Operators• Loop Control and Decision Making Statements• Numbers, Characters and String Methods• Arrays• Methods• Exceptions Handling

4

Java Overview

5

Overview

• Java Programming Language is:– Object Oriented

• Everything is an Object

– Platform Independent• Java is compiled into platform independent byte code,

which is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

– Architectural-neutral• Java compiler generates an architecture-neutral object file

format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.

6

Overview

• Java Programming Language is:– Portable

• Being architectural neutral and having no implementation dependent aspects of the specification makes Java portable.

– Multi-Threaded• With Java’s multi-threaded feature it is possible to write

programs that can do many tasks simultaneously.

– Interpreted• Java byte code is translated on the fly to native machine

instructions.

7

Java Basics

8

Java Basics

• A Java program it can be defined as a collection of objects thatcommunicate via invoking each others methods.

• Briefly:– Object

• Objects can have state and behaviour.• Ex. Person has states: Name, ID, DOB. Has behaviours:

eating, sleeping, walking• Object is an instance of a class

– Class• A class can be defined as a template that describe the

state and behaviour that an object of its type can support.– Methods

• A method is basically behaviour. It is in methods where the logic is written, data is manipulated and all the actions executed.

9

Java Basics

• Case Sensitive:– Hello is different from hello

• Naming conventions to be followed:– For all Class Names the first letter should be in Upper Case.

Ex. class MyFirstJavaClass .– All method names should start with a Lower Case letter. Ex.

public void myMethodName()– Name of the program file should exactly match the class

name. Ex. Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java‘

• Java program processing starts from the main() method which is a mandatory part of every java program.

• public static void main(String args[])

10

Java Basics

• Java KeywordsThe following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

11

Java Basics

• Comments in Java– All characters available inside any comment are ignored by

Java compiler.

– Java supports single line and multi-line comments

– Examples://This is an example of single line comments

/*This is another example of single line comments*/

/*This is an example of multi-line comments*/

12

Objects and Classes

13

Objects and Classes

• Java is an Object Oriented Language. It supports the following OO concepts:– Polymorphism– Inheritance– Encapsulation– Abstraction– Classes– Objects– Instance– Method– Message Parsing

14

Objects and Classes

• We will look into the concepts Objects and Classes.

• ObjectsIf we consider the real-world we can find many objects around us, Cars, Dogs, Humans etc. All these objects have a state and behaviour.

Example: Object – CarStates – Brand, Colour, Max SpeedBehaviours- Accelerate, Moving

Software objects also have a state and behaviour. A software object's state is stored in fields and behaviour is shown via methods.

15

Object and Classes

• A class is a blue print from which individual objects are created.

Example of a class:Public class Car{

String brand;String colour;int maxSpeed;

void accelarate(){}void moving(){}

}

16

Object and Classes

• Constructors– Every class has a constructor. If you do not write a

constructor for a class then java compiler builds a default constructor.

– The constructor should have the same name as the class.

– Constructors are invoked to create objects from the class blue print.

17

Object and Classes

• Example of constructor:

public class Bicycle{private int gear;private int speed;

public Bicycle(int startCadence, int startSpeed, int startGear) {

gear = startGear; speed = startSpeed;

}}

18

Object and Classes

• Creating an object– An object is created from a class– The “new” keyword is used to create new objects– Example:

Bicycle bicycle; bicycle = new Bicycle();

19

Object and Classes

• Java packagesIt is a way of categorizing the classes– Example:

package javaPackage;

• Import statementsImport statement is a way of giving the proper location for the compiler to find that particular class.– The following example ask compiler to load all the classes

available in directory java_installation/java/io :

import java.io.*;

20

Data Types

21

Data Types

• Variables are reserved memory locations to store values

• Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory

• A variable's data type determines the values it may contain, plus the operations that may be performed on it

• There are two data types available in Java:– Primitive Data Types– Reference Data Types

22

Data Types

• Primitive Data Types– Handled "by value“, values are stored in variables.– Eight primitive data types are supported by java.

• byte• short• int• long• float • double• boolean• Char

– Example: int num=0;

23

Data Types

• Reference Data Types– Handled "by reference“, the address of the object or array is

stored in a variable.

– Class objects and various type of array variables come under reference data type.

– Example: Animal animal = new Animal();

24

Variable Types

25

Variable Types

• Three kinds of variables in Java1. Local variables2. Instance variables3. Class/Static variables

• Local variables– Local variables are declared in methods, constructors, or

blocks– Visible only within the declared method, constructor or block– No default value for local variables, initial values should be

given after declaration– Example:

public void displayAge(){int age=30;System.out.print(“age: ” + age);

}

26

Variable Types

• Instance variables– Declared in a class, but outside a method, constructor or any

block.– Visible for all methods, constructors and block in the class.– Hold values that must be referenced by more than one

method, constructor or block, or essential parts of an object’s state that must be present through out the class.

– Access modifiers (set access levels for classes) can be given for instance variables.

– Example:public class Person{

String name;public void displayName(){

System.out.print(“My name is ”+name);}

}

27

Variable Types

• Class/Static Variables– Class variables also known as static variables are declared

with the static keyword in a class, but outside a method, constructor or a block.

– Visibility is similar to instance variables.

– They are associated with the class, rather than with any object.

28

Variable Types

• Class/Static Variables– Example:

public class Bicycle{ private int cadence;private int gear;private int speed;

// add an instance variable for the object IDprivate int id;

// add a class variable for the number of Bicycle objects instantiatedprivate static int numberOfBicycles = 0;

...... }

29

Variable Types

Exercise: Identify the variable typesInstance variable

Class/Static variable

Local variable

30

Modifier Types

31

Modifier Types

• Modifiers are keywords that you add to class, method or variabledefinitions to change their properties.

• To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement.

• Java language has a wide variety of modifiers including:– Access Control Modifiers– Non Access Modifiers

32

Modifier Types

• Access Control Modifiers– Define the visibility of your class, method or variable– Four access levels

• Visible to the package (default, no modifier is needed)– Variable or method declared without any access

control modifier is available to any other class within the same Package (package-private )

• Visible to the class only (private)– Methods, Variables and Constructors that are

declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level.

33

Modifier Types

• Visible to the world (public) – Can be accessed from any other class

• Visible to the package and all subclasses (protected)– Variables, methods and constructors which are declared

protected in a class can be accessed by classes within the same package and, in addition, by the subclasses in other packages

34

Modifier Types

• Non-access modifiers– Java provides a number of non-access modifiers to achieve

many other functionality.• static modifier

– For creating class methods and variables.– The static keyword is used to create variables or

methods that will exist independently of any instances created for the class

• final modifier– For finalizing the implementations of classes,

methods and variables.– A final variable can be explicitly initialized only once– A final method cannot be overridden by any

subclasses– A class is declared as final to prevent the class from

being subclassed..

35

Modifier Types

• Abstract modifier– For creating abstract classes and methods.– An abstract class can never be instantiated.– An abstract method is declared without any implementation.

• Synchronized modifier– Used for threads.– The synchronized keyword used to indicate that a method

can be accessed by only one thread at a time.

36

Basic Operators

37

Basic Operators

• Java provides a set of operators to manipulate variables– Arithmetic Operators

Arithmetic operators are used in mathematical expressions, addition, subtraction etc (+,-,*,/,%,++,--)

– Relational OperatorsThe equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand.(==,!=,>,<,>=,<=)

– Bitwise OperatorsWork on bits and perform bit by bit operation(&,|, ^,~,<<,>>)

38

Basic Operators

– Logical OperatorsPerform conditional operations on boolean expressions(&&,||, !)

– Assignment OperatorsAssign values to variables(=,+=,-=,*=,/=.%=)

39

Loop Control

40

Loop Control

• Java has three looping mechanisms:– while Loop

Control structure that allows you to repeat a task a certain number of times.

while(Boolean_expression){ //Statements }– do...while Loop

Similar to a while loop, except that is guaranteed to execute at least one time

do { //Statements }while(Boolean_expression); – for Loop

A repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.for(initialization;Boolean_expression;update) { //Statements }

41

Loop Control

• Examples:

42

Decision Making

43

Decision Making

• There are two types of decision making statements in Java– if statements

An if statement consists of a Boolean expression followed by one or more statements.

• if(Boolean_expression) {//Statements will execute if the Boolean expression is true }

• if(Boolean_expression) {//Statements will execute if the Boolean expression is true }

else{//Statements will execute if the Boolean expression is false

}

44

Decision Making

– switch statementsA switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.switch(expression){ case value :

//Statementsbreak; //optional

case value : //Statementsbreak; //optional

//You can have any number of case statements. default : //Optional

//Statements }

45

Decision Making

Examples:

Which part of the statement will execute?

46

Numbers

47

Numbers

• When we work with Numbers, we use primitive data types such as byte, int, long, double etc.

• There are situations were we need to use objects instead of primitive data types.

• Java provides wrapper classes for each primitive data type.

• All the wrapper classes ( Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.– Examples:

1. int i = 5;Integer I = Integer.valueOf(i); //Wrapper

2. Integer x = 5; // boxes int to an Integer object

48

Numbers

• Number methods– Instance methods that all the subclasses of the Number class

implement. Some examples are:• compareTo() • equals()• toString()• parseInt()• abs()• round()• min()• sqrt()• cos()• random()

49

Characters

50

Characters

• When we work with characters we use the primitive data type char.

• There are situations were we need to use objects instead of primitive data types.

• Java provides wrapper class Character for primitive data type char.

• Character methods:– isLetter()– isDigit()– isWhitespace()– isUpperCase()– isLowerCase()– toUpperCase()– toLowerCase()

51

Strings

52

Strings

• Strings are a sequence of characters.• In the Java programming language, strings are objects.• Strings methods:

– char charAt(int index) – int compareTo(String anotherString)– String concat(String str)– boolean endsWith(String suffix) – int indexOf(int ch) – int length() – String substring(int beginIndex)– String toLowerCase()– String toUpperCase() – String trim()

53

Arrays

54

Arrays

• A data structure which stores a fixed-size sequential collection of elements of the same type.

• Declaring Array Variables– To use an array in a program, you must declare a variable to

reference the array, and you must specify the type of array the variable can reference.

– dataType[] arrayRefVar;• Creating Arrays

– Create an array by using the “new” operator.– arrayRefVar = new dataType[arraySize];

• Processing Arrays– When processing array elements, we often loop because all

of the elements in an array are of the same type and the size of the array is known.

55

Arrays

public class TestArray { public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5};// Print all the array elementsfor (int i = 0; i < myList.length; i++) {

System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) {

total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) {

if (myList[i] > max) max = myList[i];

} System.out.println("Max is " + max); }

}

56

Methods

57

Methods

• A Java method is a collection of statements that are grouped together to perform an operation.

• Creating a Method– A method definition consists of a method header and a

method body.– Parts of a method

• Modifier (access type of the method)• Return Type (data type of the value the method returns)• Method Name• Parameters• Method Body

– A method has the following syntaxmodifier returnValueType methodName(list of parameters) {

// Method body;}

58

Methods

• Calling a method– To use a method, you have to call or invoke it– Two ways to call a method:

• If the method returns a value, a call to the method is usually treated as a value.

int larger = max(30, 40); • If the method returns void, a call to the method must be a

statement.System.out.println("Welcome to Java!");

– Passing Parameters by Values• When calling a method, you need to provide arguments,

which must be given in the same order as their respective parameters in the method specification.

59

Methods

public class TestMax {/** Main method */ public static void main(String[] args) {

int i = 5; int j = 2;int k = max(i, j);System.out.println("The maximum between " + i + " and " + j + " is " + k);

} /** Return the max between two numbers */public static int max(int num1, int num2) {

int result;if (num1 > num2) result = num1;else result = num2; return result;

} }

60

Exceptions Handling

61

Exceptions Handling

• An exception is a problem that arises during the execution of a program.

• An exception can occur for many different reasons.

• Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

• Three categories of exceptions:– Checked exceptions– Runtime exceptions– Errors

62

Exceptions Handling

• Checked exceptions– These are exceptional conditions that a well-written

application should anticipate and recover from. • Ex: if a file is to be opened, but the file cannot be found, an

exception occurs.

• Runtime exceptions– A runtime exception is an exception that occurs that probably

could have been avoided by the programmer• Ex: divide by zero

• Errors– These exceptional conditions that are external to the

application, and that the application usually cannot anticipate or recover from

• Ex: hardware failure

63

Exceptions Handling

• Catching Exceptions– A method catches an exception using a combination of the

try and catch keywords.– A try/catch block is placed around the code that might

generate an exception.– Code within a try/catch block is referred to as protected code.– try/catch syntax

try { //Protected code

}catch(ExceptionName e1) {

//Catch block }

64

Exceptions Handling

// File Name : ExcepTest.javaimport java.io.*;public class ExcepTest{

public static void main(String args[]){try{

int a[] = new int[2];System.out.println("Access element three :" + a[3]);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Exception thrown :" + e);}System.out.println("Out of the block");

} }

65

References

• Sun Developer Network “The Java Tutorials”http://java.sun.com/docs/books/tutorial/index.html

• Tutorials Point “Java Tutorial”http://www.tutorialspoint.com/java/index.htm

66

Questions

Recommended