Copyright © 2007, Infosys Technologies Ltd Java Programming - Day 1 Long Cycle - JEE ER/CORP/CRS/LA10LC/001 Ver. No.: 2:0
Oct 26, 2014
Copyright © 2007, Infosys Technologies Ltd
Java Programming - Day 1
Long Cycle - JEE
ER/CORP/CRS/LA10LC/001 Ver. No.: 2: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
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
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
5
Course Agenda (3/3)
• Day 5– Annotation
– JUnit
– QA4J
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
7
Session Plan – Day 1
• Object Oriented Concepts• The Java Architecture • The basic constructs in Java • Arrays
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
9
Course Pre-Requisites
• The participants should have knowledge of C as a programming language
10
Expectations
• At the end of this course, the participants are expected to be proficient in the following
– Object Oriented Programming using Java
Copyright © 2007, Infosys Technologies Ltd
Object Oriented Programming – A Quick Revision
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
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)
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
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
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
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
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
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
21
Example: Objects and Classes
Daria
R002
Jane
R003
Brittany
R004
Jodie
R001
classobject
Class Student
name
rollNo
setName()
setRollNo()
getMarks()
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
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
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.
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
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
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
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
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
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’
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
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?
33
Summary
• Classes and Objects• Abstraction• Encapsulation• Polymorphism• UML• Class relationships
Copyright © 2007, Infosys Technologies Ltd
Java Programming
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
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
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
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
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
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
41
Source File (HelloWorld.java)
Java Architecture
Compiler (javac)
Machine Code or Byte code (HelloWorld.class)
Operating System
Hardware
JVM
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!”);
}
}
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
44
To execute
• Use the following command to execute the bytecode
java HelloWorld
45
Compilation & Execution
Java Program(.java)
Java Compiler(javac)
Byte Code(.class)
Interpreter(java) Interpreter(java) Interpreter(java)
Win32 Linux Mac
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
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
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 */
49
Variables in Java (1/2)
• Declaring and using primitive data types is Java similar to that of C
int count;
int max=100;
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.
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
}
}
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
53
Operators
• Operators in Java are very similar to operators in C– Assignment Operators
– Arithmetic Operators
– Relational Operators
– Logical Operators
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
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
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
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];
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
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
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;
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’};
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;
}
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 */
64
Can you answer these questions?
• How is Java made platform neutral?• What is a reference variable in Java?
65
Summary:
• Review of Object Oriented Concepts• Java architecture • The basic constructs in Java • Arrays in Java
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.”