Computer Hardware Hardware components are the physical parts of the - - PowerPoint PPT Presentation

computer hardware
SMART_READER_LITE
LIVE PREVIEW

Computer Hardware Hardware components are the physical parts of the - - PowerPoint PPT Presentation

Computer Hardware Hardware components are the physical parts of the computer Main Hardware Components are: CPU Also known as processor. Brains of the computer Responsible for fetching instructions from memory and executing


slide-1
SLIDE 1

Computer Hardware

  • Hardware components are the physical parts of the computer
  • Main Hardware Components are:
  • CPU
  • Also known as processor.
  • Brains of the computer
  • Responsible for fetching instructions from memory and executing them
  • Main Memory
  • Holds/Stores the instructions that are executed by the CPU
  • Secondary Storage Devices
  • Such as hard drive, DVD etc
  • Input/Output Systems
  • Keyboard, Mouse, Monitor..
slide-2
SLIDE 2

Computer Software

  • Computer Software consists of one or more computer programs
  • A computer program is a set of instructions
  • To program is:

to provide a computer or other machine

with coded instructions

○ for the automatic performance

  • of a particular task
slide-3
SLIDE 3

What is a Programming Language?

  • Formally constructed language designed to
  • Communicate instructions to a computer
  • Can you name a few programming languages?
  • Types of Programming Language:

High Level Programming Languages

  • Written in Human Language
  • Easy to read and understand

Low Level Programming Languages

  • Written in Machine Language
  • Binary (0s and 1s)
slide-4
SLIDE 4

Compile and Run

  • Program

Set of instructions

  • Compile

Translate a program

From human language to computer language

  • Run

Execution of the translated instructions by the computer

slide-5
SLIDE 5

About Java

5

  • Java is an Object Oriented Programming Language
  • First released in 1995 by Sun Microsystems
  • Oracle acquired Sun Microsystems in 2009-2010
  • Programming Language for Android
  • Java files have the .java extension
slide-6
SLIDE 6

Object Oriented Programming (OOP)Language

  • Organise programs based on:

○ Objects and their Interaction

  • Object expose:

○ data (attributes) ○ behaviour (methods)

  • Examples:

○ SmallTalk ○ Java ○ Objective C ○ C++ ○ Swift

slide-7
SLIDE 7

OOP Concepts

  • Class
  • Object

○ Instance of Class

  • Inheritance
  • Message Passing
  • Encapsulation
  • Polymorphism
  • Dynamic Binding
  • Dynamic Typing
slide-8
SLIDE 8

Class

  • Class

○ Template or blueprint ○ Defines an object’s: data types/properties (attributes) behaviour (methods)

slide-9
SLIDE 9

Object

  • Object

○ Instance of a class

  • A class can have many instances

○ All instances are said to be the member of the same class

  • Each object has memory allocated to it
slide-10
SLIDE 10

Inheritance

  • Inheritance
  • The subclass or child class inherits all the instance variables and

methods of its superclass or parent class.

  • Class B, Class C and Class D inherit from Class A
  • Class A is the superclass, base class or parent class
  • Single Inheritance

A class can only have one direct superclass

Class A Class B Class C Class D

public class Animal{ //body } public class Dog extends Animal{ //body }

slide-11
SLIDE 11

Message Passing

  • In OOP programs are based on:

○ Objects ○ Interaction between objects

  • Objects communicate with each other

○ Through messages

  • A message is sent to an object

○ Requesting it to perform one of its methods

slide-12
SLIDE 12

Encapsulation

  • Also known as information hiding
  • internal representation of on object is hidden
  • It is the separation of:

○ The implementation of an object from its interface.

  • Implementation of a class can be changed

○ Without affecting the code that calls it.

slide-13
SLIDE 13

Polymorphism

  • Polymorphism means many forms
  • Different classes can define methods

○ with the same name

Shape Circle draw() Square draw() Rectangle draw()

slide-14
SLIDE 14

Polymorphism

14

  • Overriding
  • Overloading
slide-15
SLIDE 15

Dynamic Typing: Compile and Run

  • In high level languages

○ Instructions are written for humans to understand ○ For a computer to understand the program It has to be compiled

○ Changed into machine language

  • Once a program is compiled

○ The computer can understand the instructions

  • The program is then run

○ The computer performs the instructions

slide-16
SLIDE 16

Dynamic Typing: Compile and Run

  • Program

○ Set of instructions

  • Compile

○ Translate a program

From human language to computer language

  • Run

○ Execution of the translated instructions by the computer

slide-17
SLIDE 17

Compile and Run

  • Program

Set of instructions

Java files have the .java extension

  • Compile

Translate a program

From human language to computer language Java files are converted to .class files when compiled

  • Run

Execution of the translated instructions by the computer

Once compiled, the JVM can run the program

slide-18
SLIDE 18

Java Virtual Machine

18

  • Interpreter
  • Source Code transformed to byte code by compiler
  • The JVM is able to interpret the byte code
  • Hardware and Software Independent
  • This is why Java can be executed in any environment
  • Where there is a JVM
slide-19
SLIDE 19

Dynamic Typing

  • Type of the object it points to

○ Not checked at compile time

slide-20
SLIDE 20

Dynamic Binding

  • Method to invoke

○ Determined at runtime instead of compile time

  • Also referred to as late binding
  • Dynamic Binding enables polymorphism

○ Method to run is determined at runtime

Shape Circle draw() Square draw() Rectangle draw()

slide-21
SLIDE 21

Java - wiki

21

Oracle Corporation is the current owner of the official implementation of the Java SE platform, following their acquisition of Sun Microsystems on January 27, 2010. This implementation is based on the original implementation of Java by Sun. The Oracle implementation is available for Microsoft Windows (still works for XP, while only later versions currently "publicly" supported), Mac OS X, Linux and Solaris. Because Java lacks any formal standardization recognized by Ecma International, ISO/IEC, ANSI, or other third- party standards organization, the Oracle implementation is the de facto standard. The Oracle implementation is packaged into two different distributions: The Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs and is intended for end users, and the Java Development Kit (JDK), which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.

slide-22
SLIDE 22

Java Editions

22

  • Java Micro Edition ME
  • Java Standard Edition SE
  • Java Enterprise Edition EE
slide-23
SLIDE 23

Java Development Environment Setup

23

  • Download Java Standard Edition
slide-24
SLIDE 24

Java Development Environment Setup

24

  • Java SE (Java SE Development Kit 8)
  • Java Platform Standard Edition Development Kit
  • JDK is a development environment for building:
  • Applications
  • Applets
  • Components
  • JDK includes tools for:
  • Developing Programs written in Java
  • Testing Programs written in Java
slide-25
SLIDE 25

What is an IDE?

  • Stands for:
  • Integrated Development Environment
  • The application used for creating software programs
  • IDEs for Java:
  • Eclipse
  • IntelliJ
  • NetBeans
slide-26
SLIDE 26

Download Eclipse for Java Developers

26

  • Eclipse is an Integrated Development Environment IDE
slide-27
SLIDE 27


 Hello World Program

slide-28
SLIDE 28

Creating Hello World Program

  • Launch Eclipse
  • File New Java Project
  • Project Created
  • Add a new “Class” file to the project
  • File - New - Class
  • Add method
  • public static void main (String[] args)
  • First point of entry
  • System.out.println(“Hello World!”);
  • Prints formatted string to the console
slide-29
SLIDE 29

Package name

29

  • Use of default package is discouraged
  • Format should be aaa.bbb and all lower case
slide-30
SLIDE 30

print

  • print and println
  • System.out.print(“Hello”);
  • System.out.println(“Hi”);
  • Declaring multiple lines of text in 1 line
  • System.out.println( "Welcome\nto\nJava\nProgramming!" );
slide-31
SLIDE 31

Escape Sequence

31

slide-32
SLIDE 32

Naming Convention

  • Project Name
  • Start with capital
  • Program File Name
  • Same as class name
  • Package Name
  • All lower case
  • Method Names
  • Start with lower case
slide-33
SLIDE 33

Anatomy of a Java Program

33

Comments //single line /* multi line …. */ Reserved words Modifiers Statements Blocks Classes Methods The main method


Java is case sensitive!

slide-34
SLIDE 34

Reserved Words

slide-35
SLIDE 35

Identifier

35

  • A series of characters consisting of
  • letters, digits
  • underscores (_)
  • dollar signs ($)
  • Does not begin with a digit and
  • Does not contain spaces.
slide-36
SLIDE 36

Class

  • A class name is an identifier
  • By convention
  • class names begin with a capital letter

capitalise the first letter of each word they include

○ Example: MyJavaApplication

public class ProjectOne { //body }

slide-37
SLIDE 37

Good Programming

  • Comment your code
  • Add indentations to your code
  • Follow naming conventions
  • Use descriptive naming
  • Variable declaration starts with small letter, subsequent words are capital
  • myVariable
slide-38
SLIDE 38

Java API

38

A great strength of Java is its rich set of predefined classes that you can reuse rather than “reinventing the wheel.” These classes are grouped into packages (named groups of related classes) and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API).

The classes in the Java APIs are organized into separate groups called packages. Each package contains a set of related interfaces, classes and exceptions. Refer to the separate platforms for a description of the packages available.

slide-39
SLIDE 39

Import Declarations

39

  • Import declarations help the compiler locate a class that’s used in the program

import java.util.Scanner; // program uses class Scanner Import all missing classes in Eclipse Windows — Ctrl Shift o Mac — Command Shift o

slide-40
SLIDE 40

Primitive Data Types

  • byte
  • number 1 byte
  • short
  • number 2 bytes
  • int

○ Decimal number 1, 10, etc

  • long

○ Double precision int

  • float

○ Floating point number e.g. 0.3434343

  • double

○ Double precision floats

  • char

○ Single char ‘a’, ‘Z’, ‘3’, etc

  • boolean

○ true ○ false

Note:
 Range of variables is machine dependant and depends on the machine on which the program is running.

slide-41
SLIDE 41

Variable

  • Each variable has a memory address
  • A variable has a name
  • A value can be assigned to it
  • Naming convention: myVariable
  • Variable names cannot start with a number
slide-42
SLIDE 42

Type Cast Operator

  • Converts one type of data to another
  • For decimal numbers, the default is double

Casting is required with floats

○ float f = (float)87.54; ○ float f = 87.54f;

slide-43
SLIDE 43

Scanner: Reading input from console

43

import java.util.Scanner; public class MainClass { public static void main(String[] args) { // create a Scanner to obtain input from the command window Scanner input = new Scanner( System.in ); int num1; int num2; int sum; System.out.print( "Enter first integer: " ); // prompt num1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt num2 = input.nextInt(); // read second number from user sum = num1 + num2; // System.out.printf( "Sum is %d\n", sum ); // display sum } }

slide-44
SLIDE 44

Scanner: Reading input from console

44

import java.util.Scanner; public class MainClass { public static void main(String[] args) { // create a Scanner to obtain input from the command window

Scanner input = new Scanner( System.in ); float num1; float num2; float sum; System.out.print( "Enter first integer: " ); // prompt num1 = input.nextFloat(); // read first number from user System.out.print( "Enter second integer: " ); // prompt num2 = input.nextFloat(); // read second number from user sum = num1 + num2; // System.out.printf( "Sum is %f\n", sum ); // display sum

} }

slide-45
SLIDE 45

Scanner: Reading input from console

45

  • 1. Create a Scanner object

Scanner input = new Scanner(System.in);

  • 2. Use the methods to obtain values:
  • nextByte()
  • nextShort()
  • nextInt()
  • nextLong()
  • nextFloat()
  • nextDouble()
  • nextBoolean()
slide-46
SLIDE 46

boolean

46

boolean hungry = true; if(hungry) { System.out.println("Let's have some food!"); }

  • Note

if(hungry)

○ is equivalent to

  • if(hungry == true)
slide-47
SLIDE 47

String

47

  • The String class represents a sequence of characters
  • Can include letters, number and special characters
  • Stored in double “ quotes
  • Example
  • String s = “Mike”;
  • String s2 = new String(“Hello! How are you?”);
  • String s3 = “Mike is 16 years old.”;
  • String Methods
  • http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
slide-48
SLIDE 48

String

48

  • Can concat strings and primitives:

int age = 10; String s = "I am " + age + " years old" ; System.out.println(s);

slide-49
SLIDE 49

Strings

49

  • Declare and initialise your string
  • Print your string
  • Print first character of your string
  • Print the first 3 characters of your string
  • Add another string to your string (concatenation)
  • Replace word in your string
  • Compare strings
  • Get string length
  • Convert case
slide-50
SLIDE 50

Declaring Variables of same type

50

  • Variables of the same type can be declared on the same line:
  • int x,y,z
  • String firstname, lastname;
  • int myAge, mysize, numshoes= 28;
  • String firstName= “Laura”, lastName = “Thorpe”;
slide-51
SLIDE 51

Operators

51

  • Arithmetic
  • Assignment
  • Comparison
  • Logical
slide-52
SLIDE 52

Arithmetic Operators

  • Addition

○ b + c

  • Subtraction

○ b – c

  • Multiplication

○ b * c

  • Division

○ b / c

  • Modulus

○ b % c ○ Returns the remainder of a divided by b

slide-53
SLIDE 53

Arithmetic Operators

53

slide-54
SLIDE 54

Arithmetic Operators: Order of Evaluation

54

  • Order of evaluation:
  • *
  • /
  • %
  • +
  • -
  • =
slide-55
SLIDE 55

Increment and Decrement Operators

  • a = a + 1

○ is equivalent to a++ is equivalent to a+=1;

  • a = a -1

○ is equivalent to a— is equivalent to a-=1;

  • What is the difference between the following two?

○ a++ ○ ++a

slide-56
SLIDE 56

Basic Assignment Operator

  • Examples

○ c = a + b ○ d = a - b ○ e = a * b ○ f = a / b ○ g = f

slide-57
SLIDE 57

The Comparison Operators

  • Returns a Boolean

True = 1

False = 0

  • if (a == b)

if a is equal to b

  • if (a != b)

if a is not equal to b

  • if (a < b)

if a is less than b

  • if (a > b)

if a is greater than b

  • if (a <= b)

if a is less than or equal to b

  • if (a >= b)

if a is greater than or equal to b

slide-58
SLIDE 58

The Comparison Operators

slide-59
SLIDE 59

The Compound Assignment Operators

  • a += b

○ a = a + b

  • a -= b

○ a = a -b

  • a *= b

○ a = a * b

  • a /= b

○ a = a / b

  • a %= b

○ a = a % b

slide-60
SLIDE 60

The Boolean Logical Operators

  • Take Boolean values as operands
  • Boolean values are 0 or 1

○ 0 = false ○ 1 = true

  • Logical Negation (NOT)

○ !

  • Logical (AND)

○ &&

  • Logical (OR)

○ ||

slide-61
SLIDE 61

Precedence

61

slide-62
SLIDE 62

The Ternary Operator

  • [condition] ? [true expression] : [false expression]
  • Condition must return true or false
  • If condition returns true

○result of the first expression is returned

  • If condition returns false

○result of the second expression is returned

slide-63
SLIDE 63

Programming Decision: if

if (expression1 is true) {

Execute statement1

}

slide-64
SLIDE 64

if (Single-Selection Statement)

64

slide-65
SLIDE 65

if (Double-Selection Statement)

65

  • Can also have
  • if - else if - else
slide-66
SLIDE 66

if - else if - else

if (expression 1 is true) {

Execute statement 1

} else if (expression2 is true) {

Execute statement 2

} else {

Execute statement 3

}

  • Exercise: set a variable to 100
  • Prompt user to guess number
  • if user enters 100 print “correct”
  • if between 90 and 110 print “in range” and higher or lower depending on guess
  • if out of range print higher or lower
slide-67
SLIDE 67

Tip

  • x

if (number % 2 == 0)

even = true; else even = false;

(a) Equivalent

boolean even = number % 2 == 0;

(b)

if (even == true)

System.out.println( "It is even.");

(a) Equivalent

if (even) System.out.println( "It is even.");

(b)

slide-68
SLIDE 68

the ternary operator

  • [condition] ? [true expression] : [false expression]
  • Condition must return true or false
  • If condition returns true

○ result of the first expression is returned

  • If condition returns false

○ result of the second expression is returned

slide-69
SLIDE 69

switch

switch (expression) { case 1: Statement 1 break; case 2: Statement 2 break; case n: Statement n break; default: Default Statement }

  • A switch works with byte, short, char, and int primitive data types.
  • It also works with String
slide-70
SLIDE 70

Switch Example

70

String sName = "Nina"; String favouriteColour; switch (sName.toLowerCase()) { case "rose": favouriteColour = "Yellow"; break; case "jack": favouriteColour = "Green"; break; case "sebastien": favouriteColour = "Blue"; break; case "nina": favouriteColour = "Orange"; break; default: favouriteColour = "Unknown"; break; } System.out.println(favouriteColour);

slide-71
SLIDE 71

Several case labels

71

char c = 'N'; switch(c) { case 'n': case 'N': System.out.println("NO"); break; case 'y': case 'Y': System.out.println("YES"); break; }

slide-72
SLIDE 72

Looping

slide-73
SLIDE 73

for statement

  • for statement

○ for (initialisation; condition; expression)

{ Statement(s) }

for(int i=0; i<5; i++) { System.out.println(i); }

slide-74
SLIDE 74

Guess Age

int myAge = 15; Scanner input = new Scanner( System.in ); int guess; do { System.out.print( "Guess my age: " ); guess = input.nextInt(); if(guess < 10) { System.out.println("Out of range - try higher"); } if(guess > 20) { System.out.println("Out of range - try lower"); } if(guess < 20 && guess > 10) { if(guess == 15) { System.out.println("Well done! 15 is correct."); } if(guess < 15) { System.out.println("Close - try higher"); } if(guess > 15) { System.out.println("Close - try lower"); } } }while(guess != myAge);

slide-75
SLIDE 75

Times Table Method

75 public static void times(int n) { for(int i=0; i<11; i++) { System.out.printf("%d times %d is %d \n", i, n, n*i ); } }

slide-76
SLIDE 76

Loop

  • Repeating a loop n times

Exercise: Modify the previous example to repeat 10 times

slide-77
SLIDE 77

infinite loop

  • infinite loop

for ( ; ; )

{ Statement(s) }

slide-78
SLIDE 78

while statement

  • while statement

white (expression)

{ Statement(s) }

int a = 1; while(a<10) { System.out.println(a); a+=3; }

slide-79
SLIDE 79

do while statement

  • do while statement

do {

Statement(s) } while (expression);

  • do while loops are used when the statement has to be executed
  • At least once

int a = 100; do{ System.out.println(a); a-=10; }while(a>20);

slide-80
SLIDE 80

break statement

  • break statement

○ Exit from the loop entirely

  • Syntax

○ break;

  • Output

○ a + b = 4 ○ a + b = 5 ○ a + b = 6 ○ a + b = 7 ○ a + b = 8 ○ a + b = 9

slide-81
SLIDE 81

continue statement

  • continue statement

○ Exit current loop Do not execute the code after the continue statement

○ for current loop

○ Do not exit the loop entirely ○ Continue execution of loop

  • Syntax

○ continue;

  • Output

○ a + b = 4 ○ a + b = 5

slide-82
SLIDE 82

break and continue example

82

for(int i=0; i<20; i++) { if(i == 15) break;

// break out of for loop

if(i % 2 != 0) continue; // go to next iteration System.out.println(i); }

slide-83
SLIDE 83

Methods

slide-84
SLIDE 84

Defining and Invoking Methods

  • public static int max(int num1, int num2) {

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

modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method

int z = max(x, y);

actual parameters (arguments) method signature

slide-85
SLIDE 85

The Anatomy of a Method

85

  • modifier
  • It defines the access type of the method and it is optional to use.
  • returnType
  • Method may return a value.
  • methodName
  • This is the method name.
  • Parameter List
  • The list of parameters, it is the type, order, and number of parameters of a method.
  • These are optional, method may contain zero parameters.
  • method body
  • The method body defines what the method does with statements.
slide-86
SLIDE 86

Method Visibility

86

  • Public
  • In all classes and packages
  • Private
  • Only in current class
  • Protected
  • In current package
  • In subclasses
slide-87
SLIDE 87

Access Modifiers at a glance

87

slide-88
SLIDE 88

private

88

  • 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. Class and interfaces cannot be private.
  • Variables that are declared private can be accessed
  • utside the class, if public getter methods are present

in the class.

  • Using the private modifier is the main way that an
  • bject encapsulates itself and hides data from the
  • utside world.
slide-89
SLIDE 89

public

89

  • A class, method, constructor, interface, etc. declared

public can be accessed from any other class.

  • Therefore, fields, methods, blocks declared inside a public

class can be accessed from any class belonging to the Java Universe.

  • However, if the public class we are trying to access is in a

different package, then the public class still needs to be

  • imported. Because of class inheritance, all public methods

and variables of a class are inherited by its subclasses.

slide-90
SLIDE 90

protected

90

  • Variables, methods, and constructors, which are

declared protected in a superclass can be accessed

  • nly by the subclasses in other package or any class

within the package of the protected members' class.

  • The protected access modifier cannot be applied to

class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

  • Protected access gives the subclass a chance to use

the helper method or variable, while preventing a non-related class from trying to use it.

slide-91
SLIDE 91

Method Implementation & Call

91

Method Implementation

public static int funcName(int a, int b) { // body }

Method Call

funcName(a, b); int min= funcName(a, b);

slide-92
SLIDE 92

Minimum Number

92

  • Method to find minimum number

public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }

slide-93
SLIDE 93

Benefits of Methods

93

  • Write a method once and reuse it anywhere
  • Information hiding
  • Hide the implementation from the user
  • Reduce complexity
slide-94
SLIDE 94

Built-in versus User-defined Methods

  • We have built-in methods and user defined methods
  • Built-in Methods

Come with Java and are ready to be used

  • User defined Methods

Defined by the programmer

slide-95
SLIDE 95

Example: Built-in method call

95

int a = 10; int b = 11; int min; min = Math.min(a,b); System.out.println(min);

slide-96
SLIDE 96

Built-in Method Examples

  • print();
  • println();
  • Exercise 1:
  • List all the built-in Math methods
  • Exercise 2:
  • Write a method that finds the distance between 2 points
slide-97
SLIDE 97

More on Methods

97

  • Method Definition/Implementation
  • Method Call
  • Can store the result of the method call in a variable
slide-98
SLIDE 98

Method Example

98

//Within main method MainClass mc = new MainClass(); mc.showWelcomeMessage("narges", 80); //Method Implementation

public void showWelcomeMessage(String welcomeName, int grade) {

System.out.printf( "Welcome %s your grade is %d ",welcomeName, grade );

}

slide-99
SLIDE 99

User Defined Methods Exercise

99

  • Exercise:
  • Write a method to convert from Fahrenheit to Celsius
slide-100
SLIDE 100

Class & Method Declarations

100

public class MainClass { public static void main(String[] args) { One one = new One();

  • ne.showMessage();

} } public class One { public void showMessage() { System.out.println("Welcome to ClassOne"); } }

slide-101
SLIDE 101

Method with Parameter

101

import java.util.Scanner; public class MainClass { public static void main(String[] args) { Scanner input = new Scanner( System.in ); System.out.println( "Please enter your name: " ); String name = input.nextLine(); WelcomeYou wy = new WelcomeYou(); wy.showWelcomeMessage(name); input.close(); } } public class WelcomeYou { public void showWelcomeMessage(String welcomeName) { System.out.printf( "Welcome %s ",welcomeName ); } }

slide-102
SLIDE 102

instance variables & Setter Getter Methods

102

  • Class Person


 private String firstName; private String lastName; private int age; public void displayMessage() { System.out.printf("Welcome %s %s", getFirstName(), getLastName()); System.out.printf("\n Your age is %d", getAge()); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } //Other Getter and Setter Methods

slide-103
SLIDE 103

Generate Getter and Setter Methods

103

slide-104
SLIDE 104

Generate Getter and Setter Methods

104

slide-105
SLIDE 105

instance variables & Setter Getter Methods

105

  • MainClass

Person person = new Person("Nina");

  • Person

private String firstName; public Person(String name) { firstName = name; System.out.printf("Hello %s", firstName); } //Getter and Setter Methods

slide-106
SLIDE 106

Constructor

106

  • Special type of method
  • Has the same name as the Class
  • Has no return value
  • Initialises class objects
  • May call its super constructor on the first line
slide-107
SLIDE 107

Inheritance

107

public class Animal { //body } public class Dog extends Animal { //body }

slide-108
SLIDE 108

Inheritance

108

public class Parent { public p1() { System.out.println(“parent”); } } public class Child extends Parent { public c1() { System.out.println(“Child"); } } //In main method Child cobj=new Child(); cobj.c1(); cobj.p1();

slide-109
SLIDE 109

Method Overloading

109

  • Can have multiple methods with the same name in the class
  • As long as each method accept different sets of argument types

public void showWelcomeMessage(String welcomeName) { System.out.printf( "Welcome %s your grade is %d ",welcomeName); } public void showWelcomeMessage(String welcomeName, int grade) { System.out.printf( "Welcome %s your grade is %d ",welcomeName, grade ); }

slide-110
SLIDE 110

Overloading Example

110

public static void printArray(Integer[] inputArray) { for (Integer element : inputArray) System.out.printf("%s ", element); System.out.println(); } public static void printArray(Double[] inputArray) { for (Double element : inputArray) System.out.printf("%s ", element); System.out.println(); } public static void printArray(Character[] inputArray) { for (Character element : inputArray) System.out.printf("%s ", element); System.out.println(); } Integer[] integerArray = { 10, 22, 3, 4, 5 }; Double[] doubleArray = { 1.5, 54.2, 3.3, 8.4, 53.9, 34.8, 9.0 }; Character[] characterArray = { 'W', 'E', 'L', 'C', 'O', 'M', 'E'}; System.out.println("integerArray contains:"); printArray(integerArray); System.out.println("doubleArray contains:"); printArray(doubleArray); System.out.println("characterArray contains:"); printArray(characterArray);

slide-111
SLIDE 111

More on Java

slide-112
SLIDE 112

Static Variables, Constants, and Methods

112

  • Static variables
  • Shared by all the instances of the class.
  • Static methods
  • Not tied to a specific object
  • Static constants
  • Final variables

Shared by all the instances of the class.

slide-113
SLIDE 113

Class instantiation

113

  • GameManager game = new GameManager();
slide-114
SLIDE 114

Java Superclass

  • Superclass of all objects in Java
slide-115
SLIDE 115

String Array

115

String[] names = new String[3]; names[0] = “Android"; names[1] = “iOS"; names[2] = “Linux”; ////////////////////////////////////////////////////////// String[] nama; nama = new String[] {“Jack","Joanne","Jay"};

slide-116
SLIDE 116

int Array

116

int[] myArray; myArray = new int[3]; myArray[0] = 1; myArray[1] = 3; myArray[2] = 4; ////////////////////////////////////////////////////////// int[] anotherArray = {1, 2, 3, 4, 5};

slide-117
SLIDE 117

Iterating through an array

117

int[] myArray; myArray = new int[3]; myArray[0] = 1; myArray[1] = 3; myArray[2] = 4; for(int i = 0; i<myArray.length; i++) { System.out.println(myArray[i]); }

slide-118
SLIDE 118

Iterating through an array

int[] numArray = {5, 100, 34, 400, 520, 0}; for( int num : numArray) { System.out.println(num); }

Exercise: Print the sum of array numbers

slide-119
SLIDE 119

Sum of array elements

119

int[] numArray = {5, 100, 34, 400, 520, 0}; int sum = 0; for( int num : numArray) { System.out.println(num); sum = sum + num; } System.out.println("Sum of array numbers is:"+sum);

slide-120
SLIDE 120

Java Collection

120

  • A collection is a data structure
  • Access to data is possible through predefined methods
  • List
  • Set
  • Map
slide-121
SLIDE 121

Java Collection

121

  • List
  • Ordered Collection
  • May contain duplicate elements
  • Types:
  • ArrayList
  • LinkedList
  • Vector
slide-122
SLIDE 122

Java Collection

122

  • Set
  • Cannot contain duplicate elements
  • Main types:
  • HashSet
  • Best performing
  • Not ordered
  • TreeSet
  • Elements ordered based on value
  • LinkedHashSet
  • Orders elements based on order in which they were

added

slide-123
SLIDE 123

Java Collection

123

  • Map
  • Maps keys to values
  • Cannot contain duplicate keys
  • Three main types:
  • HashMap
  • TreeMap
  • LinkedHashMap
slide-124
SLIDE 124

ArrayList Example

124

ArrayList<String> cars = new ArrayList<String>(); cars.add("BMW"); cars.add("Audi"); cars.add("Land Rover"); Iterator<String> it = cars.iterator(); while(it.hasNext()) { String str = (String)it.next(); System.out.println(str); }

slide-125
SLIDE 125

ArrayList Example

125

package collections.example; import java.util.ArrayList; import java.util.Iterator; public class MainCollectionClass { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("BMW"); cars.add("Audi"); cars.add("Land Rover"); Iterator<String> it = cars.iterator(); while(it.hasNext()) { String str = it.next(); System.out.println(str); } } }

slide-126
SLIDE 126

Spot the difference

126

package collections.example; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class MainCollectionClass { public static void main(String[] args) { List<String> cars = new ArrayList<String>(); cars.add("BMW"); cars.add("Audi"); cars.add("Land Rover"); Iterator<String> it = cars.iterator(); while(it.hasNext()) { String str = it.next(); System.out.println(str); } } }

slide-127
SLIDE 127

List Interface

127

  • Inspect the List interface
  • What methods does it provide
  • Exercise:
  • Use methods in List interface
slide-128
SLIDE 128

128

System.out.println(cars.size()); if(cars.contains(“Audi")) { System.out.println("Audi in list"); }

slide-129
SLIDE 129

HashMap Example

129 HashMap<Integer, String> myHMap = new HashMap<Integer, String>(); //Adding elements myHMap.put(3, "Effective Java"); myHMap.put(0, "Java Generics"); myHMap.put(25, "Thinking in Java"); myHMap.put(9, "Java Application Development"); //Iterator Set set = myHMap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry mentry = (Map.Entry)iterator.next(); System.out.print("key: "+ mentry.getKey() + " Book: "); System.out.println(mentry.getValue()); }

slide-130
SLIDE 130

HashMap Example

130 System.out.println(myHMap.get(25)); myHMap.remove(9); //Iterator 2 Set set2 = myHMap.entrySet(); Iterator iterator2 = set2.iterator(); while(iterator2.hasNext()) { Map.Entry mEntry = (Map.Entry)iterator2.next(); System.out.print("key: "+ mEntry.getKey() + " Book: "); System.out.println(mEntry.getValue()); }

slide-131
SLIDE 131

HashMap Example

131

  • Exercise:
  • Get and print a particular item
  • Remove an item from the HashMap
  • Print the items again
slide-132
SLIDE 132

HashMap Example

132

System.out.println(myHMap.get(25)); myHMap.remove(9); //Iterator 2 Set set2 = myHMap.entrySet(); Iterator iterator2 = set2.iterator(); while(iterator2.hasNext()) { Map.Entry mEntry = (Map.Entry)iterator2.next(); System.out.print("key: "+ mEntry.getKey() + " Book: "); System.out.println(mEntry.getValue()); }

slide-133
SLIDE 133

HashMap Example

133

  • Postcodes as key
  • People who live at that postcode in list as values
slide-134
SLIDE 134

Date

  • Represents a single point in time
  • new Date() returns current date and time

Date date = new Date(); System.out.println(date.toString());

slide-135
SLIDE 135

Date Formatting

  • Can format date using SimpleDateFormat
  • Input parameter is the date format e.g. dd/MM/yyyy

Date mydate=new Date(); DateFormat dateformat=new SimpleDateFormat("dd/MM/yyyy"); String date_now= dateformat.format(mydate); System.out.println(date_now); //Combining the above code into 1 line System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(new Date()));

slide-136
SLIDE 136

Random Number Generator

136 Random randomNo = new Random(); System.out.println(randomNo.nextInt(50)); Exercise: Generate 6 random numbers between 0 and 50