Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction to Java
Java -Introduction
A general purpose language
Is an object oriented programming language
Developed by Sun Microsystem of USA in
1991
James Gosling, Patric Naughton, Chris Warth,
Ed Frank, Mike Sheridan
Modeled on C & C++
Problem-some features of C & C++ removed.
Platform neutral language
Thus Java is a
Simple
Reliable
Portable
Powerful language
Java features
Buzzwords
Compiled & Interpreted
Simple
Portable
Object oriented
Robust
Multithreaded
Architecture neutral
High performance
Distributed
Dynamic
Simple
Java doesnt use pointers,
preprocessor header files, goto
statements
Eliminates operator overloading &
multiple inheritance
Familiarity with C & C++
Secure
Verifies all memory access
Ensures no virus communication
Pointers are absent
Portable
Generated bytecode can be used on
any machine
Primitive data types size is machine
independent
Object oriented
Almost everything in a Java is an
object
Program code and data resides
within object and classes
Has extensive set of classes,
arranged in packages
Robust
Provides safeguards to ensure
reliable code
Has strict compile/runtime checking
for data types
Supports garbage collection
No memory management problems
Supports exception handling
Multithreaded
Supports mutlithreaded programs
Improves interactive performance of
graphical applications
Has tools to support multiprocess
synchronization
Architecture-neutral
Java programs can be easily moved
from one computer system to
another, anytime and anywhere
Generated of bytecode can be used
on any machine
Primitive data types size is machine
independent
High performance
Use of intermediate bytecode
improves performance for an
interpreted language
Reduces overheads during runtime
Multithreading enhances overall
execution speed
Distributed
Ability to share both data and
program
Can open and access remote objects
on internet
Enables multiple programmers at
multiple remote locations to
collaborate and work together
Dynamic
New class libraries, methods and
objects can be dynamically linked
Type of class can be determined
through a query, making it possible
to either dynamically link or abort
the program depending on the
response
What is Bytecode?
Definition
Highly optimized set of instruction
designed to be executed on JVM
Is an output of Java compiler
Solves both security and portability
issues
Java
compiler
Virtual
program
(bytecode)
Bytecode
Java
interpreter
Machine
code
Java Applets
Definition
Special kind of Java program designed to be
transmitted over the Internet and automatically
executed by a Java-compatible web browser to
display data, handle user input. Compute
simple mathematical functionalities etc
Advantages of applet
Security:
doesnt allow access to other data of the
computer
Portability:
same applet can be downloaded and
executed by wide variety of CPUs ,OS
and browsers connected to the internet
Java interpreter
javac
Java compiler
javap
javah
javadoc
jdb
appletviewer
Abstraction
Definition:
Abstraction is the ability to focus on
essential aspects of an application
while ignoring details
Abstraction manages complexity.
Encapsulation
Definition
is the mechanism that binds together
code and the data it manipulates and
keep both safe from outside
interference and misuse
Polymorphism
Definition
Polymorphism is a property of taking many
forms; the property that an operation may
behave differently on different classes.
The ability to hide many different
implementations behind a single interface
Inheritance
Definition
The process by which one object
acquires the properties of another
object.
It supports hierarchical classification
Hello World
A Simple Java Program
/*
This is a simple Java program Example.java
to print hello world
*/
class Example
{
//program begins here
public static void main(String args[ ] )
{
System.out.println(Hello world);
}
}
Lexical Issues
Whitespaces
Java is a free form language
Identifiers
case-sensitive, sequence of upper/lower case
letters, numbers, _ , $. Must not begin with a
number
Literals
constants int, float, char, string
Comments
/* */, //
Separators
(){}[];,.
Keywords
Floating point
numbers
Characters
Boolean
byte
short
int
long
float
double
char
boolean
Integers
Name Width
Range
long
64 -9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
int
32
-2,47,483,648 to
2,47,483,647
short
16
-32, 768 to 32, 767
byte
8
-128 to 127
Name Width
double
64
float
32
Range
4.9e-324 to 1.8e+308
1.4e-045 to 3.4e+038
Characters
NOTE
Booleans
Used for logical values
Can have only one of two possible values: true
or false
is the type returned by all relational operators
is the type required by the conditional
expressions that govern the control statements
such as if and for
Variables
Variables
is the basic unit of storage
is defined by the combination of an identifier,
a type, and an optional initializer.
All variables have scope, which defines their
visibility and a lifetime.
Variables can be initialized dynamically, using
any valid expression
Type conversion
Arrays
Array
Definition
An array is a group of like-typed
variables that are referred to by a
common name
Can have one or more dimensions
Can be of any type
Elements accessed by its index
Operators
Arithmetic operators
+
*
/
%
++
+=
-=
*=
/=
%=
--
Bitwise operators
~
&
|
^
>>
>>>
<<
&=
!=
^=
>>= <<=
>>>=
Relational operators
==
!=
>
<
>=
<=
&
|
^
||
&&
!
&=
!=
^=
==
!=
?=
Other operators
=
Assignment operator
?:
Ternary operator
Flow Control
Branching
Looping
Branching
Definition
Breaking the sequential flow of the
program and jumping to another part
of the code.
Conditional branching
Unconditional branching
Conditional branching:
Branching based on a particular
condition
Unconditional branching:
Branching without any decision
Control statements
Definition
Control statements cause the flow of
execution to advance and branch
based on changes to state of a
program
Selection statements
Definition
Statements that allow program to
choose different paths of execution
based upon the outcome of an
expression or the state of a variable.
if
switch
if statement
Definition:
if statement is Javas conditional branch
statement which can be used to route
program execution through two different
paths.
General format:
if(condition)
statement1;
else
statement2;
if statement can be a
Simple if
Nested ifs
if-else-if ladder
switch statement
Definition:
switch statement is Javas multi-way branch
statement which provides easy way to
dispatch execution to different parts of the
code based on the value of an expression.
NOTE: switch is a better alternative than a
large series of if-else-if statements
General format:
switch(expression)
{
case value1:
//statements
break;
case value2: //statements
break;
NOTE:
Expression must be of the type byte, short,
int or char
Each of the values specified in the case
statements must be of a type compatible
with the expression
Each case value must be unique literal
i.e constant NOT variable
Default statement is optional
Break statement causes jumping out of the
switch
switch v/s if
Switch can only test for equality, whereas if
can evaluate any kind of Boolean expression
No two case constants in the same switch can
have identical values. A switch statement and
an enclosing outer switch can have case
constants in common.
Switch statement is usually more efficient
than a set of nested ifs
Iteration statements
Definition
Statements that enable program
execution to repeat one or more
statements from the loop.
while
do-while
for
while loop
Definition:
While loop is Javas fundamental loop
statement to repeat a statement or block
while its controlling expression is true.
General format:
while(condition)
{
//body of loop
}
do-while loop
Definition:
do-while loop is Javas loop statement to
execute the body of the loop at least once
before testing the termination expression.
General format:
do
{
//body of loop
} while(condition);
for loop
Java supports two forms of for loops
traditional form
for-each form
Traditional for statement general format:
NOTE
Loop control variable can be declared
inside the for loop
Comma can be used to include more than
one statement in the initialization,
iteration portions of the for loop
for( ; ; ) creates infinite loop
NOTE
for each loop works on multidimensional
arrays also
A large number of algorithms such as
searching, computing average, finding
maximum, minimum etc requires the
mechanism of for each loop
Loops can be nested
Jump statements
Definition
Statements that allow program to
execute in a nonlinear fashion.
break
continue
return
break statement
Three uses:
1. To terminate a statement sequence in switch
statement
2. To exit a loop
3. Can be used as civilized form of goto.
NOTE
More than one break statement may appear
in a loop
break that terminates a switch statement
affects only that switch statement and not
any enclosing loops
control statement
Used to continue running the loop but stop
processing the remainder of the code in its
body for this particular iteration
NOTE
In while and do-while loops, control is
transferred directly to the conditional
expression that controls the loop
In for loop, control goes first to the iteration
portion and then to the conditional
expresssion.
return statement
Used to explicitly return the program
control from a method to the caller of that
method.
Introduction to Java
Object
Definition:
Object is a concept, abstraction or thing
that can be individually identified and
has meaning for an application.
An object represents an entity, either
physical, conceptual, or software.
Class
Definition:
A class is a description of a group of
objects with common properties
(attributes), behavior (operations),
relationships, and semantics.
An object is an instance of a class.
type instance-variableN;
type methodname1(parameter-list) {
//body of the method
}
//.
type methodnameN(parameter-list) {
//body of the method
}
}
Sample class
class Box
{
double width, height, depth;
void volume( )
{
System.out.print("volume of box is: ");
System.out.println(width*height*depth);
}
}
Declaring objects
Box myBox = new Box( );
BOX
ob1
Box object
NOTE:
Javas primitive types are not implemented as
objects, they are implemented as normal
variables, therefore no need to use new for int,
char etc
new allocates memory for an object during
run-time
class Box {
double width, height, depth;
void volume( ) {
System.out.print("volume of box is: ");
System.out.println(width*height*depth);
}
}
Method Declaration
Methods
General form:
ret-type name( parameter-list)
{
//body of the method
}
Constructors
Constructors
Used for automatic object initialization
immediately upon creation
Has same name as the class in which it
resides
Syntactically similar to methods
Automatically called immediately after the
object is created, before the new operator
completes
Do not have return type, not even void
Implicit return type of class constructor is the
class type itself
NOTE:
If a constructor is NOT explicitly defined
for a class, then Java creates a default
constructor for the class, which
automatically initializes all instance
variables to ZERO
Parameterized constructors
Parameters can be added to the
constructor.
this keyword
Is used inside any method to refer to the
current object (this is always a reference to
the object on which the method was invoked)
Example:
Box( double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Garbage collection
When no references to an object exist, that
object is assumed to be no longer needed, and
the memory occupied by the object can be
reclaimed.
Garbage collection only occurs sporadically
during the execution of program.
It will not occur simply because one or more
objects exist that are no longer used.
finalize method
Definition:
These are the methods which defines
specific actions that will occur when an
object is just about to be reclaimed by the
garbage collector
General form:
protected void finalize( )
{
// finalization code here
}
NOTE:
finalize is NOT called when object goes
out of scope
Method Overloading
Overloading methods
Defining two or more methods within the same
class that share the same name, but with
different parameter declarations.
NOTE:
Javas automatic type conversions can also
play a role in overload resolution
Example: methOverloadAuto.java
Overloading constructors
Constructors can be overloaded.
Example: boxConstructor.java
NOTE:
The proper overloaded constructor is called
based upon the parameters specified
when new is executed
Example: objectPassing.java
NOTE:
Most common uses of object parameters
involves constructors.
i.e to initialize a new object with some
existing object.
Example: boxObjectPassing.java
Argument passing
Java supports two ways to pass an
argument to a subroutine
1. Call by value
2. Call by reference
Call by value:
This method copies the value of an argument
into the formal parameter of the subroutine.
NOTE: Changes made to the parameter of the
subroutine have no effect on the argument
Example: callByValue.java
Call by reference:
In this method a reference to an argument is
passed to the parameter. Inside the
subroutine, this reference is used to access
the actual argument specified in the call
NOTE:
When primitive type is passed to a
method, it is passed by value
When an object is passed to a method, it
is call by reference.
Returning objects
A method can return any type of data, including
class type that we create
Example: retObject.java
Introduction to Java
Inheritance,
Method Overriding,
Dynamic Method Dispatch,
Abstract
Inheritance
Inheritance
Definition
The process by which one object
acquires the properties of another
object.
It supports hierarchical classification
NOTE
General class that defines traits common to
a set of related items can be created . It can
be inherited by more specific classes
Class that is inherited superclass
Class that does inheriting subclass
Subclass inherits all of the instance
variables and methods defined by the
superclass and adds its own unique
elements
inheritBasics.java
General form
class subclass-name extends superclass-name
{
//body of class
}
inheritBasics.java
NOTE
Java does not support multiple
inheritance
Java supports multi-level inheritance
NO class can be a superclass of itself
inheritErr1.java
inheritErr2.java
Using super
super keyword can be used by a
subclass to refer to its immediate
superclass
super has two general forms:
To call superclass constructor
To access a member of the
superclass that has been hidden by a
member of a subclass
NOTE:
arg-list specifies any argument needed by the
constructor in the superclass
super( ) must always be the first statement
executed inside a subclass constructor
super( ) always refers to the superclass
immediately above the calling class
inheritSuper1.java
Method Overriding
Method overriding
When a method in a subclass has the same
name and type signature as a method in its
superclass, then the method in the subclass is
said to override the method in the superclass
When an overridden method is called from
within a subclass, it will always refer to the
version of that method defined by the subclass
inheritOverriding.java
NOTE
Method overriding occurs only when the
names and the type signature of the two
methods are identical
Otherwise its method overloading
inheritOverloading.java
Dynamic Method
Dispatch
Abstract
Abstract classes
Abstract class defines generalized form that
will be shared by all of its subclasses, leaving
it to each subclass to fill in the details
Abstract type modifier can be used with
methods if it is to be overridden by subclasses.
Abstract methods are also referred as
subclasser responsibility.
General form:
abstract type name( parameter-list);
NOTE
Any class that contains one or more abstract
methods must also be declared abstract
Use abstract keyword in front of the class
keyword at the beginning of the class declaration
An abstract class CANNOT be directly
instantiated with new operator
CANNOT declare abstract constructor nor
abstract static methods
Any subclass of an abstract class must either
implement all of the abstract methods in the
superclass, or be itself declared abstract.
inheritAbstract.java