Download as pdf or txt
Download as pdf or txt
You are on page 1of 100

Java Programming

Unit-I

UNIT-I 1
UNIT-I 2
Content
s:Data abstraction Control flow, block scope
Encapsulation Conditional statements
Inheritance Loops
Benefits of inheritance Break and continue statements
Polymorphism Simple java program
Classes and objects Arrays
Procedural and OOP paradigms Input and output, formatting output
Constructors
History of Java Methods, parameter passing
Java buzzwords static fields and methods
Comments Access control
Data types, variables, constants this reference
Scope and life time of variables Overloading methods
Operators, operator hierarchy Overloading constructors
Expressions Recursion
Type conversion and casting Garbage collection
Enumerated types Building strings
Exploring string class
UNIT-I 3
OOP Principles
Encapsulation:

Inheritance:

Polymorphism:

UNIT-I 4
OOP Principles
Encapsulation: Encapsulation is the mechanism that binds
together code and the data it manipulates.
In Java, the basis of encapsulation is the class.
A class defines the structure and behavior that
Inheritance: will be shared by a set of objects.

The data defined by the class are referred to as


Polymorphism: member variables or instance variables.
The code that operates on that data is referred
to as member methods or just methods.

UNIT-I 5
OOP Principles
Encapsulation:

Inheritance: Inheritance is the process by which one object


acquires the properties of another object.

Polymorphism:

UNIT-I 6
OOP Principles
Encapsulation:

Inheritance:

Polymorphism: Polymorphism is a feature that allows one


interface to be used for a general class of
actions.
The specific action is determined by the exact
nature of the situation.

UNIT-I 7
Forms of Inheritance:

Inheritance for Specialization: The child is special case of the parent class.
Inheritance for Specification: The parent class defines behavior that is
implemented in the child class but not in the parent class.
Inheritance for Construction: The child class makes use of the behavior provided
by the parent class but is not a subtype of the parent class.
Inheritance for Extension: The child class adds new functionality to the parent
class, but does not change any inherited behavior.
Inheritance for Limitation: The child class restricts the use of some of the behavior
inherited from the parent class.
Inheritance for Combination: The child class inherits features from more than one
parent class.

UNIT-I 8
UNIT-I
Benefits of Inheritance:

Some of the important benefits of inheritance:


Software Reusability
Increased Reliability
Code Sharing
Consistency of Interface
Software Components
Rapid Prototyping
Polymorphism and Frameworks
Information Hiding

UNIT-I 9
UNIT-I
UNIT-I 10
Progra
ms
Computer programs, known as software, are instructions to
the computer.

Without programs, a computer is an empty machine.

Computers do not understand human languages, so we


need to use computer languages to communicate with them.

Programs are written using programming languages.

UNIT-I 11
Programming
Languages
Machine Language :

Assembly Language :

High-Level Language
:

UNIT-I 12
Programming
Languages
High-Level Language
:COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC (Beginner All-purpose Symbolic Instructional Code)
Pascal (named for Blaise Pascal)
Ada (named for Ada Lovelace)
C (whose developer designed B first)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C++ (an object-oriented language, based on C)
Java (We use it in the book)

UNIT-I 13
Compiling Source Code
A program written in a high-level language is called a source
program.
Since a computer cannot understand a source program.
Program called a compiler is used to translate the source
program into a machine language program called an object
program.
The object program is often then linked with other supporting
library code before the object can be executed on the machine.

UNIT-I 14
UNIT-I 15
Java’s History
• Java was conceived by James Gosling at Sun
Microsystems in 1991.
• It took 18 months to develop the first working version.
• This language was initially called “Oak”, but was renamed
“Java” in 1995.
• Java is the name of the island in Indonesia.
• The Java coffee is from the Java island.
• The name was chosen during one of several brainstorming
sessions held by the Java software team.
• "Java" was chosen from among many, many suggestions.
• The name is not an acronym, but rather a reminder of that
hot, aromatic stuff that many programmers like to drink lots
of
UNIT-I 16
UNIT-I 17
JDK Versions

JDK 1.0 (January 21, 1996)


JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)

UNIT-I 18
JDK Editions
• Java Standard Edition (J2SE)
• J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
• J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
• J2ME can be used to develop applications for mobile
devices such as cell phones.

UNIT-I 19
Compiling Java Source
Code
Java was designed to run object programs on any platform.
With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
The bytecode can then run on any computer with a Java Virtual
Machine.
Java Virtual Machine is a software that interprets Java
bytecode.

UNIT-I 20
Java is Compiled and
Interpreted
Hardware and
Programmer
Operating System

Source Code Byte Code


Text Interprete
Compiler
Editor r
.java file .class file

Notepad, java java


editplus, c appletviewer
Edit etc netscape

UNIT-I 21
Java Translation and
Execution
Java source code

Java compiler

Java bytecode

Java Java Java Java


interpreter interpreter interpreter interpreter
for Windows for Mac for Razr v2 for Linux

UNIT-I 22
22
UNIT-I 23
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 24
Characteristics of Java
• Java Is Simple Because Java inherits C/
• Java Is Object-Oriented C++ syntax and many of
the object-oriented
• Java Is Distributed
features of C++, learning
• Java Is Interpreted Java will be easier.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 25
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
• Java Is Object-Oriented Although many object-oriented
languages began strictly as
• Java Is Distributed procedural languages, Java was
designed from the start to be object-
• Java Is Interpreted oriented. Object-oriented
• Java Is Robust programming (OOP) is a popular
programming approach that is
• Java Is Secure replacing traditional procedural
• Java Is Architecture-Neutral
programming techniques.

• Java Is Portable One of the central issues in


• Java's Performance software development is how to
reuse code. Object-oriented
• Java Is Multithreaded programming provides great
• Java Is Dynamic flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.26
UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented Distributed computing involves
several computers working
• Java Is Distributed together on a network. Java is
designed to make distributed
• Java Is Interpreted computing easy.
• Java Is Robust Java also supports Remote
Method Invocation (RMI).
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 27
Characteristics of Java
• Java Is Simple Java enables the creation of cross-
platform programs by compiling
• Java Is Object-Oriented into an intermediate representation
• Java Is Distributed called Java bytecode. This code
can be executed on any system
• Java Is Interpreted that implements the Java Virtual
• Java Is Robust Machine

• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 28
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many
• Java Is Distributed problems that would first show up at
execution time in other languages.
• Java Is Interpreted
• Java Is Robust Java has eliminated certain types of
error-prone programming constructs
• Java Is Secure found in other languages.
• Java Is Architecture-Neutral
Java has a runtime exception-
• Java Is Portable handling feature to provide
• Java's Performance programming support for robustness.

• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 29
Characteristics of Java
• Java Is Simple By using a Java-compatible web
browser, we can safely download
• Java Is Object-Oriented Java applets without fear of viral
• Java Is Distributed infection or malicious intent.

• Java Is Interpreted Java achieves this protection by


confining a Java program to the
• Java Is Robust Java execution environment and
not allowing it access to other parts
• Java Is Secure of the computer.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 30
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Write once, run anywhere
• Java Is Interpreted With a Java Virtual Machine (JVM),
you can write one program that will
• Java Is Robust run on any platform.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 31
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Because Java is architecture neutral,
Java programs are portable.
• Java's Performance They can be run on any platform
• Java Is Multithreaded without being recompiled.

• Java Is Dynamic
UNIT-I 32
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable The Just-in-time compilers allow the
platform-independent Java programs to
• Java's Performance be executed with nearly the same run-
• Java Is Multithreaded time performance as conventional
compiled programs
• Java Is Dynamic
UNIT-I 33
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Multithread programming is smoothly
• Java Is Distributed integrated in Java, which allows you to
• Java Is Interpreted write programs that do many things
simultaneously. Whereas in other
• Java Is Robust languages you have to call procedures
specific to the operating system to
• Java Is Secure enable multithreading.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 34
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
Java programs carry with them substantial
• Java Is Portable amounts of run-time type information that
• Java's Performance is used to verify and resolve accesses to
objects at run time. This makes it possible
• Java Is Multithreaded to dynamically link code in a safe and
• Java Is Dynamic expedient manner.
UNIT-I 35
UNIT-I 36
Comment
s
Three types of comments

• Single-line //
• Multi-line /* */
• Documentation comment /** */
This type of comment is used to produce an HTML file
that documents your program.

UNIT-I 37
Naming Conventions
• Variables and method names:
• Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word in
the name.
For example:- radius, area, computeArea.
• Class names:
• Capitalize the first letter of each word in the name.
Example:- FirstProgram, Sample, DemoBoxWeight.
• Constants:
• Capitalize all letters in constants, and use underscores
to connect words.
Example:- PI, MAX_VALUE.
UNIT-I 38
Identifiers
• An identifier is a sequence of characters that consist of
uppercase and lowercase letters, digits, underscores ( _ ),
and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.

UNIT-I 39
Separator
() s and invocation, defining precedence in
Method definition
expressions, in control statements and type casting.
{} Initializing arrays, define blocks of code for classes,
methods and local scopes.
[] Declare array types, dereference array types.
; Terminates statements.
, In variable declaration, in for statement.
. To separate package names from sub packages and
classes and to separate a variable or method from a
reference variable.
UNIT-I 40
Keyword
s words recognized by Java that
Keywords are reserved
cannot be used as identifiers.
Java defines 50 keywords as follows:

enum

UNIT-I 41
Data Types
Java defines eight primitive data types:
byte, short, int, long, char, float, double and boolean.
These are put into four groups:
→ Integers

→ Floating-point numbers
→ Characters

→ Boolean

UNIT-I 42
Integers
:

Name Width Range

long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

int 32 -2,147,483,648 to 2,147,483,647

short 16 -32,768 to 32,767

byte 8 -128 to 127

UNIT-I 43
Floating-Point Types:

Name Width Range

double 64 4.9e-324 to 1.8e+308

float 32 1.4e-045 to 3.4e+038

UNIT-I 44
Characters:
► In Java, the data type used to store characters is char.
► Java uses Unicode to represent characters.
► Unicode defines a fully international character set that can
represent all of the characters found in all human languages.
Such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul and many more.
► For this purpose char is 16 bits width.
► The range of char is 65,536.
► The standard set of characters known as ASCII in Unicode
ranges from 0 to 255.
UNIT-I 45
Booleans:
► Java has a primitive type called boolean for logical values.
► It can have only one of two possible values, true or false.
► It requires one bit.
► When a boolean value is output by println( ), “true” or “false
is displayed.
► If b is boolean variable, then there is no need to write an if
statement like this:
if(b==true) …
► The outcome of a relational operator is boolean value.

UNIT-I 46
Literals
Integer Literals:
► Integer literals can be represented using any of the three
bases decimal, octal, hexadecimal and binary(Java SE 7).
► Any whole number is a decimal(base 10) number.
► Octal(base 8) values are denoted in Java by a leading zero.
Ex: 05, 012,0734
► Hexadecimal(base 16) values are denoted in Java by a
leading zero-x(0x or0X). Digits is 0 to 9, A to F (a to f).
Ex: 0x12, 0X45, 0X1B
► Binary(base 2) values are denoted in by a leading 0b or0B.
UNIT-I 47
Ex: 0b1011, 0B11011
Integer Literals:

► From Java SE 7 underscore can be used in integer literals.


Ex: int a=25_37 which is equivalent to a=2537

► Integer literals create a int value which is a 32-bit integer


value and can be assigned even to byte and short if it is
in the range.

► Integer literals can also be used for long, however we can


specify long literals explicitly by appending an upper or
lower case L to integer literal.

Ex: 1234L,0x52dfL

UNIT-I 48
Floating-Point Literals:

► Floating-point numbers represent decimal values with a


fractional component. They can be expressed in either
standard or scientific notation.
Standard notation: 2.34, 3.14159
Scientific notation: 6.022E23, 314159e-5

► Floating-point literals in Java default to double precision.


► To specify a float literal, append an F or f to the constant.
Ex:- 24.89f, 10076.45F
► double literal can also be specified explicitly by appending a

D or d.
Ex:- 24.89, 24.89d, 12.0056D

UNIT-I 49
Boolean
Literals:
► There are only two logical values that boolean can have,
true
and false.
► The true literal in Java does not equal 1 nor does the false
literal equal 0.

UNIT-I 50
Character Literals:
A character literal is represented inside a pair of single
quotes.
All of the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, ‘@’.
For characters that are impossible to enter directly, there
are several escape sequences to enter the character.

UNIT-I 51
Character Escape
Sequence
Escape Sequence Description
\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character(xxxx)
\’ Single quote
\” Double quote
\\ Blackslash
\r Carriage return
\n New line
\f Form feed
\t Tab
\b Backspace
UNIT-I 52
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.

type identifier [ =value][, identifier [=value]


…];

UNIT-I 53
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.
► In Java, the two major scopes are those defined by a class
and those defined by a method.

UNIT-I 54
UNIT-I 55
Type Conversion and Casting
Java supports both automatic type conversion and casting.

Java’s 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.
When these two conditions are met, a widening conversion
takes place.
Ex:- int to long, byte to int, float to double …

UNIT-I 56
Casting Incompatible
Types:
To create a conversion between two incompatible types use
a cast. A cast is an explicit type conversion. The general
form is:
(target-type) value
This type of conversion is some times called a narrowing
conversion.
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.

Ex:- int i=257; b=(byte)i;


byte b;
i=(int)d;
double d=456.132;
UNIT-I 57
Automatic Type Promotion in
Expressions:
Java automatically promotes each byte or short operand to
int when evaluating an expression.
Ex:- byte a=5, b=10;
a=a*b; //error
int c=a*b;
a=(byte)(a*b);
In addition to the above, Java automatic type promotion rules
are:
1. If one of the operands is double, the whole expression is
promoted to double.
2. Otherwise, if one of the operands is float, the whole
expression is promoted to float.
3. Otherwise, if one of the operands is long, the whole
expression is promoted to long.
UNIT-I 58
UNIT-I 59
Arrays
An array is a group of like-typed variables that are referred
to by a common name.

One-Dimensional
Arrays

Multidimensional Arrays

UNIT-I 60
One-Dimensional Arrays:

The general form of a one-dimensional array declaration is:


type array-var[ ];
type[ ] array-var;
To allocate memory to an array new operator is used.
array-var=new type[size];

Ex:- int nums[ ]; int[ ] vals;


nums= new int[10]; vals=new int[20];

Array initializer will not use new operator.


Ex:- int days[ ]={ 1,2,3,4,5,6,7 };

UNIT-I 61
Multidimensional
Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];

int twoDim2[ ][ ]=new int[4][ ];


twoDim2[0]=new int[1];
twoDim2[1]=new int[2];
twoDim2[2]=new int[3];
twoDim2[3]=new int[4];

UNIT-I 62
UNIT-I 63
Operators

Arithmetic Operators

Bitwise Operators

Relational Operators

Boolean Logical
Operators

UNIT-I 64
Arithmetic
Operators:
The operands of the arithmetic operators must be of a numeric
type. These can also be used on char types.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
UNIT-I 65
Bitwise Operators:
Java defines several bitwise operators which can be applied to the types,
long, int, short, char and byte. These operators act upon the individual bits
of their operands. Operator Description
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclisive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclisive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
UNIT-I 66
Relational
Operators:
The relational operators determine the relationship that one
operand has to the other. The outcome of these operations is a
boolean value.

Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

UNIT-I 67
Boolean Logical
Operators:
These operators operate only on boolean operands and result
a boolean value.
Operator Description
& Logical AND
| Logical OR
^ Logical XOR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

UNIT-I 68
Operator Precedence:

() [] .
High
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
Low
?:
= Op= UNIT-I 69
UNIT-I 70
Control Statements
Java’s control statements are put into three categories:
• Selection statements: if and switch.
• Iteration statements: for, while and do-while.
• Jump statements: break, continue and return.

UNIT-I 71
Selection statements:

if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.

UNIT-I 72
Iteration
statements:
while
do-while
for
In J2SE 5 a new version of for loop known as For-Each loop
was introduced.
Its general form is:
for( type itr-var : collection) statement-block

Collection is of any type of collection or array.

int nums[ ]={10,20,30,40,50};


int sum=0;
for(int x : nums) sum+=x;

UNIT-I 73
Jump Statements:
break:
In java, the break statement has three uses,
• In a switch statement.
• To exit a loop.
• Can be used as a form of goto.
The general form of the third type of break is:
break label;
Label is the name of a label that identifies a block of code.
When this form of break executes control is transferred out of
the named block of code.
Java label is a valid identifier followed
UNIT-I
by a colon. 74
continue:
Used in loops.
Also used with label.
The general form of continue with label is:
continue label;
return:
The return statement is used to explicitly return from a method.

UNIT-I 75
UNIT-I 76
Class Fundamentals
• A class defines a new data type.

• Once defined can be used to create objects of that type.

• A class is a template for an object.

• An object is an instance of a class.

UNIT-I 77
The general form of a class definition is:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list){
// body of method
}
// . . .
type methodnameM(parameter-list){
// body of method
}
UNIT-I 78
}
Class Fundamentals
• The data (or) variables defined within a class are called instance
variables because each instance (object) of the class contains its own
copy of these variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called
members of the class.

UNIT-I 79
Declaring Objects:
The object is defined in two-steps:
1. Declare a variable of the class type.
classname class-var;
2. Acquire an actual, physical copy of the object and assign it to that
variable using a new operator.
class-var=new classname( );

Ex:- Box mybox; null


class Box
mybo
{
x
double width;
double height; mybox=new Box( ); width
double depth;
} mybo height
x depth
UNIT-I 80
Assigning Object Reference Variables:
Box b1=new Box();
Box b2;
b2=b1;
After these above statements both b1 b2 refer to the same object.
In the first statement object b1 is created and memory is allocated to it.
After the 3rd statement b2 refers to the same object as b1 refer to.
Any changes made to object through b2 will affect to b1.

width
b1
height Box object
depth
nul
l
b2
UNIT-I 81
UNIT-I
UNIT-I
UNIT-I 84
Constructors:
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides.
Similar to a method but does not have a return type.
Automatically called immediately after the object creation, before new
operator completes.
The constructor’s job is to initialize the internal state of an object.
Constructors can be with no parameters (default) as well as with
parameters.

Ex:-
Box( ) { Box(double w, double h, double d) { Box b1=new Box( );
width=10; width=w;
height=20; height=h;
depth=30; depth=d; Box b2=new Box(40,50,60);
} }
UNIT-I 85
UNIT-I
UNIT-I 87
Methods:
The general form of a method:
type name(parameter-list){
// body of method
}

Overloading Methods:
• In a class, if two or more methods are defined with the same name and
different parameter declarations, then the methods are said to be
overloaded
and the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• Variable-Length Arguments

UNIT-I 88
UNIT-I
UNIT-I 90
The this Keyword:
‘this’ keyword can be used inside any method to refer to the current object.
class Rect { class Rect { class Rect {
int length,breadth; int length,breadth; int length,breadth;
void init(int a, int b){ void init(int length, void init(int length,
length=a; int breadth){
int breadth){ this.length=length;
breadth=b;
length=length;
} this.breadth=breadth;
breadth=breadth;
} }
} }
}

Rect r1=new Rect( ); Rect r1=new Rect( );


Rect r1=new Rect( );
r1.init(10,20); r1.init(10,20);
r1.init(10,20);
UNIT-I 91
UNIT-I 92
Garbage Collection:
In java, objects are dynamically allocated by using the new operator.
Such objects are automatically destroyed and their memory is released
when
no references to the objects exists.
The technique that accomplishes this is called garbage collection.
Sometimes an object will need to perform some action when it is destroyed.
Java provides a mechanism called finalization using which we can define
specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, simply define the finalize() method, which the
Java runtime calls this method whenever it is about to recycle an object.
protected void finalize( ) {
// finalization code
}
UNIT-I 93
Recursion:

Recursion Java supports recursion. Recursion is the process of defining something in


terms of itself. As it relates to Java programming, recursion is the attribute that allows a
method to call itself. A method that calls itself is said to be recursive

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

UNIT-I
Introducing Nested and Inner Classes:

It is possible to define a class within another class; such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its
enclosing class. Thus, if class B is defined within class A, then B does not exist
independently of A. A nested class has access to the members, including private
members, of the class in which it is nested. However, the enclosing class does not
have access to the members of the nested class. A nested class that is declared
directly within its enclosing class scope is a member of its enclosing class. It is also
possible to declare a nested class that is local to a block.

There are two types of nested classes: static and non-static.


A static nested class is one that has the static modifier applied. Because it is static,
it must access the members of its enclosing class through an object. That is, it
cannot refer to members of its enclosing class directly. Because of this restriction,
static nested classes are seldom used.
The most important type of nested class is the inner class. An inner class is a non-
static nested class. It has access to all of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members
of the outer class do.

UNIT-I
UNIT-I
Exploring the String Class:

The first thing to understand about strings is that every string you create is actually
an object of type String. Even string constants are actually String objects. For
example, in the statement
System.out.println("This is a String, too");

the string "This is a String, too" is a String object.


The second thing to understand about strings is that objects of type String are
immutable;
once a String object is created, its contents cannot be altered. While this may seem
like a
serious restriction, it is not, for two reasons:

If you need to change a string, you can always create a new one that contains the
modifications. • Java defines peer classes of String, called StringBuffer and
StringBuilder, which allow strings to be altered, so all of the normal string
manipulations are still available in Java.
Strings can be constructed in a variety of ways. The easiest is to use a statement
like this:

String myString = "this is a test";


System.out.println(myString);
UNIT-I
Java defines one operator for String objects: +. It is used to concatenate two
strings. For example, this statement
String myString = "I" + " like " + "Java.";
results in myString containing "I like Java."

UNIT-I
The String class contains several methods that you can use. Here are a few. You can test two
strings for equality by using equals( ). You can obtain the length of a string by calling the
length( ) method. You can obtain the character at a specified index within a string by calling
charAt( ).

boolean equals(secondStr)
int length( )
char charAt(index)

UNIT-I
UNIT-I

You might also like