5UNIT-I
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
will be shared by a set of objects.
The data defined by the class are referred to as
member variables or instance variables.
The code that operates on that data is referred
to as member methods or just methods.
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
6UNIT-I
Inheritance is the process by which one object
acquires the properties of another object.
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
7UNIT-I
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.
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
UNIT-I
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.
8UNIT-I
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
9UNIT-I
10UNIT-I
11UNIT-I
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.
Programs
12UNIT-I
Programming Languages
Machine Language :
Assembly Language :
High-Level Language :
13UNIT-I
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)
14UNIT-I
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.
16UNIT-I
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
19UNIT-I
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.
20UNIT-I
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.
Java Bytecode
Java Virtual
Machine
Any
Computer
21UNIT-I
Java is Compiled and Interpreted
Text Editor Compiler Interpreter
Programmer
Source Code
.java file
Byte Code
.class file
Hardware and
Operating System
Notepad,
editplus,
Edit etc
javac
java
appletviewer
netscape
22UNIT-I
22
Java Translation and Execution
Java source code
Java compiler
Java interpreter
for Windows
Java interpreter
for Razr v2
Java bytecode
Java interpreter
for Mac
Java interpreter
for Linux
23UNIT-I
24UNIT-I
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
25UNIT-I
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
Because Java inherits C/C++
syntax and many of the object-
oriented features of C++,
learning Java will be easier.
26UNIT-I
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
Java is inherently object-oriented.
Although many object-oriented languages
began strictly as procedural languages,
Java was designed from the start to be
object-oriented. Object-oriented
programming (OOP) is a popular
programming approach that is replacing
traditional procedural programming
techniques.
One of the central issues in software
development is how to reuse code. Object-
oriented programming provides great
flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.
27UNIT-I
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
Distributed computing involves
several computers working
together on a network. Java is
designed to make distributed
computing easy.
Java also supports Remote
Method Invocation (RMI).
28UNIT-I
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
Java enables the creation of cross-
platform programs by compiling
into an intermediate representation
called Java bytecode. This code
can be executed on any system
that implements the Java Virtual
Machine
29UNIT-I
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
Java compilers can detect many
problems that would first show up at
execution time in other languages.
Java has eliminated certain types of
error-prone programming constructs
found in other languages.
Java has a runtime exception-handling
feature to provide programming
support for robustness.
30UNIT-I
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
By using a Java-compatible web
browser, we can safely download
Java applets without fear of viral
infection or malicious intent.
Java achieves this protection by
confining a Java program to the
Java execution environment and
not allowing it access to other parts
of the computer.
31UNIT-I
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
Write once, run anywhere
With a Java Virtual Machine (JVM),
you can write one program that will run
on any platform.
32UNIT-I
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
Because Java is architecture neutral,
Java programs are portable.
They can be run on any platform
without being recompiled.
33UNIT-I
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
The Just-in-time compilers allow the
platform-independent Java programs to
be executed with nearly the same run-
time performance as conventional
compiled programs
34UNIT-I
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
Multithread programming is smoothly
integrated in Java, which allows you to
write programs that do many things
simultaneously. Whereas in other
languages you have to call procedures
specific to the operating system to enable
multithreading.
35UNIT-I
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
Java programs carry with them substantial
amounts of run-time type information that is
used to verify and resolve accesses to
objects at run time. This makes it possible
to dynamically link code in a safe and
expedient manner.
36UNIT-I
37UNIT-I
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.
Comments
38UNIT-I
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.
39UNIT-I
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.
40UNIT-I
( ) Method definition and invocation, defining precedence in
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.
Separators
41UNIT-I
enum
Keywords are reserved words recognized by Java that
cannot be used as identifiers.
Java defines 50 keywords as follows:
Keywords
42UNIT-I
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
43UNIT-I
Integers:
NameWidth 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
short16 -32,768 to 32,767
byte 8 -128 to 127
44UNIT-I
Name Width Range
double 64 4.9e-324 to 1.8e+308
float 32 1.4e-045 to 3.4e+038
Floating-Point Types:
45UNIT-I
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.
46UNIT-I
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.
47UNIT-I
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.
Ex: 0b1011, 0B11011
48UNIT-I
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
49UNIT-I
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
50UNIT-I
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.
51UNIT-I
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.
52UNIT-I
Escape SequenceDescription
\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
Character Escape Sequence
53UNIT-I
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.
type identifier [ =value][, identifier [=value] …];
54UNIT-I
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.
55UNIT-I
56UNIT-I
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 …
57UNIT-I
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.
b=(byte)i;
i=(int)d;
Casting Incompatible Types:
Ex:- int i=257;
byte b;
double d=456.132;
58UNIT-I
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);
Automatic Type Promotion in Expressions:
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.
59UNIT-I
60UNIT-I
Arrays
An array is a group of like-typed variables that are referred to
by a common name.
One-Dimensional Arrays
Multidimensional Arrays
61UNIT-I
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 };
62UNIT-I
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];
Multidimensional Arrays:
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];
65UNIT-I
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
Arithmetic Operators:
66UNIT-I
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
Bitwise Operators:
67UNIT-I
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
Relational Operators:
68UNIT-I
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
Boolean Logical Operators:
71UNIT-I
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.
72UNIT-I
Selection statements:
if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.
73UNIT-I
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;
74UNIT-I
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 by a colon.
75UNIT-I
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.
76UNIT-I
77UNIT-I
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.
78UNIT-I
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
}
}
79UNIT-I
• 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.
Class Fundamentals
80UNIT-I
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( );
Box mybox;
mybox=new Box( );
null
mybox
mybox
width
height
depth
Ex:-
class Box
{
double width;
double height;
double depth;
}
81UNIT-I
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 3
rd
statement b2 refers to the same object as b1 refer to.
Any changes made to object through b2 will affect to b1.
width
height
depth
b1
b2
Box object
null
UNIT-I
UNIT-I
84UNIT-I
85UNIT-I
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.
Box(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}
Ex:-
Box( ) {
width=10;
height=20;
depth=30;
}
Box b1=new Box( );
Box b2=new Box(40,50,60);
UNIT-I
87UNIT-I
88UNIT-I
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
90UNIT-I
91UNIT-I
The this Keyword:
‘this’ keyword can be used inside any method to refer to the current object.
class Rect {
int length,breadth;
void init(int a, int b){
length=a;
breadth=b;
}
}
Rect r1=new Rect( );
r1.init(10,20);
class Rect {
int length,breadth;
void init(int length,
int breadth){
length=length;
breadth=breadth;
}
}
Rect r1=new Rect( );
r1.init(10,20);
class Rect {
int length,breadth;
void init(int length,
int breadth){
this.length=length;
this.breadth=breadth;
}
}
Rect r1=new Rect( );
r1.init(10,20);
92UNIT-I
93UNIT-I
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
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)