Sei sulla pagina 1di 145

Java

Prof. Chethana R Murthy


Assistant Professor, RVCE

Introduction to Java

Java Language introduction, Java features


Why Java is important to internet?
Hello World A Simple Java Program
Lexical Issues
Java class Libraries
Variables
Data Types- Simple Types
Type conversion
Arrays
Operators
Flow Control-Branching, Looping

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

Compiled & Interpreted


Java is a 2-stage system
Compiler translates to bytecode
Interpreter generates machine code

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 Virtual Machine- JVM


Definition
Is a Java run-time system, memory resident
Is a simulated computer and does all
major functions of a real computer

Java program compilation


Java
program

Java
compiler

Virtual
program
(bytecode)

Bytecode

Java
interpreter

Machine
code

Why Java is important to


internet?

Java can be used to create websites


containing applet programs and Java
enabled browser can be used to download
an applet remotely located

Java incorporation into web pages


supports animation, graphics, games and
wide range of special effects, thus making
web pages interactive and dynamic

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 Development Kit - JDK


java

Java interpreter

javac

Java compiler

javap

Java dis-assembler (bytecode files into


program description)
For C header files

javah
javadoc
jdb

appletviewer

For creating HTML docs from Java


source code files
Java debugger to find error in
program
To view Java applets

Object oriented programming


Emphasis is on data rather than procedure
Programs are divided into objects.
Data structures are designed such that they
characterize the object
Functions that operate on the data of an object
are tied together in the data structure
Data is hidden and cannot be accessed by
external functions
New data and methods can be easily added
whenever necessary

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

Java class Libraries

Java environment has several built-in


class libraries for:
I/O handling
String handling
Networking
Graphics etc

Data Types- Simple Types

Javas most fundamental elements


Data types
Variables
Arrays

The Primitive Types


Integers

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

Floating point types

Name Width
double
64
float
32

Range
4.9e-324 to 1.8e+308
1.4e-045 to 3.4e+038

Characters
NOTE

char in Java is NOT the same as char in


C/C++
Java uses Unicode to represent characters and
is global portable
Java char is 16-bit type
Range of char is 0 to 65,536
No negative chars

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

The scope and lifetime of Variables


A scope determines what objects are visible to
other parts of your program. It also determines
the lifetime of those objects.
Global scope
Local scope
Class scope
Method scope
Scope can be nested
Declaring a variable to have the same name as
one in an outer scope is NOT allowed

Type conversion

Javas automatic conversions


When one type of data is assigned to another
type of variable, an automatic type conversion
will take place if the following two conditions
are met:
The two types are compatible
The destination type is larger than the source
type (widening conversion)

Casting Incompatible Types


Also called narrowing conversion
Done using cast: simply an explicit type
conversion. General form
(target-type) value
Casting an int to byte, if the integers value is
larger than the range of a byte, it will be
reduced modulo bytes range.
Casting float to int causes truncation

Type Promotion Rules


NOTE
Automatic type promotion can happen in
expression
All byte and short values are promoted to int
If one operand is a long, the whole expression
is promoted to long
If one operand is a float, the whole expression
is promoted to float.
If any of the operands is double, the result is
double

Java is a strongly typed language


A part of Javas safety and robustness
comes from this fact.
Every variable has a type, every expression
has a type and every type is strictly defined.
All assignments, whether explicit or via
parameter passing in method calls, are
checked for type compatibility
There are no automatic coercions or
conversions of conflicting types
Any types mismatches are errors

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

Java provides a rich operator


environment. Four groups are:
Arithmetic
Bitwise
Relational
Logical

Arithmetic operators
+
*
/
%
++

+=
-=
*=
/=
%=
--

Bitwise operators
~
&
|
^
>>
>>>

<<
&=
!=
^=
>>= <<=
>>>=

Relational operators
==
!=
>
<
>=
<=

Boolean logical operators


Operate on boolean operands

&
|
^
||
&&
!

&=
!=
^=
==
!=
?=

Other operators
=

Assignment operator

?:

Ternary operator

instanceof Gives run-time type


information about an
object

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

Javas program control statements


categorized as:
Selection
Iteration
Jump

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;

case valueN: //statements


break;
default: //statements
}

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 statement can be a


Nested switch statements
using a switch as part of the
statement sequence of an outer
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:

for (initialization; condition; iteration )


{
//body of loop
}

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

for-each version of for loop


Also called enhanced for loop
This version is designed to cycle through a
collection of objects such as an array, in
strictly sequential fashion from start to finish.
General format:
for (type itr_var : collection )
{
//body of 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

Classes- Object References,


Instance Variables,
The new operator,
The Dot(.) Operator,
Method Declaration,
Method Calling,
Constructors,
Method Overloading,

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.

General form of Java class


class classname
{
type instance-variable1;
type instance-variable2;
type instance-variable3;

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 myBox ; //declare reference to object


myBox = new Box( ); //allocate a box object

The new operator

new operator dynamically allocates memory for


an object.
Box ob1;
null ob1
obj1 = 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

Assigning object reference variables


Box b1 = new Box( );
b1
Box b2 = b1;
BOX
//
b1 = null;
b2
NOTE:
When one object reference variable is assigned
to another object reference variable, we are not
creating a copy of the object, we are only
making a copy of the reference

The Dot(.) Operator

class Box {
double width, height, depth;
void volume( ) {
System.out.print("volume of box is: ");
System.out.println(width*height*depth);
}
}

Box myBox = new Box( );


myBox.width = 10;
myBox.height = 15;
myBox.depth = 20;
myBox.volume( );

Method Declaration

Methods
General form:
ret-type name( parameter-list)
{
//body of the method
}

Returning a value from method


The type of data returned by a method
must be compatible with the return type
specified by the method.
The variable receiving the value returned
by a method must also be compatible
with the return type specified for the
method

Adding a method that takes


parameters
Parameterized method can operate on a
variety of data and/or be used in a
number of slightly different situations

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;
}

Instance variable hiding


this is used to resolve name-space collisions
Example:
Box( double width, double height,
double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}

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.

Method overloading implements polymorphism


One interface, multiple methods
Example: methOverload.java

The overloaded methods must differ in the


type and/or number of their parameters

Overloaded methods may have different


return types, but the return type alone is
insufficient to distinguish two versions of a
method
The correct version of overloaded method is
determined by type and/or number of
arguments

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

Using objects as parameters


Class objects can be used as parameters to
methods

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: Changes made to the parameter of the


subroutine will affect the argument used to
call the subroutine
Example: callByReference.java

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

Member access and inheritance


NOTE
Subclass includes all of the members
of its superclass
BUT cannot access private members of
superclass
inheritPriv.java

Superclass variable can reference


a subclass object
NOTE
Superclass reference variable can be
assigned a reference to any subclass object
derived from that superclass
Reference variable can access only those
objects defined by superclass in the
subclass. It has no knowledge of objects
added by the subclass
inheritRef.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

Using super to call superclass constructors


General form
super( arg-list )

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

Using super to access a member of the


superclass
General form
super.member
NOTE:
Member can be either a method or an instance
variable
Applicable to situations in which member names
of a subclass hide members by the same name in
superclass
inheritSuper2.java

Creating a multi-level hierarchy


In multi-level hierarchies subclass
inherits all of the traits found in all of its
superclasses
inheritMultilevel.java

When constructors are called


Constructors are called in the order of
derivation, from super class to subclass
As the superclass does not have any
knowledge about subclass any initialization it
needs to perform is separate from and possibly
prerequisite to any initialization performed by
the subclass
inheritConstructor.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

Dynamic method dispatch


Is the mechanism by which a call to an overridden
method is resolved at run time, rather than at
compile time
Dynamic method dispatch implements run-time
polymorphism
When an overridden method is called through a
superclass reference, Java determines which
version of that method to execute based upon the
type of the object being referred to at the time the
call occurs
inheritDynamic.java

Why overridden methods?


Supports run-time polymorphism
one interface, multiple methods
Combining inheritance with overridden
methods, a superclass can define the general
form of the methods that will be used by all of
its subclasses
Code reuse, robustness ability of existing
code libraries to call methods on instances of
new classes without recompiling while
maintaining a clean abstract interface .

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

Using final with inheritance


Three uses
1. Used to create the equivalent of a named
constant
2. To prevent overriding
3. To prevent inheritance

Using final to prevent overriding


Used to prevent a method from being
overridden
method declaration is preceded with final
final methods sometimes provides
performance enhancement: compiler is free to
inline calls to them because it knows they will
not be overridden by a subclass. (early
binding)
inheritFinal1.java

Using final to prevent inheritance


Used to prevent a class from being inherited
Class declaration is preceded with final
Declaring a class final implicitly declares all of
its methods as final too.
NOTE: it is illegal to declare a method as both
abstract and final!!
inheritFinal2.java

Potrebbero piacerti anche