Java Programming - Day 1
Long Cycle - JEE
ER/CORP/CRS/LA10LC/001 Ver. No.: 2:0
Copyright 2007, Infosys Technologies Ltd
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
Course Agenda (1/3)
Day1
Object Oriented Concepts The Java Architecture The basic constructs in Java Arrays OO SDLC Classes and Objects Constructors Method Overloading Static Members Command Line Arguments Class Relationships
Day 2
Course Agenda (2/3)
Day 3
Method Overriding Abstract classes Dynamic Binding and Runtime Polymorphism The final keyword Interfaces Packages The Java Library Exception Handling Generics The Collection Framework
Day 4
Course Agenda (3/3)
Day 5
Annotation JUnit QA4J
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
Session Plan Day 1
Object Oriented Concepts The Java Architecture The basic constructs in Java Arrays
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
Course Pre-Requisites
The participants should have knowledge of C as a programming language
Expectations
At the end of this course, the participants are expected to be proficient in the following
Object Oriented Programming using Java
10
Object Oriented Programming A Quick Revision
Copyright 2007, Infosys Technologies Ltd
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
12
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)
14
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
15
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
16
State and Behavior
Example: Car object
State
Current Speed
Current Gear Engine State (Running, Not Running)
Example: Dog Object
State
Color
Breed Activity (Barking/Not barking) Tail Activity (Wagging/Not Wagging)
Behavior (Acts on the object and changes state)
Slow down Accelerate Stop Switch Off Engine Start Engine
Behavior
Bark
Wag Tail
Eat
17
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
18
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
19
What is a Class? (3/3)
(BEHAVIOR)
A e cc r le e at
Number of Gears 5 Seating Capacity 7 Number of Doors 4 Current Speed 45 km/h Current Gear 3
Interface to external world (Through Methods/ Functions only)
(STATE)
ak Do e (S w lo n) w
State is internal to the object. Not exposed to external world/other objects
Class Car
20
Br
ge an Ch ea G r
Example: Objects and Classes
object
class
Class Student name rollNo
setName()
setRollNo()
Jodie R001
Daria R002
Jane R003
Brittany R004
getMarks()
21
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
22
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
23
Encapsulation
Encapsulate = En + Capsulate; En = In a; Encapsulate = In a Capsule
Localization of information of knowledge within an object.
Information hiding A cars dashboard hides the complexity and internal workings of its engine.
24
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
25
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
26
Polymorphism
Refers to an objects 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
27
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
28
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
29
Representing a class in UML Class Diagrams
Employee -name : string -age : int -employeeNumber : int -basicSalary : float -allowances : float +getName() : string +getAge() : int +getEmployeeNumber() : int +getBasicSalary() : float +getAllowances() : float +getTotalSalary() : float UML Class Diagram Representation of Employee class
Class name Member Variables
Some notations in UML + before a member indicates public - before a member indicates private
Member Functions
30
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
31
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?
32
Summary
Classes and Objects Abstraction Encapsulation Polymorphism UML Class relationships
33
Java Programming
Copyright 2007, Infosys Technologies Ltd
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
35
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
36
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
37
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
38
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
39
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
40
Java Architecture
Source File (HelloWorld.java)
JVM
Compiler (javac)
Machine Code or Byte code (HelloWorld.class)
Operating System Hardware
41
A Sample Java Application
The following program can be created using any text editor
public class HelloWorld{ public static void main(String [] args){ System.out.println(Hello World!); } }
Save the file as HelloWorld.java Take care; case of file name matters
42
To Compile
Open a command prompt Go to the directory in which the source file is saved Type the following command
javac HelloWorld.java
The Java compiler will convert the source code into the byte code
HelloWorld.class
43
To execute
Use the following command to execute the bytecode
java HelloWorld
44
Compilation & Execution
Java Program(.java)
Java Compiler(javac)
Byte Code(.class)
Interpreter(java)
Interpreter(java)
Interpreter(java)
Win32
Linux
Mac
45
Primitive Data Types in Java
Integer Types
byte (1 byte)
All numeric data types are signed The size of data types remain the same on all platforms
short (2 bytes)
int (4 bytes) long (8 bytes)
Floating Type
float (4 bytes) double (8 bytes)
46
Primitive Data Types in Java
Textual
char (2 bytes)
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
Logical
boolean (1 byte) (true/false)
47
Comments in Java
A single line comment in Java will start with //
// This is a single line comment in Java
A multi line comment starts with a /* and ends with a */
/* This is a multi line comment
in Java */
48
Variables in Java (1/2)
Declaring and using primitive data types is Java similar to that of C
int count; int max=100;
49
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.
50
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 } }
51
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
52
Operators
Operators in Java are very similar to operators in C
Assignment Operators Arithmetic Operators Relational Operators Logical Operators
53
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
54
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
55
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
56
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];
57
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
58
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 Printing a reference will NOT address stored in it print the address of the object referred by it Pointer arithmetic like incrementing a pointer is valid in the case of a pointer A pointer has to be dereferenced using the * operator to get the value pointed by it We cannot use arithmetic operators on references A reference is automatically de-referenced to give the data referred by it and no special operator is required for this
59
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;
60
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};
61
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;
62
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 */
63
Can you answer these questions?
How is Java made platform neutral? What is a reference variable in Java?
64
Summary:
Review of Object Oriented Concepts Java architecture The basic constructs in Java Arrays in Java
65
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.
Copyright 2007, Infosys Technologies Ltd