0% found this document useful (0 votes)
62 views

La10 - Java Programming - 01

The document provides an overview of a one day Java programming course. The session plan includes a review of object oriented concepts, an introduction to the Java architecture and basic constructs. Key topics that will be covered are classes and objects, features of object oriented programming like abstraction and encapsulation, and an introduction to the Java programming language itself including its platform independence through the Java Virtual Machine.

Uploaded by

loga prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

La10 - Java Programming - 01

The document provides an overview of a one day Java programming course. The session plan includes a review of object oriented concepts, an introduction to the Java architecture and basic constructs. Key topics that will be covered are classes and objects, features of object oriented programming like abstraction and encapsulation, and an introduction to the Java programming language itself including its platform independence through the Java Virtual Machine.

Uploaded by

loga prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Java Programming

(J2EE LC)
Day 1
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 introduce User Interface Concepts & Event Handling

Java Applets

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 2
Technologies Ltd Version 1.00
Session Plan

Day 1
– Review of Object Oriented Concepts

– Java architecture

– The basic constructs in Java

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 3
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 4
Technologies Ltd Version 1.00
Example : Objects and Classes

object class
class Student
char name
int rollNo
setName()
Jodie Daria Jane Brittany setRollNo()
R001 R002 R003 R004
calcMarks()

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 5
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 6
Technologies Ltd Version 1.00
Object Oriented Program State (Data) is kept
accessible only to a
set of functions.
Behavior of the
object is exposed
using methods.

Data Data

Function Function

An object communicates
with another object by
passing messages
(invoking methods)

Data Data

Function Function

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 7
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 8
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 9
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 10
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 11
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 12
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 13
Technologies Ltd Version 1.00
Java Architecture:
JVM

Source File (HelloWorld.java)


Class Loader

Byte Code Verifier

Compiler (javac) JIT Code


Interpreter
Generator

Runtime

Machine Code or Byte code


(HelloWorld.class) Operating System

Hardware

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 14
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 15
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 16
Technologies Ltd Version 1.00
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%\lib\tools.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
Copyright © 2005, Infosys 17
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 18
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 19
Technologies Ltd Version 1.00
To execute

Type in the command prompt

java HelloWorldApp

The result

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 20
Technologies Ltd Version 1.00
Compilation & Execution

Java Program (.java)

Java Complier (javac)

Byte Code (.class file)

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

Win 32 Linux Mac

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 21
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 22
Technologies Ltd Version 1.00
Java Keywords – (For Reference Only)
The reserved keywords defined in the Java language

abstract const finally implements public this

boolean continue for instanceof throw transient

break float if null short void

byte default import int super volatile

case do false return switch while

catch double interface package synchronized

char else long private static

class extends goto protected try

true final new native throws

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 23
Technologies Ltd Version 1.00
Data Types in Java

Java is a Strongly typed language


– What is typecasting?

– Unlike C, at runtime type checking is strictly enforced

– Impossible to typecast incompatible types

Two types of variables


– Primitive type

– Reference type

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 24
Technologies Ltd Version 1.00
Primitive Data Types in Java
Integer data types Notes:
byte (1 byte) All numeric data types are signed
short (2 bytes) The size of data types remain the
int (4 bytes) same on all platforms (standardized)

long (8 bytes) char data type in Java is 2 bytes


because it uses UNICODE character
Floating Type
set. By virtue of it, Java supports
float (4 bytes)
internationalization
double (8 bytes)
UNICODE is a character set which
Textual covers all known scripts and
char (2 bytes) language in the world

Logical
boolean (1 byte) (true/false)

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 25
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 26
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 27
Technologies Ltd Version 1.00
Reference Types (3 of 3)

Use of a reference variable is similar to using the remote to operate the


television

ChangeChannel(6)

ChangeVolume(INCREASE)
TV (object)
Remote Control
(reference variable)

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 28
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 29
Technologies Ltd Version 1.00
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;

BEST PRACTICE: Declare a variable in program only when


required. Do not declare variables upfront like in C.

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

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 30
Technologies Ltd Version 1.00
Variables -- declaration and initialization (1 of 2)

Variables must have a type

Variables must have a name

int count
name

type

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 31
Technologies Ltd Version 1.00
Variables -- declaration and assignment (2 of 2)
Assigning a value to the variable

count =10;

Declaration and initialization may be combined in a single step

int count =10;

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 32
Technologies Ltd Version 1.00
Give it a try….

What will be the output of the following code snippet when you try to compile
and run it?

class Sample{
public static void main (String args[]){
args[]){
int count;
System.out.println(count);
System.out.println(count);
}
}

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 33
Technologies Ltd Version 1.00
Typecasting of primitive data types

Automatic, non-explicit type changing is known as Conversion


– Variable of smaller capacity can be assigned to another variable of bigger capacity

int i = 10;

double d;

d = i;

Whenever a larger type is converted to a smaller type, we have to explicitly


specify the type cast operator
Type cast operator
double d = 10

int i;

i = (int) d;

– This prevents accidental loss of data

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 34
Technologies Ltd Version 1.00
Typecasting of primitive data types –(Contd…)

Please find more explanation of the previous slide in the notes page

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 35
Technologies Ltd Version 1.00
Operators and Assignments

Arithmetic Operators:

The Bitwise operators:

Relational Operators:

Boolean Logical operators:

The ternary operator:

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 36
Technologies Ltd Version 1.00
Operators and Assignments –(Contd…)

Please find more explanation of the previous slide in the notes page

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 37
Technologies Ltd Version 1.00
Operators and Assignments –(Contd…)

Please find more explanation of the previous slide in the notes page

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 38
Technologies Ltd Version 1.00
Constituents of a Class
public class Student {
private int rollNo;
rollNo;
Data Members
private String name;
(State)

Student(){
//initialize data members
} Constructor
Student(String nameParam){
nameParam){
name = nameParam;
nameParam;
}
public int getrollNo (){
return rollNo;
rollNo;
Method (Behavior)
}
}

The main method may or may not be present depending on whether the class is a starter class

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 39
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 40
Technologies Ltd Version 1.00
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. : obj1 is reference


variable
Student obj1;

obj1 = new Student();

Or
new keyword creates
Student obj2 = new Student(“Jack”); an object and returns
a reference to it

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 41
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 42
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 43
Technologies Ltd Version 1.00
Lifetime of objects (1 of 2)
obj1

Student obj1 = new student(); 1

Student obj2 = new student(); heap

The two Student objects are now living on the heap 2

-- References: 2
obj2

-- Objects: 2

obj1

Student obj3 = obj2;


1
-- References: 3 heap
obj3 2
-- Objects: 2

obj2

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 44
Technologies Ltd Version 1.00
Lifetime of objects (2 of 2)
obj1

obj3 = obj1;
1
-- References: 3 ob3 heap
2

-- Objects: 2

obj2

obj2 = null;

-- Active References: 2
obj1

-- null references: 1
1
-- Reachable Objects: 1 ob3 heap

-- Abandoned objects: 1 2 This object can be


garbage collected
(Can be Removed
obj2 from memory)
Null reference

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 45
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 46
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 47
Technologies Ltd Version 1.00
Variables and their scope (2 of 3)

class Student{ rollNo and name are


instance variables, to be
stored in the heap
int rollNo;

String name;

public void display (int z){

int x=z+10;

} z and x are local


variables to be stored in
the stack

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 48
Technologies Ltd Version 1.00
Variables and their scope (3 of 3)

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 49
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 50
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 51
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 52
Technologies Ltd Version 1.00
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


* Sum of two numbers. This method is invoked from another class
* by passing the necessary values as parameters
*/

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 53
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 54
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 55
Technologies Ltd Version 1.00
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


An array holding 5 int elements

20 50 45 100 70

An array holding 4 rabbit objects

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 56
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 57
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 58
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 59
Technologies Ltd Version 1.00
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){


x[i] = 5;
}

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 60
Technologies Ltd Version 1.00
Arrays in Java (6 of 7)

Multidimensional arrays are arrays of arrays.

To declare a multidimensional array variable, specify each additional index


using another set of square brackets.

-- Ex: int twoD[ ][ ] = new int[4][5] ;

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 61
Technologies Ltd Version 1.00
Arrays in Java (7 of 7)

When you allocate memory for a multidimensional array, you need only specify
the memory for the first (leftmost) dimension

You can allocate the remaining dimensions separately.

In Java the length of each array in a multidimensional array is under your


control.

Ex:
– int twoD[][] = new int[4][];

– twoD[0] = new int[5];

– twoD[1] = new int[6];

– twoD[2] = new int[7];

– twoD[3] = new int[8];

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 62
Technologies Ltd Version 1.00
this keyword(1 of 2)
class Counter{ class CounterTest{

private int data; public static void main(String args[]){

Counter a = new Counter(10);


Counter(int var1){
a.increment();
data=var1;
System.out.println(a.getData());
}
System.out.println(a.getData());
public void increment(){ Counter b = new Counter(25);
++data;
b.increment();
} System.out.println(b.getData());

public int getData(){ }


return data; }
}

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 63
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 64
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 65
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 66
Technologies Ltd Version 1.00
static (3 of 4) The static duckCount variable is
initialised to 0, ONLY when the
class is first loaded, NOT each time
Class Duck { a new instance is made

private int size;


private static int duckCount;
duckCount;
public Duck(){
duckCount++;
duckCount++;
}
public void setSize (int s){ Each time the constructor is invoked ie
an object gets created, the static
size = s; variable duckCount will be incremented
} thus keeping a count of the total no of
Duck objects creataed
public int getSize (int s){
return size;
} Which duck? Whose size? A static
public static void main(String args[]){ method cannot access anything
args[]){
non-static
System.out..println(“
System.out..println(“Size of the duck is;”
is;” + size);
}
}

Compilation
error

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 67
Technologies Ltd Version 1.00
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

class Test{
static {
//Code
//Code goes here
}
}

– A static block helps to initialize the static data members just like constructors help to
initialize instance members

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 68
Technologies Ltd Version 1.00
Java Native API (JNI)

Even though Java is platform independent, it can call a platform specific


function that is written in another language like C or C++

Such methods are qualified with the keyword native, to show that it is native
code and not implemented using Java

Java provides an API specially to handle native (platform-specific) code

The library has to be loaded in the static block using the method call
System.loadLibrary

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 69
Technologies Ltd Version 1.00
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
Copyright © 2005, Infosys 70
Technologies Ltd Version 1.00
Summary:
– Review of Object Oriented Concepts

– Java architecture

– The basic constructs in Java

ER/CORP/CRS/LA10/003
Copyright © 2005, Infosys 71
Technologies Ltd Version 1.00

You might also like