1 object oriented programming with java references: java jdk6 documentations. java™ how to...

54
1 Object Oriented Programming with JAVA References: •Java JDK6 documentations. http://java.sun.com/javase/ •Java™ How to Program, Sixth Edition Instructor: Haya Sammaneh

Upload: samson-robbins

Post on 25-Dec-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

1

Object Oriented Programmingwith

JAVA

References:•Java JDK6 documentations. http://java.sun.com/javase/

•Java™ How to Program, Sixth Edition

Instructor: Haya Sammaneh

Page 2: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

2

History of Java

• Java– Originally for intelligent consumer-electronic

devices (cell phones)

– Then used for creating Web pages with dynamic content

– Now also used for:• Develop large-scale enterprise applications

Page 3: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

3

The Java Programming Language

• A high-level language that can be characterized by all of the following:

– Simple– Object oriented– Portable– Distributed– High performance– Multithreaded– Robust– Secure

Page 4: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

4

Java life cycle• Java programs normally undergo four phases

– Edit

• Programmer writes program (and stores program on disk)

– Compile

• Compiler creates bytecodes from program (.class)

– Load

• Class loader stores bytecodes in memory

– Execute

• Interpreter: translates bytecodes into machine language

Page 5: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

5

Java life cycle

• Source code (.java)

• Compiled into Byte codes (.class) , as (.exe) in c++

– The Java Application Programming Interface(API)

– a large collection of ready-made software components. It is grouped into libraries of related classes and interfaces; these libraries are known as packages.

– Java Virtual Machine (JVM)

– Machine code

Page 6: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

6

Java life, cont..

Page 7: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

7

JVM an Portability• Through the Java VM, the same application is

capable of running on multiple platforms.

Page 8: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

8

Java Technology• Java EE vs. Java SE

– EE: enterprise edition (web services, distribution, RMI, …)– SE: standard edition (stand alone app.)

• Development Tools– The main tools you'll be using are the javac compiler, the

java launcher (java), and the javadoc documentation tool.

• Application Programming Interface (API)– Java SE Development Kit 6 (JDK 6)– Offers a wide array of useful classes ready for use in your

own applications.

Page 9: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

9

Java Technology, cont…

• User Interface Toolkits– Swing and Java 2D toolkits to create Graphical

User Interfaces (GUIs).

• Integration Libraries– Application Programming Interface (API)– Java RMI, and Java Remote Method Invocation

over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access.

Page 10: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

10

Before you start• Install the Java SE Development

Kit 6 (JDK 6).

• Modify the Java Path environment.– Go to the System Properties by right

clicking you My Computer and choosing properties Environment variablesclick on TEMP Edit.

– Add the path to the java bin directory as shown in the next slid.

• Install the Textpad editor which we will use to develop our applications.

Page 11: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

11

Modifying the Path Environment variable.

Page 12: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

12

Hello world• To begin you need a text editor.

– Notepad, TextPad, …– Create a new directory on C: name it JavaProjects.

• Open new file, save it as HelloWorld.java in new directory HelloWorld inside the JavaProjects Directory.

• Write the following code and save the file:

class HelloWorld {/*simple java application*/public static void main(String[] args) {System.out.println(“Hello World”); //displays a string }}• Note: the file name should have the same name as the class

Page 13: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

13

Compiling and running• Assuming the HelloWorld.java is saved in the c:\JavaProjects\HelloWorld

directory:

• Open the a Console, (startRun…), type cmd.

• Type cd \ to return to c:>

• Go to the helloworld directry– (cd c:\JavaProjects\HelloWorld)

• compile your application– javac HelloWorld.java

• Run your application– java HelloWorld.class

• Note: Type all code, commands, and file names exactly as shown. Both thecompiler (javac) and launcher (java) are case-sensitive

Page 14: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

14

Closer Look• Three primary components: source code comments, the

HelloWorld class definition, and the main method.

• Comments are ignored by the compiler but are useful to other programmers.

• Two supported kinds of comments– /* text */ The compiler ignores everything from /* to */.

– // text The compiler ignores everything from // to the end of the line.

• The most basic form of a class definition is– class name {…}– Every program must have at least one class, and this class should

contain the main method.

Page 15: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

15

Closer Look, cont…• In the Java programming language, every application must

contain a main method whose signature is:– public static void main(String[] args)– The modifiers public and static can be written in either order (public

static or static public).– You can name the argument anything you want, but most programmers

choose "args" or "argv.“

• This is the string array that will contains the command line arrguments.– The main method is the entry point for your application and will

subsequently invoke all the other methods required by your program.

• System.out.println("Hello World!");– uses the System class from the API to print the "Hello World!" message

to standard output.

Page 16: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

16

Example, Prints.java

import java.lang.System;

class Prints{public static void main(String[] args){System.out.print(":Haya ");System.out.println("This Text in one line");System.out.printf("\nFormated text;\n%s\t%s\n%s\t%d\n%s\t%d\

n","Student","Mark","Ahmad",3,"Sami",5);

System.out.printf(" %x\n",15); // f

System.out.printf(" %o\n",15); // 17}}

• %o for octal, %x for hexadicemal, %f for floating point representations.

Page 17: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

17

Page 18: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

18

Example

– Name of class called identifier• Series of characters consisting of letters, digits,

underscores ( _ ) and dollar signs ( $ )

• Does not begin with a digit, has no spaces

• Java is case sensitive

• Examples: Print, $Print, _Print, Print7 is valid– 7print is invalid

Page 19: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

19

Summation of two numbersExample

import java.util.Scanner; // program uses class Scannerpublic class Summation{public static void main( String args[] ){// create Scanner to obtain input from command windowScanner input = new Scanner( System.in );int number1;int number2;int sum;System.out.print( "Enter first integer: " );number1 = input.nextInt(); // read first number from userSystem.out.print( "Enter second integer: " );number2 = input.nextInt(); // read second number from usersum = number1 + number2; // add numbersSystem.out.printf( "Sum is %d\n", sum ); // display sum

Page 20: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

20

Summation – cont.• import: used to get the library (Java API) contains the definition for the used

classes– We need the scanner class defined in java.util.scanner package

– All imports must be at the beginning, before class definition.

– Using a Java API without importing the required package cause syntax error.

– A Scanner enables a program to read data (e.g., numbers). The data can come from many sources, such as a file on disk or the user at the keyboard (System.in).

– By default, package java.lang is imported in every Java program, this package contains the definition for “System” class.

– We uses Scanner object input's “nextInt” method to obtain an integer from the user at the keyboard.

Page 21: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

21

Object-Oriented Programming Concepts

• What Is an Object?

• What Is a Class?

• What Is Inheritance?

• What Is an Interface?

• What Is a Package?

Page 22: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

22

What Is an Object?

– Real world consists of objects (desk, your television set, your bicycle).

– They share two characteristics: They all have state and behavior.

• Bicycles have state (current gear, current speed) and behavior (changing gear, applying brakes).

– Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation.

Page 23: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

23

What Is an Object? – cont.

• Grouping code into individual software objects provides a number of benefits, including:

– Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

– Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

– Code re-use: If an object already exists , you can use that object in your program.

– Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its

Page 24: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

24

What Is a Class?

– In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

class Bicycle {int speed = 0;int gear = 1;void changeGear(int newValue) { gear = newValue; }void speedUp(int increment) { speed = speed + increment; }void applyBrakes(int decrement) { speed = speed - decrement; }void printStates() { System.out.println( speed:"+speed+"

gear:"+gear); }

}

Page 25: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

25

What Is a Class? – cont.• Here's a BicycleDemo class that creates two separate Bicycle objects and

invokes their methods:

class BicycleDemo {public static void main(String[] args) {// Create two different Bicycle objectsBicycle bike1 = new Bicycle();Bicycle bike2 = new Bicycle();// Invoke methods on those objectsbike1.speedUp(10);bike1.changeGear(2);bike1.printStates();bike2.speedUp(10);bike2.changeGear(2);bike2.speedUp(10);bike2.changeGear(3);bike2.printStates();}

}

Page 26: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

26

What Is Inheritance?

• Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

• The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle{// new fields and methods defining a mountain bike// would go here}

Page 27: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

27

What Is an Interface?• An interface is a group of related methods with empty bodies.

interface Bicycle{

void changeGear(int newValue);void speedUp(int increment);void applyBrakes(int decrement);

}

• To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration:

class ACMEBicycle implements Bicycle{// remainder of this class implemented as before}

Page 28: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

28

What Is a Package?

• A package is a namespace that organizes a set of related classes and interfaces.

• you can think of packages as being similar to different folders on your computer.

Page 29: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

29

Language Basics

• Variables

• Operators

• Expressions, Statements, and Blocks

• Control Flow Statements

Page 30: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

30

Variables

Four kinds:– Instance Variables (Non-Static Fields).

• Values are unique to each instance (object) of a class

– Class Variables (Static Fields).• There is exactly one copy of this variable in existence.

– Local Variables.

– Parameters.

Page 31: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

31

Variables – Naming

• Variable names are case sensitive.

• Can be any legal identifier an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign, "$", or the underscore character, "_".

• If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. Ex: GearRatio

Page 32: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

32

Variables - Primitive Data Types

• byte: 8-bit signed integer.

• short : 16-bit signed integer

• int: 32-bit signed integer

• long: 64-bit signed integer

Page 33: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

33

Variables - Primitive Data Types

• float: 32-bit– This data type should never be used for precise values, such as

currency. For that, you will need to use the java.math.BigDecimal class instead.

• double: 64-bit

• boolean: has only two possible values: true and false.

• char:The char data type is a single 16-bit Unicode character. ('\u0000' (or 0) to '\uffff' (or 65,535).

• String object; for example, String s = "this is a string";. Once created, their values cannot be changed.

Page 34: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

34

Page 35: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

35

Literals– Ex: boolean result = true; char capitalC = 'C' ; byte b = 100; short s =10000; int i = 100000;

• int:– int decVal = 26; // The number 26, in decimal– int hexVal = 0x1a; // The number 26, in hexadecimal

• float and double:– E or e (for scientific notation)– F or f (32-bit float literal)– D or d (64-bit double literal).– double d1 = 123.4;– double d2 = 1.234e2; // same value as d1, but in scientific notation– float f1 = 123.4f;

Page 36: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

36

Literals – cont.

• char and String:

– char ch='\u0108‘;

Page 37: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

37

Arrays

• An array is a container object.• Each item in an array is called an element, and each element is

accessed by its numerical index.

• Declaring a Variable to Refer to an Array– type[] <arrayname>;– Ex:• int[] arrayOfIntegers;• float arrayOfFloats[ ]; // this form is discouraged

• Creating, Initializing, and Accessing an Array– <array_name>=new type[<size>];– Ex:• arrayOfIntegers = new int[10]; // create an array of integers• Or you can create and initialize at the same time:• int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Page 38: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

38

Page 39: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

39

Multidimensional Arrays

• int b[][] = { { 1, 2 }, { 3, 4, 5 } };

• int b[][];

b = new int [ 3 ][ 4 ];

• int b[][];b = new int[ 2 ][ ]; // create 2 rows

b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0

b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

Page 40: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

40

Operator

Page 41: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

41

Operators – cont.

• The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo

class ConcatDemo{

public static void main(String[] args){String firstString = "This is";String secondString = " a concatenated string.";String thirdString = firstString+secondString;System.out.println(thirdString);}

}

Page 42: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

42

Page 43: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

43

Expressions, Statements, and Blocks

• An expression is a construct made up of variables, operators, and method invocations.

1 * 2 * 3x + y / 100 // ambiguous(x + y) / 100 // unambiguous, recommendedx + (y / 100) // unambiguous, recommended

• A statement forms a complete unit of execution.aValue = 8933.234; // assignment statementaValue++; // increment statementSystem.out.println("Hello World!"); // method invocation // statementBicycle myBike = new Bicycle(); // object creation // statement

Page 44: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

44

Expressions, Statements, and Blocks

• A block is a group of zero or more statements between balancedbraces and can be used anywhere a single statement is allowed.

class BlockDemo {public static void main(String[] args) {boolean condition = true;

if (condition) { // begin block 1System.out.println("Condition is true."); } // end block oneelse { // begin block 2System.out.println("Condition is false.");} // end block 2

}}

Page 45: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

45

Control Flow Statements

• Decision-making statements– if, if-else, switch

• The looping statements– for, while, do – while

• The branching statements– break, continue, return

Page 46: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

46

Decision-making statements. void applyBrakes(){

if (isMoving){ // the "if" clause: bicycle must be movingcurrentSpeed--; // the "then" clause: // decrease current speed}}• The opening and closing braces are optional, provided that the"then" clause contains only one statementvoid applyBrakes(){if (isMoving) {currentSpeed--;}else {System.err.println("The bicycle has already stopped!");}

}

Page 47: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

47

Page 48: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

48

Page 49: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

49

Page 50: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

50

Page 51: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

51

The while and do-while Statements• Ex1:class WhileDemo {

public static void main(String[] args){int count = 1;while (count < 11) {System.out.println("Count is: " + count); count++;}}

}• Ex2:class DoWhileDemo { public static void main(String[] args){

int count = 1;do { System.out.println("Count is: " + count); count++; } while (count <=11);}

}

Page 52: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

52

The for Statement and continue.

• class PsDemo {public static void main(String[] args) {String searchMe = "peter piper picked a peck of " + "pickled

peppers";int max = searchMe.length();int numPs = 0;for (int i = 0; i < max; i++) { //interested only in p'sif (searchMe.charAt(i) != 'p')continue; //process p'snumPs++;}System.out.println("Found " + numPs + " p's in the string.");}

}

Page 53: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

53

The for statement and break.class BreakDemo {

public static void main(String[] args) {int[ ] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };int searchfor = 12;int i;boolean foundIt = false;for (i = 0; i < arrayOfInts.length; i++) {if (arrayOfInts[i] == searchfor) {foundIt = true;break; //<<<<<<<<<<<<<<<<<<<<the break statement}}if (foundIt) {System.out.println("Found " + searchfor + " at index " + i);}else {System.out.println(searchfor + " not in the array");}}

}

Page 54: 1 Object Oriented Programming with JAVA References: Java JDK6 documentations.  Java™ How to Program, Sixth Edition Instructor:

54

continue and break with lableclass BreakWithLabelDemo {

public static void main(String[] args) {int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77,

955 } };int searchfor = 12;int i;int j = 0;boolean foundIt = false;search: //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<labelfor (i = 0; i < arrayOfInts.length; i++) {for (j = 0; j < arrayOfInts[i].length; j++) {if (arrayOfInts[i][j] == searchfor) {foundIt = true;break search; //<<<<<<<<< break with label}}}if (foundIt) {System.out.println("Found " + searchfor + " at " + i + ", " + j); }else {System.out.println(searchfor + " not in the array"); } } }