Top Banner
Copyright © 2007, Infosys Technologies Ltd Java Programming - Day 1 Long Cycle - JEE ER/CORP/CRS/LA10LC/001 Ver. No.: 2:0
65
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Programming Slides01 Fp2007 Ver1.0

Copyright © 2007, Infosys Technologies Ltd

Java Programming - Day 1

Long Cycle - JEE

ER/CORP/CRS/LA10LC/001 Ver. No.: 2:0

Page 2: Java Programming Slides01 Fp2007 Ver1.0

2

Course Objectives

• To revise Object Oriented Programming concepts • To introduce Java architecture and the basic syntax of Java • To introduce the implementation of object oriented concepts using Java • To introduce the Java library• To introduce exception handling in Java• To introduce annotations in Java• To introduce JUnit• To introduce QA4J

Page 3: Java Programming Slides01 Fp2007 Ver1.0

3

Course Agenda (1/3)

• Day1– Object Oriented Concepts

– The Java Architecture

– The basic constructs in Java

– Arrays

• Day 2– OO SDLC

– Classes and Objects

– Constructors

– Method Overloading

– Static Members

– Command Line Arguments

– Class Relationships

Page 4: Java Programming Slides01 Fp2007 Ver1.0

4

Course Agenda (2/3)

• Day 3– Method Overriding

– Abstract classes

– Dynamic Binding and Runtime Polymorphism

– The final keyword

– Interfaces

– Packages

• Day 4– The Java Library

– Exception Handling

– Generics

– The Collection Framework

Page 5: Java Programming Slides01 Fp2007 Ver1.0

5

Course Agenda (3/3)

• Day 5– Annotation

– JUnit

– QA4J

Page 6: Java Programming Slides01 Fp2007 Ver1.0

6

References

• Herbert Schildt, “The Complete Reference, Java J2SE 5 Edition”, Tata McGraw Edition

• Sierra, Kathy and Bates, Bert, “Head First Java, 2nd Edition”, Shroff Publishers

Page 7: Java Programming Slides01 Fp2007 Ver1.0

7

Session Plan – Day 1

• Object Oriented Concepts• The Java Architecture • The basic constructs in Java • Arrays

Page 8: Java Programming Slides01 Fp2007 Ver1.0

8

What is Java and where is Java being used?

• Java is a very powerful OO programming language developed by Sun Microsystems

• Java is widely used for developing web applications• Java is the programming language used for developing Enterprise

Applications using the JEE Platform

Page 9: Java Programming Slides01 Fp2007 Ver1.0

9

Course Pre-Requisites

• The participants should have knowledge of C as a programming language

Page 10: Java Programming Slides01 Fp2007 Ver1.0

10

Expectations

• At the end of this course, the participants are expected to be proficient in the following

– Object Oriented Programming using Java

Page 11: Java Programming Slides01 Fp2007 Ver1.0

Copyright © 2007, Infosys Technologies Ltd

Object Oriented Programming – A Quick Revision

Page 12: Java Programming Slides01 Fp2007 Ver1.0

12

Software Complexity

• There are two categories of software

– Software developed for individuals for their own use

– Industrial strength software normally used by many people

• Industrial strength software is very complex in nature because of several

reasons

– Numerous Business rules (Functional Requirements)

– Non-Functional Requirements like Usability, Performance, Reliability etc

– Complexity due to development process

Page 13: Java Programming Slides01 Fp2007 Ver1.0

14

Ways to handle Software Complexity

• Unstructured Programming

– Use of goto statements

– Lengthy code with no modularity

– As size increases, code becomes more complex to maintain

• Procedural Programming or Structured Programming was introduced to

handle software complexity

– Brought in Modularity in coding, enhancing maintainability

– Complexity made manageable by hiding complexity inside functions (Concept

of APIs)

– Introduced the concept of structures (also known as data structures)

Page 14: Java Programming Slides01 Fp2007 Ver1.0

15

Limitations of Structured Programming

• In structured programming, focus is on the algorithm and importance is

given to the procedure (logic) and not to the data on which these

procedures operate

• The entire problem was divided into a number of smaller units

– Functions/Procedures

• All these units need to work on a data item to produce the result

– The data need to be global

– Global data made the code complex

• As the code size grows, maintaining code becomes difficult

Page 15: Java Programming Slides01 Fp2007 Ver1.0

16

Object Oriented Programming

• Object Oriented Programming

– The entire program is visualized as a number of objects interacting with each

other

• An object is a self-contained entity that contains attributes (data) and

behaviors (functions)

– Car, Telephone, Pen

• For using an object one needs to just invoke a method (function) on the

object

– No need to know the internal details (data) of the object

Page 16: Java Programming Slides01 Fp2007 Ver1.0

17

State and Behavior

• Example: Car object

– State

– Current Speed

– Current Gear

– Engine State (Running, Not Running)

– Behavior (Acts on the object and

changes state)

– Slow down

– Accelerate

– Stop

– Switch Off Engine

– Start Engine

• Example: Dog Object

– State

– Color

– Breed

– Activity (Barking/Not barking)

– Tail Activity (Wagging/Not

Wagging)

– Behavior

– Bark

– Wag Tail

– Eat

Page 17: Java Programming Slides01 Fp2007 Ver1.0

18

What is a Class? (1/3)

• A Class

– Is a blue print used to create objects.

– Is a software template that defines the methods and variables to be included

in a particular kind of Object.

• Examples

– Animal, Human Being, Automobiles, Bank Account, Customer

Page 18: Java Programming Slides01 Fp2007 Ver1.0

19

What is a Class? (2/3)

• A class contains state and behavior

• State (Member Variables)

– Variables defined inside the class

– Not exposed to external world

• Behavior (Member Methods)

– Functions defined inside the class

– Behavior exhibited by the class to external world

– Exposed to external world

• An object is an instance of a class

Page 19: Java Programming Slides01 Fp2007 Ver1.0

20

What is a Class? (3/3)

Class ‘Car’

45 km/h

CurrentSpeed

3

CurrentGear

5

Numberof Gears

7

SeatingCapacity

4

Numberof Doors

Accelerate

Brake

(Slo

w

Down)

Change Gear

(STATE)

(BEHAVIOR) Interface to externalworld (ThroughMethods/ Functionsonly)

State is internal tothe object. Notexposed to externalworld/other objects

Page 20: Java Programming Slides01 Fp2007 Ver1.0

21

Example: Objects and Classes

Daria

R002

Jane

R003

Brittany

R004

Jodie

R001

classobject

Class Student

name

rollNo

setName()

setRollNo()

getMarks()

Page 21: Java Programming Slides01 Fp2007 Ver1.0

22

Abstraction (1/2)

• The process of exposing the relevant details and hiding the irrelevant

details is called Abstraction

– Helps simplify the understanding and using of any complex system

– One does not have to understand how the engine works to drive a car

– Similarly one does not have to understand the internal implementation of a

software object to use it

Engine Driving

Page 22: Java Programming Slides01 Fp2007 Ver1.0

23

Abstraction (2/2)

• Consider a Stack

– The Stack can be implemented using an array or a linked list

– One need not know this to use the Stack object

– Just invoke the push method and pop method to make the Stack object work

Page 23: Java Programming Slides01 Fp2007 Ver1.0

24

Encapsulation

• Encapsulate = “En” + “Capsulate”; En = “In a”; Encapsulate = “In a

Capsule”

– Localization of information of knowledge within an object.

– Information hiding

– A car’s dashboard hides the complexity and internal workings of its engine.

Page 24: Java Programming Slides01 Fp2007 Ver1.0

25

Encapsulation (Data Hiding)

• Process of hiding the members from outside the class

• Implemented using the concept of access specifiers

– public, private etc.

• Typically in a class

– State is private (not accessible externally)

– Behavior is public (accessible externally)

• By enforcing this restriction, object oriented programming allows isolation

of complexity in a manageable way

Page 25: Java Programming Slides01 Fp2007 Ver1.0

26

Encapsulation (Data Hiding)

• In a class Stack, the data could be stored in an array which will be private

• The methods push and pop will be public

– A program cannot access the array directly from outside the class

– A program can access the array indirectly through the push and pop methods

Page 26: Java Programming Slides01 Fp2007 Ver1.0

27

Polymorphism

• Refers to an object’s ability to behave differently depending on its type– Poly = ‘many’

– morph = ‘form’

• Method Overloading is a way to achieve polymorphism• Practice of using same method name to denote several different

operations

Page 27: Java Programming Slides01 Fp2007 Ver1.0

28

Polymorphism

• For example, consider a class String which is designed to simplify string operations

• Append functions are overloaded to accept different types of data• One Append function appends an integer value to string, another Append

function appends a float value– void Append(int)

– void Append(float)

• The appropriate function will be invoked based on the type of the argument used in the function call

• Any number of functions can have the same name as long as they differ in any one of the following

– Type of arguments

– Number of arguments

Page 28: Java Programming Slides01 Fp2007 Ver1.0

29

UML and UML Class Diagrams

• Unified Modeling Language (UML) is a set of diagrams which pictorially represent object oriented design

• UML is extensively used by software engineers to communicate design• In OO Design

– Pictures are easier to understand than textual explanation

• UML Class diagram is a technique to represent classes and their relationships pictorially

Page 29: Java Programming Slides01 Fp2007 Ver1.0

30

Representing a class in UML Class Diagrams

+getName() : string+getAge() : int+getEmployeeNumber() : int+getBasicSalary() : float+getAllowances() : float+getTotalSalary() : float

-name : string-age : int-employeeNumber : int-basicSalary : float-allowances : float

Employee

UML Class Diagram Representation ofEmployee class

Class name

MemberVariables

MemberFunctions

• Some notations in UML

– ‘+’ before a member

indicates ‘public’

– ‘-’ before a member

indicates ‘private’

Page 30: Java Programming Slides01 Fp2007 Ver1.0

31

Relationships

• Different types of relationships can exist between classes• Identifying relationships helps design the objects better

– Analogous to relations between entities in RDBMS design

• There are 3 types of relationships• Has-A (or Part-Of)

– Car has an Engine

• Uses-A– Driver uses a Car

• Is-A (or Kind-Of)– Trainee is an Employee

Page 31: Java Programming Slides01 Fp2007 Ver1.0

32

Can you answer these questions?

• How is structured programming different from object oriented programming?

• What are classes and objects?• What is abstraction?• What is encapsulation?• What is polymorphism?• What is UML?• What are the relationships that can exist between classes?

Page 32: Java Programming Slides01 Fp2007 Ver1.0

33

Summary

• Classes and Objects• Abstraction• Encapsulation• Polymorphism• UML• Class relationships

Page 33: Java Programming Slides01 Fp2007 Ver1.0

Copyright © 2007, Infosys Technologies Ltd

Java Programming

Page 34: Java Programming Slides01 Fp2007 Ver1.0

35

Introduction to Java

• Java is a language developed by Sun Microsystems

• Java was developed initially for consumer devices

• Now it is a popular platform to develop web based enterprise applications

Page 35: Java Programming Slides01 Fp2007 Ver1.0

36

Salient Features of Java

• Object Oriented• Simpler language

– Compared to earlier OO languages like C++, it is simple

– Designed considering the pitfalls of earlier languages

• Architecture Neutral/Portable– Example: Java code compiled on Windows can be run on Unix without

recompilation

– Write Once, Run Anywhere

• Secure– Built -in security features like absence of pointers

Page 36: Java Programming Slides01 Fp2007 Ver1.0

37

Platform Independence

• Java is platform independent.

• A Java program that is written and compiled in one platform can run

on any other platform without any recompilation or modification

– Write Once Run Anywhere

Page 37: Java Programming Slides01 Fp2007 Ver1.0

38

Java Compiler

• The source code of Java will be stored in a text file with

extension .java

• The Java compiler compiles a .java file into byte code

– Byte code will be in a file with extension .class

– Languages like C compiles the program into the machine language format

of the hardware platform on which it is running

– Byte Code is NOT in the machine language format of the hardware

platform on which the code is compiled

– The hardware processor cannot understand the byte code

Page 38: Java Programming Slides01 Fp2007 Ver1.0

39

JVM (1/2)

• The byte code is in the machine language format of a machine known

as the Java Virtual Machine or the JVM

– Needs a JVM to execute the byte code

– JVM is not a real machine, it is just a virtual machine; implemented in

software

Page 39: Java Programming Slides01 Fp2007 Ver1.0

40

JVM (2/2)

• JVM is platform dependant; that is there is one JVM for Windows, another one for UNIX, yet another one for Mainframe etc

• All JVMs accept the same input, the byte code• Each JVM interprets the byte code into the machine language format of

the platform on which it is running• The same byte code can be run on any platform, if the JVM for that

platform is available– The JVMs for all platforms are available free (http://java.sun.com/) and hence

we say that the byte code runs in all platforms

Page 40: Java Programming Slides01 Fp2007 Ver1.0

41

Source File (HelloWorld.java)

Java Architecture

Compiler (javac)

Machine Code or Byte code (HelloWorld.class)

Operating System

Hardware

JVM

Page 41: Java Programming Slides01 Fp2007 Ver1.0

42

A Sample Java Application

• The following program can be created using any text editor

• Save the file as HelloWorld.java• Take care; case of file name matters

public class HelloWorld{

public static void main(String [] args){

System.out.println(“Hello World!”);

}

}

Page 42: Java Programming Slides01 Fp2007 Ver1.0

43

To Compile

• Open a command prompt• Go to the directory in which the source file is saved• Type the following command

• The Java compiler will convert the source code into the byte code– HelloWorld.class

javac HelloWorld.java

Page 43: Java Programming Slides01 Fp2007 Ver1.0

44

To execute

• Use the following command to execute the bytecode

java HelloWorld

Page 44: Java Programming Slides01 Fp2007 Ver1.0

45

Compilation & Execution

Java Program(.java)

Java Compiler(javac)

Byte Code(.class)

Interpreter(java) Interpreter(java) Interpreter(java)

Win32 Linux Mac

Page 45: Java Programming Slides01 Fp2007 Ver1.0

46

Primitive Data Types in Java

• Integer Types

– byte (1 byte)

– short (2 bytes)

– int (4 bytes)

– long (8 bytes)

• Floating Type

– float (4 bytes)

– double (8 bytes)

• All numeric data types are

signed

• The size of data types remain

the same on all platforms

Page 46: Java Programming Slides01 Fp2007 Ver1.0

47

Primitive Data Types in Java

• Textual

– char (2 bytes)

• Logical

– boolean (1 byte) (true/false)

• The char data type in Java is 2

bytes because it uses

UNICODE character set to

support internationalization

• UNICODE is a character set

which covers all known scripts

and language in the world

Page 47: Java Programming Slides01 Fp2007 Ver1.0

48

Comments in Java

• A single line comment in Java will start with //

• A multi line comment starts with a /* and ends with a */

// This is a single line comment in Java

/* This is a multi line

comment

in Java */

Page 48: Java Programming Slides01 Fp2007 Ver1.0

49

Variables in Java (1/2)

• Declaring and using primitive data types is Java similar to that of C

int count;

int max=100;

Page 49: Java Programming Slides01 Fp2007 Ver1.0

50

Variables in Java (2/2)

• Unlike C, in Java variables can be declared anywhere in the program

int i = 10;

System.out.println(“Program starts here”);

int j = 20;

for (int count=0; count < max; count++) {

int z = count * 10;

}

BEST PRACTICE: Declare a variable in program only when required. Do not declare variables upfront like in C.

Page 50: Java Programming Slides01 Fp2007 Ver1.0

51

Local Variables

• In Java, if a local variable is used without initializing it, the compiler will show an error

class Sample{

public static void main (String [] args){

int count;

System.out.println(count);//Error

}

}

Page 51: Java Programming Slides01 Fp2007 Ver1.0

52

Typecasting of primitive data types

• Variable of smaller capacity can be assigned to another variable of bigger capacity without any explicit typecasting

int i = 10;

double d;

d = i;

• Whenever a larger type is converted to a smaller type, the typecast operator has to be explicitly specified

double d = 10;

int i;

i = (int) d;

Type cast operator

Page 52: Java Programming Slides01 Fp2007 Ver1.0

53

Operators

• Operators in Java are very similar to operators in C– Assignment Operators

– Arithmetic Operators

– Relational Operators

– Logical Operators

Page 53: Java Programming Slides01 Fp2007 Ver1.0

54

Control Statements

• The syntax of the control statements in Java are very similar to that of C language

– if

– if-else

– for

– while

– do-while

– switch

– break

– continue

Page 54: Java Programming Slides01 Fp2007 Ver1.0

55

Methods in Java

• The syntax of writing methods in Java is similar to that of functions in C• Unlike C

– All methods in Java should be written inside a class

– There is no default return type for a Java method

Page 55: Java Programming Slides01 Fp2007 Ver1.0

56

Arrays in Java

• In Java, all arrays are created dynamically• The operator new is used for dynamic memory allocation• The following statement creates an array of 5 integers

new int[5]

• The above statement returns a reference to the newly created array– References in Java are very similar to pointers in C

Page 56: Java Programming Slides01 Fp2007 Ver1.0

57

Reference variables in Java (1/4)

• Reference variables are used in Java to store the references of the objects created by the operator new

• Any one of the following syntax can be used to create a reference to an int array

int x[];

int [] x;

• The reference x can be used for referring to any int array

//Declare a reference to an int array

int [] x;

//Create a new int array and make x refer to it

x = new int[5];

Page 57: Java Programming Slides01 Fp2007 Ver1.0

58

Reference variables in Java (2/4)

• The following statement also creates a new int array and assigns its reference to x

int [] x = new int[5];

• In simple terms, reference can be seen as the name of the array

Page 58: Java Programming Slides01 Fp2007 Ver1.0

59

Reference variables in Java (3/4)

• Even though we can think of Java references as C pointers, their usages are different

Pointers References

Printing a pointer will print the address stored in it

Printing a reference will NOT print the address of the object referred by it

Pointer arithmetic like incrementing a pointer is valid in the case of a pointer

We cannot use arithmetic operators on references

A pointer has to be de-referenced using the * operator to get the value pointed by it

A reference is automatically de-referenced to give the data referred by it and no special operator is required for this

Page 59: Java Programming Slides01 Fp2007 Ver1.0

60

Reference Types in Java (4/4)

• A reference type can be assigned ‘null’ to show that it is not referring to any object

– ‘null’ is a keyword in Java

int [] x = null;

Page 60: Java Programming Slides01 Fp2007 Ver1.0

61

Initializing an array in Java

• An array can be initialized while it is created as follows

int [] x = {1, 2, 3, 4};

char [] c = {‘a’, ‘b’, ‘c’};

Page 61: Java Programming Slides01 Fp2007 Ver1.0

62

The length of an array

• Unlike C, Java checks the boundary of an array while accessing an element in it

– Java will not allow the programmer to exceed its boundary

• If x is a reference to an array, x.length will give you the length of the array– The for loops can be set up as follows

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

x[i] = 5;

}

Page 62: Java Programming Slides01 Fp2007 Ver1.0

63

Multidimensional Arrays

• Multidimensional arrays are arrays of arrays. • To declare a multidimensional array variable, specify each additional

index using another set of square brackets.

int [][] x;

//x is a reference to an array of int arrays

x = new int[3][4];

/*Create 3 new int arrays, each having 4 elements

x[0] refers to the first int array, x[1] to the second etc

x[0][0] is the first element of the first array

x.length will be 3

x[0].length, x[1].length and x[2].length will be 4 */

Page 63: Java Programming Slides01 Fp2007 Ver1.0

64

Can you answer these questions?

• How is Java made platform neutral?• What is a reference variable in Java?

Page 64: Java Programming Slides01 Fp2007 Ver1.0

65

Summary:

• Review of Object Oriented Concepts• Java architecture • The basic constructs in Java • Arrays in Java

Page 65: Java Programming Slides01 Fp2007 Ver1.0

Copyright © 2007, Infosys Technologies Ltd

Thank You

“The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Infosys Technologies Ltd.”

“© 2006 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Infosys Technologies Ltd.”