SlideShare a Scribd company logo
Introduction to Java and XML
Day 1
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
2
Course Objective
To introduce Java Architecture & appreciate basic syntax in Java Language
To apply Object Oriented Concepts using Java
To illustrate how to make use of standard Java Class Library and create
reusable classes.
To introduce Exception Handling in Java
To learn what is required to package and deploy a Java application
To understand XML and XML parsing
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
3
Session Plan
Day 1
– Review of Object Oriented Concepts
– Java architecture
– The basic constructs in Java
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
4
Class and Object
What is a Class?
– A class is a blueprint or prototype that defines the variables and the
methods (functions) common to all objects of a certain kind.
What is an Object?
– An object is a representative or specimen of a class. Software objects are
often used to model real-world objects you find in everyday life.
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
5
Features of OOP
Abstraction:
– The process of extracting the essential information and hiding the irrelevant details
Encapsulation:
– The process of binding code and data together in the form of a capsule
Inheritance:
– The feature by which one class acquires the properties and functionalities of another
class
Polymorphism:
– The feature that allows the same interface to be used for a general set of actions
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
6
Introduction to Java
A language developed by Sun Microsystems
A general-purpose language
High-level language
Developed initially for consumer devices
Popular platform to develop enterprise applications
– Finds use in internet based applications
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
7
Features of Java
Object-oriented
Simpler language
– Compared to earlier OO languages like C++, it is simple
– Designed considering the pitfalls of earlier languages
Robust
Architecture Neutral / Portable
– Example: Java code compiled on Windows can be run on Unix without recompilation
Secure
– Built -in security features like absence of pointers and confinement of the java program within its
runtime environment
Support for Multithreading at language level
Designed to handle Distributed applications
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
8
Features of Java- (Contd…)
Please find more explanation of the previous slide in the notes page
(This slide is intentionally left blank)
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
9
Platform independence
Java is a language that is platform independent.
A platform is the hardware and software environment in which a program
runs
Once compiled, code will run on any platform without recompiling or any
kind of modification.
– “Write Once Run Anywhere”
This is made possible by making use of a Java Virtual Machine commonly
known as JVM
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
10
Java Virtual Machine (JVM) (1 of 2)
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
The byte code will be in a file with extension .class
The .class file that is generated is the machine code of this processor.
– Byte code is a binary language
The byte code is interpreted by the JVM
JVM can be considered as a processor purely implemented with software.
The interface that the JVM has to the .class file remains the same irrespective of the
underlying platform.
– This makes platform independence possible
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
11
Java Virtual Machine (JVM) (2 of 2)
The JVM interprets the .class file to the machine language of the underlying
platform.
The underlying platform processes the commands given by the JVM
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
12
Source File (HelloWorld.java)
Java Architecture:
Compiler (javac)
Machine Code or Byte code
(HelloWorld.class)
JVM
Class Loader
Byte Code Verifier
Interpreter
JIT Code
Generator
Runtime
Operating System
Hardware
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
13
Java Architecture- (Contd…)
Please find more explanation of the previous slide in the notes page
(This slide is intentionally left blank)
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
14
Installing and using Java
Before we begin, something on installation
– Java 2 SDK (v1.4 or higher)
– Can be downloaded freely from http://java.sun.com
– Also available in the intranet
Setting Environment variables for Java
Environment Variable:
– A variable that describes the operating environment of the process
– Common environment variables describe the home directory, command search path
etc.
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
15
Environment variables used by JVM
JAVA_HOME: Java Installation directory
– This environment variable is used to derive all other env. variables used by JVM
– In Windows: set JAVA_HOME=C:jdk1.4.3
– In UNIX: export JAVA_HOME=/var/usr/java
CLASSPATH
– In Windows: set PATH=%PATH%;%JAVA_HOME%libtools.jar;.
– In UNIX: set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.
PATH
– Path variable is used by OS to locate executable files
– In Windows: set PATH=%PATH%;%JAVA_HOME%bin
– In UNIX: set PATH=$PATH:$JAVA_HOME/bin
This approach helps in managing multiple versions of Java – Changing JAVA_HOME will
reflect on CLASSPATH and PATH as well
Set these environment variables on the command prompt and type ‘javac’
– Displays all the options of using ‘javac’
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
16
Source File Layout - Hello World
We will have the source code first
Type this into any text editor
public class HelloWorldApp {
public static void main(String[]args){
System.out.println(“Hello World!”);
}
}
Save this as HelloWorldApp.java
Important :
– Take care!! cAsE of file name matters
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
17
To Compile
Open a command prompt
Set Environment variables (explained earlier)
Go to the directory in which you have saved your program.
Type javac HelloWorldApp.java
– If it says bad command or file name then check the path setting
– If it does not say anything, and you get the prompt, then the compilation was
successful.
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
18
To execute
Type in the command prompt
java HelloWorldApp
The result
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
19
Best Practices
One .java file must contain only one class declaration
The name of the file must always be same as the name of the class
Stand alone Java program must have a public static void main defined
– it is the starting point of the program.
– Not all classes require public static void main
Code should be adequately commented
Must follow indentation and coding standards
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
20
Primitive Data Types in Java
Integer data types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
Floating Type
float (4 bytes)
double (8 bytes)
Textual
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Notes:
All numeric data types are signed
The size of data types remain the
same on all platforms (standardized)
char data type in Java is 2 bytes
because it uses UNICODE character
set. By virtue of it, Java supports
internationalization
UNICODE is a character set which
covers all known scripts and
language in the world
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
21
Reference Types in Java (1 of 3)
Objects, Arrays are accessed using reference variables in Java
A reference variable is similar to a pointer (stores memory address of an
object)
Java does not support the explicit use of addresses like other languages
Java does not allow pointer manipulation or pointer arithmetic
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
22
Reference Types in Java (2 of 3)
A reference type cannot be cast to primitive type
A reference type can be assigned ‘null’ to show that it is not referring to any
object
– ‘null’ is a keyword in Java
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
23
Comment entry 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 */
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
24
Variables in Java
Using primitive data types is similar to other languages
int count;
int max=100;
In Java variables can be declared anywhere in the program
for (int count=0; count < max; count++) {
int z = count * 10;
}
In Java, if a local variable is used without initializing it, the compiler will show an error
BEST PRACTICE: Declare a variable in program only when
required. Do not declare variables upfront like in C.
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
25
Typecasting of primitive data types –(Contd…)
Please find more explanation of the previous slide in the notes page
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
26
Operators and Assignments –(Contd…)
Please find more explanation of the previous slide in the notes page
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
27
Operators and Assignments –(Contd…)
Please find more explanation of the previous slide in the notes page
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
28
Constituents of a Class
The main method may or may not be present depending on whether the class is a starter class
public class Student {public class Student {public class Student {public class Student {
private intprivate intprivate intprivate int rollNorollNorollNorollNo;;;;
private String name;private String name;private String name;private String name;
Student(){Student(){Student(){Student(){
//initialize data members//initialize data members//initialize data members//initialize data members
}}}}
Student(StringStudent(StringStudent(StringStudent(String nameParamnameParamnameParamnameParam){){){){
name =name =name =name = nameParamnameParamnameParamnameParam;;;;
}}}}
public intpublic intpublic intpublic int getrollNogetrollNogetrollNogetrollNo (){(){(){(){
returnreturnreturnreturn rollNorollNorollNorollNo;;;;
}}}}
}}}}
Data Members
(State)
Constructor
Method (Behavior)
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
29
Access Modifiers – private and public
Data members are always kept private
– It is accessible only within the class
The methods which expose the behavior of the object are kept public
– However, we can have helper methods which are private
Key features of object oriented programs
– encapsulation (binding of code and data together)
– State (data) is hidden and Behavior (methods) is exposed to external world
Access modifiers (public, private etc) will be covered in more details in the later
slides
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
30
Creating Objects in Java
The new operator creates the object and returns a reference to it
Memory allocation of objects happens in the heap area
Reference returned can be stored in reference variables
E.g. :
Student obj1;
obj1 = new Student();
Or
Student obj2 = new Student(“Jack”);
obj1 is reference
variable
new keyword creates
an object and returns
a reference to it
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
31
Constructors (1 of 2)
A constructor is a special method that is used to initialize a newly created
object
Called just after the memory is allocated for the object
Can be used to initialize the objects to required or default values at the time of
object creation
It is not mandatory for the coder to write a constructor for the class
When writing a constructor, remember that:
– it has the same name as the class
– it does not return a value not even void
– It may or may not have parameters (arguments)
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
32
Constructors (2 of 2)
If no user defined constructor is provided for a class, compiler initializes
member variables to its default values. Examples:
– numeric data types are set to 0
– char data types are set to null character(‘0’)
– reference variables are set to null
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
33
Lifetime of objects (1 of 2)
Student obj1 = new student();
Student obj2 = new student();
The two Student objects are now living on the heap
-- References: 2
-- Objects: 2
Student obj3 = obj2;
-- References: 3
-- Objects: 2
2
1
heap
obj1
obj2
2
1
heap
obj1
obj2
obj3
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
34
Lifetime of objects (2 of 2)
obj3 = obj1;
-- References: 3
-- Objects: 2
obj2 = null;
-- Active References: 2
-- null references: 1
-- Reachable Objects: 1
-- Abandoned objects: 1 2
1
heap
obj1
obj2
ob3
2
1
obj1
obj2
ob3
heap
Null reference
This object can be
garbage collected
(Can be Removed
from memory)
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
35
Garbage Collection
In C language, it is the programmer’s responsibility to de-allocate memory
allocated dynamically
– free() function is used to de-allocate
In Java, JVM will automatically do the memory de-allocation
– Called “Garbage collection”
– However programmer has to ensure that reference to the object is released
• If a reference variable is declared within a function, the reference is invalidated soon as the
function call ends
• Other way of explicitly releasing the reference is to set the reference variable to null
• Setting a reference variable to null means that it is not referring to any object
An object which is not referred by any reference variable is removed from
memory by the garbage collector
Primitive types are not objects. They cannot be assigned null
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
36
Variables and their scope (1 of 3)
Instance variables (Also known as member variables)
– Declared inside a class
– Outside any method or constructor
– Belong to the object
– Stored in the heap area along with the object to which they belong
– Lifetime depends on the lifetime of the object
Local variables (Also known as stack variables)
– Declared inside a method
– Method parameters are also local variables
– Stored in the program stack along with method calls and live until the call ends
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
37
Strings in Java
Unlike C, String is a system defined class in Java
Declaring “Hello World” in code will create and object of type string with data “Hello
World” and returns a reference to it.
String is defined in the Java API under the package ‘java.lang’
– Packages are covered in detail later.
– The fully qualified name of String class in Java is ‘java.lang.String’
Unlike C, the string is of fixed length and memory for the string is managed totally by the
String class
– Prevents buffer overruns
– NULL terminator not used in strings
Unlike C, string is not a simple array of characters
– internally it is stored as an array, but not exposed to programmer
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
38
Control Structures in Java
Similar to the “C” Programming Language
Conditionals
– if-else, else if statements
– switch case statements
Loops
– for
– while
– do-while
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
39
Coding standards and Best practices for naming
classes and variables
Class name should begin with uppercase and camel casing
– Eg. Student, ArrayList
Name should tell what the variable, method or class does
No short form of words
Variable name should start with lower case and to follow camel casing
– Eg. int numberOfStudents;
Method names should begin with lowercase and follow camel casing
– Eg. void displayUserChoice()
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
40
Commenting code in Java (1 of 3)
File header
– Description of the file
/* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the
* Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class
* by passing the necessary values as parameters* by passing the necessary values as parameters* by passing the necessary values as parameters* by passing the necessary values as parameters
*/*/*/*/
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
41
Commenting code in Java (2 of 3)
Class header
– description of the class
– Date
– @ author
– @ version
– Note: Do not type class name in header
/**
* This class contains a method to print sum of two numbers.
* Date: 12-Jan-2005
* @author E&R Dept, Infosys Technologies Limited
* @version 1.0
*/
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
42
Commenting code in Java (3 of 3)
Method header
– description of the method
– @param
– @return
– Note: Do not type method name in header
/**
* Computes the sum of the two integer variables passed
* as parameters
* @param number1 The First number
* @param number2 The Second number
* @return the sum of the two numbers passed as arguments
*/
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
43
Arrays in Java (1 of 7)
An array is a data structure which defines an ordered collection of a fixed
number of homogeneous data elements
The size of an array is fixed and cannot increase to accommodate more
elements
Arrays in Java are objects and can be of primitive data types or reference
variable type
All elements in the array must be of the same data type
20 10045 7050
An array holding 5 int elements
An array holding 4 rabbit objects
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
44
Arrays in Java (2 of 7)
Declaring Array Variables
<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];
where <elementType> can be any primitive data type or reference type
Example:
int intArray[];
Pizza[] mediumPizza, largePizza;
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
45
Arrays in Java (3 of 7)
Constructing an Array
<arrayName> = new <elementType>[<noOfElements>];
Example:
int intArray[];
Pizza mediumPizza[], largePizza[];
intArray = new int[10];
mediumPizza = new Pizza[5];
largePizza = new Pizza[2];
Declaration and Construction combined
int intArray[] = new int[10];
Pizza mediumPizza[] = new Pizza[5];
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
46
Arrays in Java (4 of 7)
Declaring and Initializing an Array
<elementType>[] <arayName> = {<arrayInitializerCode>};
Example:
int intArray[] = {1, 2, 3, 4};
char charArray[] = {‘a’, ‘b’, ‘c’};
Pizza pizzaArray[] = {new Pizza(), new Pizza()};
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
47
Arrays in Java (5 of 7)
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
So setting up a for loop as follows is very common in Java
for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){
x[i] = 5;x[i] = 5;x[i] = 5;x[i] = 5;
}}}}
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
48
this keyword(1 of 2)
class Counter{
private int data;
Counter(int var1){
data=var1;
}
public void increment(){
++data;
}
public int getData(){
return data;
}
}
class CounterTest{
public static void main(String args[]){
Counter a = new Counter(10);
a.increment();
System.out.println(a.getData());
System.out.println(a.getData());
Counter b = new Counter(25);
b.increment();
System.out.println(b.getData());
}
}
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
49
this reference (2 of 2)
In the Counter example, when we call a.increment(), the increment() method
will say ++data
Whose data is it?
The methods of a class will automatically have a reference called this
The ‘this’ reference will always refer to the object that called the method
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
50
static (1 of 4)
static keyword can be used in 3 scenarios:
– For class variables
– For methods
– For a block of code
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
51
static (2 of 4)
static variable
– It is a variable which belongs to the class
– A single copy to be shared by all instances of the class
– For using static variables, creation of instance is not necessary
– Accessed using <class-name>.<variable-name> unlike instance variables which are accessed
as <object-name>.<variable-name>
static method
– It is a class method
– Accessed using class name.method name
– For using static methods, creation of instance is not necessary
– A static method can only access other static data and methods. It cannot access non-static
members
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
52
static (3 of 4)
Class Duck {Class Duck {Class Duck {Class Duck {
private int size;private int size;private int size;private int size;
private static intprivate static intprivate static intprivate static int duckCountduckCountduckCountduckCount;;;;
public Duck(){public Duck(){public Duck(){public Duck(){
duckCountduckCountduckCountduckCount++;++;++;++;
}}}}
public voidpublic voidpublic voidpublic void setSizesetSizesetSizesetSize (int s){(int s){(int s){(int s){
size = s;size = s;size = s;size = s;
}}}}
public intpublic intpublic intpublic int getSizegetSizegetSizegetSize (int s){(int s){(int s){(int s){
return size;return size;return size;return size;
}}}}
public static voidpublic static voidpublic static voidpublic static void main(Stringmain(Stringmain(Stringmain(String argsargsargsargs[]){[]){[]){[]){
System.out..println(System.out..println(System.out..println(System.out..println(““““SizeSizeSizeSize of the duck is;of the duck is;of the duck is;of the duck is;”””” + size);+ size);+ size);+ size);
}}}}
}}}}
The static duckCount variable is
initialised to 0, ONLY when the
class is first loaded, NOT each time
a new instance is made
Each time the constructor is invoked ie
an object gets created, the static
variable duckCount will be incremented
thus keeping a count of the total no of
Duck objects creataed
Which duck? Whose size? A static
method cannot access anything
non-static
Compilation
error
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
53
static (4 of 4)
static block
– The static block is a block of statement inside a Java class that will be executed
when a class is first loaded and initialized
• A class is loaded typically after the JVM starts
• In some cases a class is loaded when the program requires it
– A static block helps to initialize the static data members just like constructors help to
initialize instance members
class Test{class Test{class Test{class Test{
static {static {static {static {
//Code goes here//Code goes here//Code goes here//Code goes here
}}}}
}}}}
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
54
Referring to Java documentation
Java provides a rich set of library classes
Demo on how to refer to library classes
ER/CORP/CRS/LA10/003
Version 2.00
Copyright © 2005, Infosys
Technologies Ltd
55
Summary:
– Review of Object Oriented Concepts
– Java architecture
– The basic constructs in Java

More Related Content

Introduction tojavaandxml lc-slides01-fp2005-ver 1.0

  • 1. Introduction to Java and XML Day 1
  • 2. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 2 Course Objective To introduce Java Architecture & appreciate basic syntax in Java Language To apply Object Oriented Concepts using Java To illustrate how to make use of standard Java Class Library and create reusable classes. To introduce Exception Handling in Java To learn what is required to package and deploy a Java application To understand XML and XML parsing
  • 3. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 3 Session Plan Day 1 – Review of Object Oriented Concepts – Java architecture – The basic constructs in Java
  • 4. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 4 Class and Object What is a Class? – A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of a certain kind. What is an Object? – An object is a representative or specimen of a class. Software objects are often used to model real-world objects you find in everyday life.
  • 5. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 5 Features of OOP Abstraction: – The process of extracting the essential information and hiding the irrelevant details Encapsulation: – The process of binding code and data together in the form of a capsule Inheritance: – The feature by which one class acquires the properties and functionalities of another class Polymorphism: – The feature that allows the same interface to be used for a general set of actions
  • 6. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 6 Introduction to Java A language developed by Sun Microsystems A general-purpose language High-level language Developed initially for consumer devices Popular platform to develop enterprise applications – Finds use in internet based applications
  • 7. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 7 Features of Java Object-oriented Simpler language – Compared to earlier OO languages like C++, it is simple – Designed considering the pitfalls of earlier languages Robust Architecture Neutral / Portable – Example: Java code compiled on Windows can be run on Unix without recompilation Secure – Built -in security features like absence of pointers and confinement of the java program within its runtime environment Support for Multithreading at language level Designed to handle Distributed applications
  • 8. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 8 Features of Java- (Contd…) Please find more explanation of the previous slide in the notes page (This slide is intentionally left blank)
  • 9. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 9 Platform independence Java is a language that is platform independent. A platform is the hardware and software environment in which a program runs Once compiled, code will run on any platform without recompiling or any kind of modification. – “Write Once Run Anywhere” This is made possible by making use of a Java Virtual Machine commonly known as JVM
  • 10. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 10 Java Virtual Machine (JVM) (1 of 2) 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 The byte code will be in a file with extension .class The .class file that is generated is the machine code of this processor. – Byte code is a binary language The byte code is interpreted by the JVM JVM can be considered as a processor purely implemented with software. The interface that the JVM has to the .class file remains the same irrespective of the underlying platform. – This makes platform independence possible
  • 11. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 11 Java Virtual Machine (JVM) (2 of 2) The JVM interprets the .class file to the machine language of the underlying platform. The underlying platform processes the commands given by the JVM
  • 12. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 12 Source File (HelloWorld.java) Java Architecture: Compiler (javac) Machine Code or Byte code (HelloWorld.class) JVM Class Loader Byte Code Verifier Interpreter JIT Code Generator Runtime Operating System Hardware
  • 13. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 13 Java Architecture- (Contd…) Please find more explanation of the previous slide in the notes page (This slide is intentionally left blank)
  • 14. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 14 Installing and using Java Before we begin, something on installation – Java 2 SDK (v1.4 or higher) – Can be downloaded freely from http://java.sun.com – Also available in the intranet Setting Environment variables for Java Environment Variable: – A variable that describes the operating environment of the process – Common environment variables describe the home directory, command search path etc.
  • 15. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 15 Environment variables used by JVM JAVA_HOME: Java Installation directory – This environment variable is used to derive all other env. variables used by JVM – In Windows: set JAVA_HOME=C:jdk1.4.3 – In UNIX: export JAVA_HOME=/var/usr/java CLASSPATH – In Windows: set PATH=%PATH%;%JAVA_HOME%libtools.jar;. – In UNIX: set PATH=$PATH:$JAVA_HOME/lib/tools.jar:. PATH – Path variable is used by OS to locate executable files – In Windows: set PATH=%PATH%;%JAVA_HOME%bin – In UNIX: set PATH=$PATH:$JAVA_HOME/bin This approach helps in managing multiple versions of Java – Changing JAVA_HOME will reflect on CLASSPATH and PATH as well Set these environment variables on the command prompt and type ‘javac’ – Displays all the options of using ‘javac’
  • 16. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 16 Source File Layout - Hello World We will have the source code first Type this into any text editor public class HelloWorldApp { public static void main(String[]args){ System.out.println(“Hello World!”); } } Save this as HelloWorldApp.java Important : – Take care!! cAsE of file name matters
  • 17. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 17 To Compile Open a command prompt Set Environment variables (explained earlier) Go to the directory in which you have saved your program. Type javac HelloWorldApp.java – If it says bad command or file name then check the path setting – If it does not say anything, and you get the prompt, then the compilation was successful.
  • 18. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 18 To execute Type in the command prompt java HelloWorldApp The result
  • 19. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 19 Best Practices One .java file must contain only one class declaration The name of the file must always be same as the name of the class Stand alone Java program must have a public static void main defined – it is the starting point of the program. – Not all classes require public static void main Code should be adequately commented Must follow indentation and coding standards
  • 20. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 20 Primitive Data Types in Java Integer data types byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes) Floating Type float (4 bytes) double (8 bytes) Textual char (2 bytes) Logical boolean (1 byte) (true/false) Notes: All numeric data types are signed The size of data types remain the same on all platforms (standardized) char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports internationalization UNICODE is a character set which covers all known scripts and language in the world
  • 21. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 21 Reference Types in Java (1 of 3) Objects, Arrays are accessed using reference variables in Java A reference variable is similar to a pointer (stores memory address of an object) Java does not support the explicit use of addresses like other languages Java does not allow pointer manipulation or pointer arithmetic
  • 22. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 22 Reference Types in Java (2 of 3) A reference type cannot be cast to primitive type A reference type can be assigned ‘null’ to show that it is not referring to any object – ‘null’ is a keyword in Java
  • 23. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 23 Comment entry 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 */
  • 24. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 24 Variables in Java Using primitive data types is similar to other languages int count; int max=100; In Java variables can be declared anywhere in the program for (int count=0; count < max; count++) { int z = count * 10; } In Java, if a local variable is used without initializing it, the compiler will show an error BEST PRACTICE: Declare a variable in program only when required. Do not declare variables upfront like in C.
  • 25. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 25 Typecasting of primitive data types –(Contd…) Please find more explanation of the previous slide in the notes page
  • 26. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 26 Operators and Assignments –(Contd…) Please find more explanation of the previous slide in the notes page
  • 27. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 27 Operators and Assignments –(Contd…) Please find more explanation of the previous slide in the notes page
  • 28. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 28 Constituents of a Class The main method may or may not be present depending on whether the class is a starter class public class Student {public class Student {public class Student {public class Student { private intprivate intprivate intprivate int rollNorollNorollNorollNo;;;; private String name;private String name;private String name;private String name; Student(){Student(){Student(){Student(){ //initialize data members//initialize data members//initialize data members//initialize data members }}}} Student(StringStudent(StringStudent(StringStudent(String nameParamnameParamnameParamnameParam){){){){ name =name =name =name = nameParamnameParamnameParamnameParam;;;; }}}} public intpublic intpublic intpublic int getrollNogetrollNogetrollNogetrollNo (){(){(){(){ returnreturnreturnreturn rollNorollNorollNorollNo;;;; }}}} }}}} Data Members (State) Constructor Method (Behavior)
  • 29. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 29 Access Modifiers – private and public Data members are always kept private – It is accessible only within the class The methods which expose the behavior of the object are kept public – However, we can have helper methods which are private Key features of object oriented programs – encapsulation (binding of code and data together) – State (data) is hidden and Behavior (methods) is exposed to external world Access modifiers (public, private etc) will be covered in more details in the later slides
  • 30. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 30 Creating Objects in Java The new operator creates the object and returns a reference to it Memory allocation of objects happens in the heap area Reference returned can be stored in reference variables E.g. : Student obj1; obj1 = new Student(); Or Student obj2 = new Student(“Jack”); obj1 is reference variable new keyword creates an object and returns a reference to it
  • 31. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 31 Constructors (1 of 2) A constructor is a special method that is used to initialize a newly created object Called just after the memory is allocated for the object Can be used to initialize the objects to required or default values at the time of object creation It is not mandatory for the coder to write a constructor for the class When writing a constructor, remember that: – it has the same name as the class – it does not return a value not even void – It may or may not have parameters (arguments)
  • 32. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 32 Constructors (2 of 2) If no user defined constructor is provided for a class, compiler initializes member variables to its default values. Examples: – numeric data types are set to 0 – char data types are set to null character(‘0’) – reference variables are set to null
  • 33. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 33 Lifetime of objects (1 of 2) Student obj1 = new student(); Student obj2 = new student(); The two Student objects are now living on the heap -- References: 2 -- Objects: 2 Student obj3 = obj2; -- References: 3 -- Objects: 2 2 1 heap obj1 obj2 2 1 heap obj1 obj2 obj3
  • 34. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 34 Lifetime of objects (2 of 2) obj3 = obj1; -- References: 3 -- Objects: 2 obj2 = null; -- Active References: 2 -- null references: 1 -- Reachable Objects: 1 -- Abandoned objects: 1 2 1 heap obj1 obj2 ob3 2 1 obj1 obj2 ob3 heap Null reference This object can be garbage collected (Can be Removed from memory)
  • 35. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 35 Garbage Collection In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically – free() function is used to de-allocate In Java, JVM will automatically do the memory de-allocation – Called “Garbage collection” – However programmer has to ensure that reference to the object is released • If a reference variable is declared within a function, the reference is invalidated soon as the function call ends • Other way of explicitly releasing the reference is to set the reference variable to null • Setting a reference variable to null means that it is not referring to any object An object which is not referred by any reference variable is removed from memory by the garbage collector Primitive types are not objects. They cannot be assigned null
  • 36. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 36 Variables and their scope (1 of 3) Instance variables (Also known as member variables) – Declared inside a class – Outside any method or constructor – Belong to the object – Stored in the heap area along with the object to which they belong – Lifetime depends on the lifetime of the object Local variables (Also known as stack variables) – Declared inside a method – Method parameters are also local variables – Stored in the program stack along with method calls and live until the call ends
  • 37. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 37 Strings in Java Unlike C, String is a system defined class in Java Declaring “Hello World” in code will create and object of type string with data “Hello World” and returns a reference to it. String is defined in the Java API under the package ‘java.lang’ – Packages are covered in detail later. – The fully qualified name of String class in Java is ‘java.lang.String’ Unlike C, the string is of fixed length and memory for the string is managed totally by the String class – Prevents buffer overruns – NULL terminator not used in strings Unlike C, string is not a simple array of characters – internally it is stored as an array, but not exposed to programmer
  • 38. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 38 Control Structures in Java Similar to the “C” Programming Language Conditionals – if-else, else if statements – switch case statements Loops – for – while – do-while
  • 39. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 39 Coding standards and Best practices for naming classes and variables Class name should begin with uppercase and camel casing – Eg. Student, ArrayList Name should tell what the variable, method or class does No short form of words Variable name should start with lower case and to follow camel casing – Eg. int numberOfStudents; Method names should begin with lowercase and follow camel casing – Eg. void displayUserChoice()
  • 40. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 40 Commenting code in Java (1 of 3) File header – Description of the file /* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the/* This java file contains a class with a method to compute the * Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class* Sum of two numbers. This method is invoked from another class * by passing the necessary values as parameters* by passing the necessary values as parameters* by passing the necessary values as parameters* by passing the necessary values as parameters */*/*/*/
  • 41. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 41 Commenting code in Java (2 of 3) Class header – description of the class – Date – @ author – @ version – Note: Do not type class name in header /** * This class contains a method to print sum of two numbers. * Date: 12-Jan-2005 * @author E&R Dept, Infosys Technologies Limited * @version 1.0 */
  • 42. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 42 Commenting code in Java (3 of 3) Method header – description of the method – @param – @return – Note: Do not type method name in header /** * Computes the sum of the two integer variables passed * as parameters * @param number1 The First number * @param number2 The Second number * @return the sum of the two numbers passed as arguments */
  • 43. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 43 Arrays in Java (1 of 7) An array is a data structure which defines an ordered collection of a fixed number of homogeneous data elements The size of an array is fixed and cannot increase to accommodate more elements Arrays in Java are objects and can be of primitive data types or reference variable type All elements in the array must be of the same data type 20 10045 7050 An array holding 5 int elements An array holding 4 rabbit objects
  • 44. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 44 Arrays in Java (2 of 7) Declaring Array Variables <elementType>[] <arrayName>; or <elementType> <arrayName>[]; where <elementType> can be any primitive data type or reference type Example: int intArray[]; Pizza[] mediumPizza, largePizza;
  • 45. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 45 Arrays in Java (3 of 7) Constructing an Array <arrayName> = new <elementType>[<noOfElements>]; Example: int intArray[]; Pizza mediumPizza[], largePizza[]; intArray = new int[10]; mediumPizza = new Pizza[5]; largePizza = new Pizza[2]; Declaration and Construction combined int intArray[] = new int[10]; Pizza mediumPizza[] = new Pizza[5];
  • 46. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 46 Arrays in Java (4 of 7) Declaring and Initializing an Array <elementType>[] <arayName> = {<arrayInitializerCode>}; Example: int intArray[] = {1, 2, 3, 4}; char charArray[] = {‘a’, ‘b’, ‘c’}; Pizza pizzaArray[] = {new Pizza(), new Pizza()};
  • 47. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 47 Arrays in Java (5 of 7) 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 So setting up a for loop as follows is very common in Java for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){for(int i = 0; i < x.length; ++i){ x[i] = 5;x[i] = 5;x[i] = 5;x[i] = 5; }}}}
  • 48. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 48 this keyword(1 of 2) class Counter{ private int data; Counter(int var1){ data=var1; } public void increment(){ ++data; } public int getData(){ return data; } } class CounterTest{ public static void main(String args[]){ Counter a = new Counter(10); a.increment(); System.out.println(a.getData()); System.out.println(a.getData()); Counter b = new Counter(25); b.increment(); System.out.println(b.getData()); } }
  • 49. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 49 this reference (2 of 2) In the Counter example, when we call a.increment(), the increment() method will say ++data Whose data is it? The methods of a class will automatically have a reference called this The ‘this’ reference will always refer to the object that called the method
  • 50. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 50 static (1 of 4) static keyword can be used in 3 scenarios: – For class variables – For methods – For a block of code
  • 51. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 51 static (2 of 4) static variable – It is a variable which belongs to the class – A single copy to be shared by all instances of the class – For using static variables, creation of instance is not necessary – Accessed using <class-name>.<variable-name> unlike instance variables which are accessed as <object-name>.<variable-name> static method – It is a class method – Accessed using class name.method name – For using static methods, creation of instance is not necessary – A static method can only access other static data and methods. It cannot access non-static members
  • 52. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 52 static (3 of 4) Class Duck {Class Duck {Class Duck {Class Duck { private int size;private int size;private int size;private int size; private static intprivate static intprivate static intprivate static int duckCountduckCountduckCountduckCount;;;; public Duck(){public Duck(){public Duck(){public Duck(){ duckCountduckCountduckCountduckCount++;++;++;++; }}}} public voidpublic voidpublic voidpublic void setSizesetSizesetSizesetSize (int s){(int s){(int s){(int s){ size = s;size = s;size = s;size = s; }}}} public intpublic intpublic intpublic int getSizegetSizegetSizegetSize (int s){(int s){(int s){(int s){ return size;return size;return size;return size; }}}} public static voidpublic static voidpublic static voidpublic static void main(Stringmain(Stringmain(Stringmain(String argsargsargsargs[]){[]){[]){[]){ System.out..println(System.out..println(System.out..println(System.out..println(““““SizeSizeSizeSize of the duck is;of the duck is;of the duck is;of the duck is;”””” + size);+ size);+ size);+ size); }}}} }}}} The static duckCount variable is initialised to 0, ONLY when the class is first loaded, NOT each time a new instance is made Each time the constructor is invoked ie an object gets created, the static variable duckCount will be incremented thus keeping a count of the total no of Duck objects creataed Which duck? Whose size? A static method cannot access anything non-static Compilation error
  • 53. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 53 static (4 of 4) static block – The static block is a block of statement inside a Java class that will be executed when a class is first loaded and initialized • A class is loaded typically after the JVM starts • In some cases a class is loaded when the program requires it – A static block helps to initialize the static data members just like constructors help to initialize instance members class Test{class Test{class Test{class Test{ static {static {static {static { //Code goes here//Code goes here//Code goes here//Code goes here }}}} }}}}
  • 54. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 54 Referring to Java documentation Java provides a rich set of library classes Demo on how to refer to library classes
  • 55. ER/CORP/CRS/LA10/003 Version 2.00 Copyright © 2005, Infosys Technologies Ltd 55 Summary: – Review of Object Oriented Concepts – Java architecture – The basic constructs in Java