This document provides an overview of key concepts in Java programming including object-oriented principles like encapsulation, inheritance and polymorphism. It discusses Java characteristics such as being simple, object-oriented, architecture neutral and portable. It also covers Java history, compilers, data types, variables, operators, control flow statements, arrays, methods and other core Java topics. The document is intended as teaching material for an introductory Java programming course.
6. 6
UNIT-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:
UNIT I 6
7. 7
UNIT-I
Inheritance is the process by which one object
acquires the properties of another object.
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
UNIT I 7
8. 8
UNIT-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 8
9. 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.
9
UNIT-I 9
10. 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
10
UNIT-I 10
12. 12
UNIT-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
UNIT I 12
14. 14
UNIT-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)
UNIT I 14
15. 15
UNIT-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.
Compiler
Source File Object File Linker Excutable File
UNIT I 15
17. 17
UNIT-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
UNIT I 17
20. 20
UNIT-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.
UNIT I 20
21. 21
UNIT-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
UNIT I 21
22. 22
UNIT-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
UNIT I 22
23. 23
UNIT-I
23
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
UNIT I 23
25. 25
UNIT-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
UNIT I 25
26. 26
UNIT-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.
UNIT I 26
27. 27
UNIT-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.
UNIT I 27
28. 28
UNIT-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).
UNIT I 28
29. 29
UNIT-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
UNIT I 29
30. 30
UNIT-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.
UNIT I 30
31. 31
UNIT-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.
UNIT I 31
32. 32
UNIT-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.
UNIT I 32
33. 33
UNIT-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.
UNIT I 33
34. 34
UNIT-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
UNIT I 34
35. 35
UNIT-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.
UNIT I 35
36. 36
UNIT-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.
UNIT I 36
38. 38
UNIT-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
UNIT I 38
39. 39
UNIT-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.
UNIT I 39
40. 40
UNIT-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.
UNIT I 40
41. 41
UNIT-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
UNIT I 41
42. 42
UNIT-I
enum
Keywords are reserved words recognized by Java that
cannot be used as identifiers.
Java defines 50 keywords as follows:
Keywords
UNIT I 42
43. 43
UNIT-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
UNIT I 43
44. 44
UNIT-I
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 44
46. 46
UNIT-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.
UNIT I 46
47. 47
UNIT-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.
UNIT I 47
48. 48
UNIT-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
UNIT I 48
49. 49
UNIT-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
UNIT I 49
50. 50
UNIT-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
UNIT I 50
51. 51
UNIT-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.
UNIT I 51
52. 52
UNIT-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.
UNIT I 52
53. 53
UNIT-I
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
Character Escape Sequence
UNIT I 53
55. 55
UNIT-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.
UNIT I 55
57. 57
UNIT-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 …
UNIT I 57
58. 58
UNIT-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;
UNIT I 58
59. 59
UNIT-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.
UNIT I 59
61. 61
UNIT-I
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 61
62. 62
UNIT-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 };
UNIT I 62
63. 63
UNIT-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];
UNIT I 63
66. 66
UNIT-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:
UNIT I 66
67. 67
UNIT-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:
UNIT I 67
68. 68
UNIT-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:
UNIT I 68
69. 69
UNIT-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:
UNIT I 69
72. 72
UNIT-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.
UNIT I 72
74. 74
UNIT-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;
UNIT I 74
75. 75
UNIT-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.
UNIT I 75
76. 76
UNIT-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.
UNIT I 76
78. 78
UNIT-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.
UNIT I 78
79. 79
UNIT-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
}
}
UNIT I 79
80. 80
UNIT-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
UNIT I 80
81. 81
UNIT-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;
}
UNIT I 81
82. 82
UNIT-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 3rd 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 82
84. 84
UNIT-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 84
86. 86
UNIT-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 86
87. 87
UNIT-I
Variable-Length Arguments(Varargs):
A method that takes a variable number of arguments is called a variable-arity
method (or) a varargs method.
A variable length argument is specified by three periods (…).
Ex:- void add(int … v)
A method can have normal parameters along with a variable-length parameter.
The variable-length parameter must be the last parameter declared by the
method.
Ex:- void display(int a, int … p)
void test(boolean a, boolean b, double c, char … d)
There must be only one variable-length parameter
UNIT I 87
91. 91
UNIT-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);
UNIT I 91
92. 92
UNIT-I
static keyword:
Normally, a class member must be accessed only with an object of its class.
It is possible to create a member that can be accessed before any objects of
its class are created and without reference to an object.
To create such a member, precede its declaration with the keyword static.
Such members can be accessed with the class name by the dot operator.
class Sample {
static int a=10;
static int b;
static void methodOne(int p, int q) {
System.out.println(“p=“+p+”q=“+q);
}
}
int c=Sample.a+Sample.b;
Sample.methodOne(5,6);
UNIT I 92
93. 93
UNIT-I
All instances of the class share the same static variable.
static variables:
Instance variables declared as static are essentially global variables.
When objects of a class are declared, no copy of a static variable is made.
To initialize static variables, declare a static block which get executed exactly
once, when the class is first loaded.
UNIT I 93
94. 94
UNIT-I
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this and super in any way.
static methods:
UNIT I 94
95. 95
UNIT-I
final keyword:
final can be applied for variables, methods and classes.
final variable contents cannot be modified.
final variable must be initialized when it is declared.
Variables declared as final do not occupy memory on a per-instance basis.
A final variable is a constant.
Ex:- final int FILE_NEW=1;
final int FILE_OPEN=2;
UNIT I 95
97. 97
UNIT-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 97
99. 99
UNIT-I
Strings in Java:
A string is a sequence of characters.
Java implements strings as objects of type String class.
When a String object is created, a string is created that cannot be changed.
We can still perform all types of string operations, but each time an existing
string is altered a new String object is created that contains the modifications.
Java provide two classes to create modifiable strings.
They are StringBuffer and StringBuilder.
The classes String, StringBuffer and StringBuilder are defined in java.lang
package. All are final.
UNIT I 99
100. 100
UNIT-I
Constructors of String class:
String( )
String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ],int startIndex,int numChars)
String(StringBuffer strBufObj)
String(int codePoints[ ],int startIndex, int numChars) Added in J2SE 5
String(StringBuilder strBuildObj) Added in J2SE 5
UNIT I 100
102. 102
UNIT-I
String Concatenation:
The + operator concatenates two strings, producing a String object as the
result.
Example1:
String age = “9”;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
The O/P here is “He is 9 years old.”
Example2:
int age = 9;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
The O/P here is also “He is 9 years old.”
UNIT I 102
103. 103
UNIT-I
Example3:
String s = “abcdefghij “ + 20 + 30;
System.out.println( s );
The O/P here is “abcdefghij 2030”
String Concatenation:
This is because the compiler automatically converts an operand to its string
equivalent whenever the other operand of the + operator is an instance of
String.
Example4:
String s = “abcdefghij “ + (20 + 30);
System.out.println( s );
The O/P here is “abcdefghij 50”
UNIT I 103
104. 104
UNIT-I
String Conversion and toString( ):
Java converts data into its string representation during concatenation by
calling one of the overloaded versions of the string conversion method
valueOf( ) defined by String class.
valueOf( ) is overloaded for all simple types and for type Object.
static String valueOf(int num)
static String valueOf(byte num)
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(char chars[ ])
static String valueOf(Object ob)
static String valueOf(char chars[ ],int startIndex, int numChars)
UNIT I 104
105. 105
UNIT-I
For objects, valueOf( ) calls the toString( ) method on the object.
Every class implements toString( ) because it is defined by Object.
The default implementation of toString( ) is sufficient.
We can override toString( ) and provide our own string representations for
objects.
The syntax is:
String toString( )
String Conversion and toString( ):
UNIT I 105
106. 106
UNIT-I
Example:
class Rect{
int length,breadth;
Rect(int x,int y) {
length=x;
breadth=y;
}
}
class Cube {
int length,width,height;
Cube(int x,int y,int z) {
length=x;
width=y;
height=z;
}
public String toString( ) {
return "Hai I am instance of Cube class";
}
}
class String1
{
public static void main(String args[])
{
Rect r1=new Rect(10,20);
String s1=“Rect:”+r1;
System.out.println(s1);
Cube b1=new Cube(10,20,30);
String s2=“Cube:”+b1;
System.out.println(s2);
}
}
O/P :
Rect:Rect@82ba41
Cube:Hai I am instance of Cube class
UNIT I 106
107. 107
UNIT-I
Character Extraction:
String object cannot be indexed as if they were a character array.
Many of the String methods employ an index into the string for their operation
beginning at zero.
char charAt(int where)
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
byte[ ] getBytes( )
char[ ] toCharArray( )
UNIT I 107
108. 108
UNIT-I
String Comparision:
boolean equals(String str)
boolean equalsIgnoreCase(String str)
boolean regionMatches(int startIndex,String str2, int str2StartIndex,
int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex,String str2,
int str2StartIndex, int numChars)
boolean startsWith(String str)
boolean endsWith(String str)
int compareTo(String str) <0 if invoking string<str
>0 if invoking string>str
0 if two strings are equal
UNIT I 108
109. 109
UNIT-I
Searching Strings:
int indexOf(int ch) for first occurrence
int lastIndexOf(int ch) for last occurrence
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
startIndex specifies the index at which point the search begins.
UNIT I 109
110. 110
UNIT-I
Modifying a String:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String concat(String str)
String replace(char original, char replacement)
String replace(CharSequence original, CharSequence replacement)
Added in J2SE 5
String trim( )
UNIT I 110
111. 111
UNIT-I
Changing the Case of Characters within a String:
String toLowerCase( )
String toUpperCase( )
UNIT I 111
112. 112
UNIT-I
Some other String Methods:
String replaceAll(String regExp,String newStr)
int codePointAt(int i) Added by J2SE 5
int codePointBefore(int i) “
int codePointCount(int start,int end) “
boolean contains(CharSequence str) “
boolean contentEquals(CharSequence str) “
boolean contentEquals(StringBuffer str)
static String format(String fmtstr,Object … args) “
static String format(Locale loc, String fmtstr, Object … args) “
boolean matches(String regExp)
int offsetByCodePoints(int start, int num) “
String replaceFirst(String regExp,String newStr)
String[ ] split(String regExp)
String[ ] split(String regExp, int max)
CharSequence subSequence(int startIndex, int stopIndex)
UNIT I 112
115. 115
UNIT-I
Methods:
int length( ) string length
int capacity( ) total allocated capacity
void ensureCapacity(int capacity) preallocate
void setLength(int len)
char charAt(int where)
void setCharAt(int where, char ch)
void getChars(int sourceStart,int sourceEnd,char target[ ],int
targetStart)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
The new capacity is the larger of:
a. The minimumCapacity argument.
b. Twice the old capacity, plus 2.
UNIT I 115
118. UNIT-I 118
► Inheritance is the process by which one object acquires the properties of
another object.
Definition:
► The class that is inherited is called a superclass or baseclass.
► The class that does the inheriting is called a subclass or derivedclass.
► Subclass is a specialized version of a superclass.
UNIT I 118
120. UNIT-I 120
The general form of a class definition that inherits a superclass uses the
keyword extends and is shown as:
class subclass-name extends superclass-name
{
//body of class
}
Syntax:
UNIT I 120
121. UNIT-I 121
Sample program: Single Inheritance
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo1
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
} O/P:
i=10 j=20
p=50 q=60
i=30 j=40 p=50 q=60
i=30 j=40
UNIT I
122. UNIT-I 122
Java supports the following access specifiers(Modifiers)
public
private
protected
No modifier(default)
Although a subclass includes all of the members of its superclass,
it cannot access those members of the superclass that have been
declared as private.
Member Access:
UNIT I 122
123. UNIT-I 123
Sample program: Use of private keyword
class A
{
private int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo2
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
}
Compile time ERROR
UNIT I 123
124. UNIT-I 124
Superclass variable referencing a subclass object:
► A reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass.
UNIT I 124
125. UNIT-I 125
Sample program: Superclass variable referencing a subclass object
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo3
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj1=obj2;
obj1.show( );
}
}
O/P:
i=10 j=20
i=30 j=40
UNIT I
126. UNIT-I 126
super keyword:
super has two general forms:
1) To call the superclass constructor.
2) To access a member of the superclass.
Whenever a subclass needs to refer to its immediate superclass,
it can do so by use of the keyword super.
UNIT I 126
127. UNIT-I 127
super to call the superclass constructor:
► A subclass can call a constructor defined by its superclass by use of
the following form of super:
super(parameter-list)
Note: super( ) must always be the first statement inside a subclass constructor.
UNIT I 127
128. 128
class A{
int i, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int p,q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
p=c;
q=d;
Sample program: super(parameter-list)
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“i=”+i+” j=“+j+“ p=“+p+”
q=“+q);
}}
class SuperConstructor{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
i=30 j=40 p=50 q=60
i=30 j=40
UNIT I
129. UNIT-I 129
► This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.
Second use of super keyword;
The general form is:
super.member
► The super always refers to the superclass of the subclass in which it is used.
UNIT I 129
130. 130
class A{
int i, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int i, j, p, q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
i=c;
j=d;
Sample program: super.member
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“Ai=”+super.i+”Aj=“+
super.j+“ i=“+i+” j=“+j);
}}
class SuperMember{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
Ai=30 Aj=40 i=50 j=60
i=30 j=40 130
132. UNIT-I 132
class A
{
int i,j;
A( )
{
System.out.println("A default");
}
}
class B extends A
{
int p,q;
B( )
{
System.out.println("B default");
}
}
Sample Program: Multilevel Inheritance
O/P: ?
class C extends B
{
int x,y;
C( )
{
System.out.println("C default");
}
}
class ConstructorOrder1
{
public static void main(String args[ ])
{
C c1=new C();
}
}
UNIT I 132
133. UNIT-I 133
► If super( ) is not used, then the default or parameter less constructor of each
superclass will be executed.
In what order Constructors are called:
► In a class hierarchy, constructors are called in the order of derivation,
from superclass to subclass.
► Since super( ) must be the first statement executed in a subclass constructor,
this order is the same whether or not super( ) is used.
UNIT I 133
134. UNIT-I 134
class C extends B {
int x,y;
C( ) {
System.out.println("C default");
}
C(int a,int b,int c,int d,int e,int f) {
super(a,b,c,d);
x=e;
y=f;
System.out.println("C 6 args");
}
void display( ) {
System.out.println("i="+i+"j="+j+"p="+p+"q="+
q+"x="+x+"y="+y);
}}
class ConstructorOrder2 {
public static void main(String args[]) {
C c1=new C(10,20,30,40,50,60);
c1.display();
}}
class A{
int i,j;
A( ) {
System.out.println("A default");
}
A(int a, int b) {
i=a;
j=b;
System.out.println("A 2 args");
}}
class B extends A {
int p,q;
B( ) {
System.out.println("B default");
}
B(int a,int b,int c,int d) {
super(a,b);
p=c;
q=d;
System.out.println("B 4 args");
}}
Sample Program: Multilevel Inheritance
UNIT I 134
136. UNIT-I 136
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 overriden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass.
► The version of the method defined by the superclass will be hidden.
► The superclass version of an overridden method can be accessed
using super.
UNIT I 136
137. UNIT-I 137
class A{
int i, j;
void show( ){
System.out.println(“This is in A’s show “);
}}
class B extends A{
int p, q;
void show( ){
super.show( );
System.out.println(“This is in B’s show “);
}}
class Override{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B( );
obj1.show( );
obj2.show( );
}}
Sample program: Method Overriding
O/P:
This is in A’s show
This is in A’s show
This is in B’s show
UNIT I 137
138. UNIT-I 138
Dynamic Method Dispatch:
Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at run time, rather than compile time.
Java implements run-time polymorphism using dynamic method dispatch.
UNIT I 138
139. UNIT-I 139
class A {
void callme( ) {
System.out.println("A's method");
}
}
class B extends A {
void callme( ) {
System.out.println("B's method");
}
}
class C extends A {
void callme( ) {
System.out.println("C's method");
}
}
class DynamicMethodDispatch {
public static void main(String args[]) {
A a1=new A( );
B b1=new B( );
C c1=new C( );
A p1;
p1=a1;
p1.callme( );
p1=b1;
p1.callme( );
p1=c1;
p1.callme();
}
}
Sample program: Dynamic Method Dispatch
O/P:-
A’s method
B’s method
C’s method
UNIT I 139
140. UNIT-I 140
Abstract classes:
An abstract method is a method without implementation.
The general form is:
abstract type name(parameter-list);
Abstract methods must be overridden(implemented) in the subclasses.
Any class that contains one or more abstract methods must be declared
abstract.
An abstract class cannot be directly instantiated with the new keyword.
We cannot declare abstract constructors or 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.
An abstract class reference can point to a subclass object.
UNIT I 140
141. UNIT-I 141
abstract class A
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
}
Sample program1: Abstract classes
O/P:-
Param1=10 Param2=20
class AbstractClass
{
public static void main(String args[ ])
{
B b1=new B();
b1.display(10,20);
}
}
UNIT I 141
142. UNIT-I 142
Sample program2: Abstract classes
class AbstractClass2
{
public static void main(String args[ ])
{
B b1=new B( );
b1.display(10,20);
A a1;
a1=b1;
a1.display(30,40);
}
}
O/P:-
Param1=10 Param2=20
Param1=30 Param2=40
abstract class A
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
} UNIT I 142
143. UNIT-I 143
final keyword:
final can be applied for variables, methods and classes.
A final variable is a constant.
Methods declared as final cannot be overridden.
Classes declared as final cannot be inherited.
Declaring a class as final implicitly declares all of its methods as final.
UNIT I 143
144. 144
Base class Object :
Object class contains the following methods:
Object clone( )
boolean equals(Object object)
void finalize( )
Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds)
Object is superclass of all other classes.
144
145. UNIT-I 145
Subclass, Subtype and Substitutability:
When new classes are constructed using inheritance from existing
classes, the argument used to justify the validity of substitutability is
as follows:
• Instances of the subclass must possess all data fields associated with
the parent class
• Instances of the subclass must implement, through inheritance atleast
all functionality defined for the parent class.
• An instance of a child class can mimic the behavior of the parent class
and should be indistinguishable from an instance of the parent class if
substituted in a similar situation.
UNIT I 145
146. UNIT-I 146
Subclass, Subtype and Substitutability:
The term subtype is used to describe the relationship between types
that explicitly recognizes the principle of substitution.
Type B is considered to be a subtype of A if two conditions hold
•An instance of B can legally be assigned to a variable declared as type A.
•This value can then be used by the variable with no observable change in
behavior.
The term subclass refers to the mechanism of constructing a new
class using inheritance.
UNIT I 146
147. UNIT-I 147
Forms of Inheritance:
Inheritance is employed in a variety of ways.
The various forms of inheritance:
Inheritance for Specialization
Inheritance for Specification
Inheritance for Construction
Inheritance for Extension
Inheritance for Limitation
Inheritance for Combination
UNIT I 147
148. UNIT-I 148
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 148
149. UNIT-I 149
Costs of Inheritance:
Although the benefits of inheritance are great, almost nothing is without
cost of one sort or another.
Some of the costs of inheritance are:
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity
UNIT I 149