Unit I - Java - 0
Unit I - Java - 0
Java Programming
MCA 205
Unit - I
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Learning Objectives
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Introduction
Computer Program
Set of instructions to perform a specific task.
Programming Language
Set of vocabulary and grammatical rules to instruct a
computer to perform a specific task
Programming Paradigm
General approach to solutions of problems using a
programming language. Ex: Procedural, Structured, ObjectOriented
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI1
U1.
#
Inheritance
Polymorphism
Encapsulation
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
JAVA Introduction
JAVA
Conceived by James Gosling, Patrick
Noughton, Chris Wart, Ed Frank and
C++ (Bjarne Stroustrup)
Mike Sheridan at Sun Microsystems
in 1991.
C (Dennis Ritchie)
Initially called Oak , renamed Java
in 1995.
B (Ken Thompson)
A general purpose, high-level, pure
object-oriented programming
BCPL
(Martin Richards)
language.
Designed to be a platformindependent language to be used for BASIC, COBOL, FORTRAN(High
Level Languages)
developing embedded software for
consumer electronics like
ASSEMBLY LANGUAGE
microwaves, TV remotes etc.
Is both a programming language and
MACHINE LANGUAGE
a platform.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI2
Versions of JAVA
Version
JDK 1.0
Jan,1996
JDK 1.1
Feb, 1997
J2SE 1.2
Dec, 1998
J2SE
2S 11.33
May, 2000
HotSpot
S
JVM, RMI, JavaSound
S d
J2SE 1.4
Feb, 2002
J2SE 1.5
Sep, 2004
Java SE 6
Dec, 2006
Java SE 7
July ,2011
Initial Release
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Fundamentals
1960s saw structured programming which enables modular programs
which are readable and easily modified. The paradigm however failed
with large programs of increasing complexity.
Object-Oriented programming thus organized complex programs
using the object model with principles like encapsulation, inheritance
and polymorphism.
When details of Java were being worked out,
out the www was also
emerging . This brought Java to the forefront as the web demanded
portable programs which JAVA PROVIDED.
C++
JAVA
Fig: Java, C++ and C
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
JAVA versus C
Java has similarities to both C and C++,but it is neither upwardly
nor downwardly compatible with both.
JAVA AND C
C is a structured language, java is purely object-oriented.
Java does not have C unique keywords like goto, sizeof and typedef.
C creates applications, Java creates both applications and applets.
Java unlike C does not have the data types struct, union and enum.
Java
J
ddoes not hhave the
h type modifiers
difi auto, extern, register,
i
signed
i d andd
unsigned.
Java does not support pointers.
Java does not have any pre-processor directives like #define, #include etc.
Java has no mechanism for defining variable arguments to functions.
Java adds new operators like instanceof and >>>.
Java adds labeled break and continue statements.
Java adds many OOP features not present in C.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI3
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
JAVA Buzzwords
Simple
Object-Oriented
Network-Savvy
Robust
Multithreaded
Secure
Portable
Architecture-Neutral
Interpreted
High-performance
Dynamic
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI4
APPLICATIONS
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
01
JVM
MyProgram.java
y g
j
MyProgram.class
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Welcome. java
public class Welcome
{
public static void main(String[] args)
{
System.out.println(Hello
System.out.println(
Hello World);
World );
}
}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI5
Keywords
abstract
continue
goto
package
synchronized
assert
boolean
default
do
if
implements
private
protected
this
throws
throw
break
double
import
public
byte
else
instanceof
return
transient
case
extends
int
short
try
catch
final
interface
static
void
char
finally
long
strictfp
volatile
class
const
float
for
native
new
super
switch
while
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Constants/Literals
A constant value in Java is created by using a literal representation
of it. For example, here are some literals:
100
98.6
X
This is a test
Left to right, the first literal specifies an integer, the next is a
floating-point value, the third is a character constant, and the last is
a string. A literal can be used anywhere a value of its type is
allowed.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Variables
Variable is the basic unit of defined by the combination of an
identifier, a type, and an optional initializer. In addition, all
variables have a scope, which defines their visibility and lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The
basic form of a variable declaration is as below:
type identifier [ = value][, identifier [= value] ...] ;
type is one of Javas atomic types, or the name of a class or
interface.
identifier is the name of the variable. You can initialize the variable
by specifying an equal sign and a value.
Note: the initialization expression must result in a value of the
same (or compatible) type as that specified for the variable.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI6
Variables (contd.)
To declare more than one variable of the specified type, use a
comma-separated list.
Example: int a, b, c=1;
byte z=22; char x=a;
Dynamic Initializations: Java also allows dynamic variable
initializations, using any expression valid at the time the
variable
i bl is
i declared.
d l d
Example: double c = Math. sqrt (a * a + b * b);
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
integral
boolean
reference
floating point
float
array interface
class
double
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI7
Variables (contd.)
Type Conversion
Automatic Type Conversion/
Wid i Conversion
Widening
C
i
Ex: int to long
Narrowing Conversion/ Type Casting
Ex: byte to int
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Operators
Java provides a rich set of operators, which can be categorized
into the following four groups:
CATEGORY
Arithmetic
Bitwise
Relational
Boolean
Logical
OPERATORS
+, -, *, /,%, ++, --, +=, -=, *=, /=, %=
~, &, |, ^, >>, <<, >>>, &=, |=, ^=,>>=,
>>>=,, <<=
==, !=, >, <, >=, <=
&, |,^, ||,&&,!, &=, |=,^=,==,!=,?=
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Short-Circuit Evaluation
int age, height;
age = 25;
height = 70;
EXPRESSION
(age > 50) && (height > 60)
false
Evaluation can stop now because result of && is only true
when both sides are true. It is already determined that the
entire expression will be false.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI8
Expressions
Operators, variables, and literals are the constituents of
expressions. An expression in Java is any valid combination of
above pieces.
Within an expression, it is possible to mix two or more different
types of data as long as they are compatible with each other.
When different types of data are mixed within an expression,
they are all converted to the same type. This is accomplished
through the use of Javas type promotion rules.
// A promotion surprise!
class PromDemo { public static void main(String args[]) {
byte b; int i;
b = 10; i = b * b;
b = 10; b = (byte) (b * b); // cast needed!!
System.out.println("i and b: " + i + " " + b); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Control Structures
Programming language uses control statements to cause the
flow of execution to advance and branch based on changes to the
state of a program.
Javas program control statements can be put into the following
categories: selection, iteration, and jump.
Selection statements allow your program to choose different
paths
th off execution
ti based
b d upon th
the outcome
t
off an expression
i or
the state of a variable. Ex: if, if-else, switch.
Iteration statements enable program execution to repeat one or
more statements (that is, iteration statements form loops). Ex:
for,while and do-while.
Jump statements allow your program to execute in a nonlinear
fashion. Ex: goto, continue and break
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Switch example
// A simple example of the switch.
public class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System out println("ii is zero.
System.out.println(
zero ");
);
break;
case 1:
System.out.println("i is one.");
break;
}}
What is the output?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI9
while example
// Predict the output.
class While
{
public static void main(String args[])
{
int n = 10;;
while(n > 0)
{
System.out.println("tick " + n); n--; }
}
}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
while variant
The body of the while (or any other of Javas loops) can be
empty. This is because a null statement (one that consists
only of a semicolon) is syntactically valid in Java. For
example, consider the following program:
// The target of a loop can be empty.
Guess the output?
class NoBodyy {
public static void main(String args[])
{
int i, j;
i = 100; j = 200;
while (++i < --j) ;
System.out.println ("Midpoint is " + i);
}
}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
do-while (Contd.)
Each iteration of the do-while loop first executes the body of
the loop and then evaluates the conditional expression. If this
expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Javas loops,
condition must be a Boolean expression.
// Demonstrate the do
do-while
while loop.
loop
class DoWhile { public static void main(String args[]) {
int n = 10;
do { System.out.println ("tick " + n);
n--; } while(n > 0); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI10
for
// Demonstrate the for loop.
class ForTick { public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n); }}
// Declare a loop control variable inside the for.
class ForTick {public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n); }}
Q. Identify the difference between the two codes above?
Q. Will both the codes produce the same output?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
For-each
The basic for loop was extended in Java 5 to make iteration over
arrays and other collections more convenient.
This newer for statement is called the enhanced for or for-each.
The for-each loop is used to access each successive value in a
collection of values.
y or a Collections class
It's commonlyy used to iterate over an array
(eg, ArrayList).
For-each loop
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI11
Try for-each
Write the for-each equivalent of the loop below:
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (int i = 0; i < ar.length; i++)
{ // i indexes each element successively.
y
sum += ar[i]; }
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Jump statements
Java supports three jump statements: break, continue, and
return. These statements transfer control to another part of your
program.
The break statement has three uses. First, it terminates a
statement sequence in a switch statement.
Second, it can be used to exit a loop.
Third,
Third it can be used
sed as a ci
civilized
ili ed form of goto.
goto
// Using break to exit a loop.
class BreakLoop {public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);}
System.out.println("Loop complete.");}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
break
// Using break to exit a while loop.
class BreakLoop2 {public static void main (String args[])
{ int i = 0;
while (i < 100) { if (i == 10) break; // terminate loop if i is 10
System.out.println ("i: " + i);i++;}
System.out.println ("Loop complete.");}}
When used inside a set of nested loops, the break statement
will only break out of the innermost loop. For example:
Q. Modify the code below to terminate the loop if j=10?
class BreakLoop3 {public static void main(String args[])
{ for (int i=0; i<3; i++) {System.out.print ("Pass " + i + ": ");
for (int j=0; j<100; j++) { if (j == 10)
System.out.print (j + " ");} System.out.println();}
System.out.println ("Loops complete.");}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI12
break
// Using break as a civilized form of goto.
class Break {public static void main (String args[]) {
boolean t = true;
first: { second: {third: {
System.out.println ("Before the break.");
if (t) break second; // break out of second block
S
System.out.println
i l ("This
(" hi won't' execute");}
") }
System.out.println ("This won't execute");}
System.out.println ("This is after second block.");}}}
Q. Note the difference in the code above?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Using continue
U1.
#
continue
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
y
p
();
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println(); }}
Q. Predict the output?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI13
return
return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller
of the method.
// Demonstrate return.
class Return {public static void main (String args[]) {
boolean t = true;
System.out.println ("Before the return.");
if (t) return; // return to caller
System.out.println ("This won't execute.");}}
Q. In above code return returns execution to whom?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
JAVA Platform
has two components:
The Java Virtual Machine
The Java Application Programming Interface (API)
Java Platform
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI14
JAVAS Bytecode
Bytecode is a highly optimized set of instructions designed to be
executed by the Java run-time system, called the Java Virtual
Machine (JVM). It is the key behind Javas security and
portability.
JVM is actually an interpreter for bytecode, helping solve
problems associated with downloading programs.
Translating Java program to bytecode makes it much easier to
run the program in a wide variety of environments as only the
JVM needs to be implemented for each platform, thus creating a
truly portable program.
Java provides on-the-fly compilation of bytecode, into native
code by the use of the Just-In-Time compiler provided by Java2
release.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI15
JAVAS Architecture
U1.
#
U1.
#
JAVA API
The Java API helps make Java suitable for networks through its
support for platform independence and security.
The Java API is set of runtime libraries that give you a standard
way to access the system resources of a host computer.
When you write a Java program, you assume the class files of the
Java API will be available at any Java Virtual Machine that may
ever have
h
th
the privilege
i il
off running
i your program. This
Thi is
i a safe
f
assumption because the Java Virtual Machine and the class files for
the Java API are the required components of any implementation
of the Java Platform.
The combination of all loaded class files (from your program and
from the Java API) and any loaded dynamic libraries (containing
native methods) constitute the full program executed by the Java
Virtual Machine.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI16
JVM
At the heart of Javas network-orientation is the Java Virtual Machine,
which supports: platform independence, security, and networkmobility.
The Java Virtual Machine is an abstract computer.
A Java Virtual Machines main job is to load class files and execute
the bytecodes they contain.
Only
O l those
h
class
l files
fil from
f
the
h Java
J
API that
h are actually
ll needed
d d by
b a
running program are loaded into the virtual machine.
The bytecodes are executed in an execution engine, which is one part
of the virtual machine that can vary in different implementations.
Execution Engine
Interpreter
Just In Time
Compiler (JIT)
Embedded
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Introduction to JVM
JVM is a component of the Java system that interprets and
executes the instructions in our class files.
The following figure shows a block diagram of the JVM that
includes its major subsystems and memory areas.
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI17
u2
u4
u8
Name
Count
u4
magic
u2
minor_version
u2
major_version
u2
constant_pool_count
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Name
Count
cp_info
constant_pool
constant_pool_count-1
u2
access_flags
u2
this_class
u2
super_class
u2
interfaces_count
u2
2
i t f
interfaces
i t f
interfaces_count
t
u2
fields_count
field_info
fields
fields_count
u2
methods_count
method_info
methods
methods_count
u2
attributes_count
attribute_info
attributes
attributes_count
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI18
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
BCEL (Contd.)
Classes are represented by objects which contain all the
symbolic information of the given class: methods, fields and
byte code instructions, in particular.
Objects can be read from an existing file, be transformed by a
program (e.g. a class loader at run-time) and dumped to a file
again.
BCEL is already being used successfully in several projects
such as compilers, optimizers, obsfuscators, bytecode verifiers
and analysis tools, the most popular probably being the Xalan
XSLT compiler at Apache.
Note: The BCEL Library is written entirely in Java.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Uses of BCEL
BCEL provides a simple library that exposes the internal aggregate
components of a given Java class through its API as object constructs
(as opposed to the disassembly of the lower-level opcodes).
The BCEL library has been used in several diverse applications, such
as:
i. Java Bytecode Decompiling, Obfuscation, and Refactoring
ii Performance and Profiling
ii.
iii. Instrumentation calls that capture performance metrics can be
injected into Java class binaries to examine memory/coverage data.
(For example, injecting instrumentation at entry/exit points.)
iv. Implementation of New Language Semantics
v. Static code analysis
vi. FindBugs uses BCEL to analyze Java bytecode for code idioms
to indicate bugs
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI19
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI20
Loading
A class loader is a subclass of the class java.lang.ClassLoader.
The load phase starts in a method called loadClass of the
ClassLoader , but it's abstract, so it has no implementation.
Subclasses of ClassLoader must provide an implementation. The
descriptor of loadClass is:
Class loadClass(String name, boolean resolve);
where
h name represents
t the
th name off the
th class
l that
th t loadClass
l dCl is
i to
t
load. The name will be fully qualified (that is, it might be
java.lang.Object, not Object), and it will contain periods (.), not
slashes (/), to separate package components. The parameter
resolve tells loadClass whether or not to proceed to the linking
stage.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Linking
Class must be linked before it can be used. During linking, the class is verified
to make sure it meets certain criteria, and initialization takes place.
Linkage happens in ClassLoader final method called resolveClass (), which is
called at the end of loadClass() to resolve the class (when the resolve argument
is true). Before linking a class, its superclass must be linked, and so on.
resolveClass() first does verification. JVM ensures that class obey certain rules:
i. All the methods required by the interfaces are implemented.
ii The
ii.
Th iinstructions
t ti
use constant
t t pooll references
f
correctly.
tl
iii. The methods don't overflow the stack.
iv. The methods don't try to use an int as a reference.
v. Once the class is successfully verified, the class is initialized.
Finally, the virtual machine invokes the <clinit> method of the class. <clinit> is
where the Java compiler places all the code that appears outside any method
including field initializers and code marked static. On <clinit> termination, the
class is ready.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Since the inception of Java technology, there was strong and growing
interest around the security of the Java platform
Java security includes two aspects:
i) Provide the Java platform as a secure, ready-built platform on which to
run Java-enabled applications in a secure fashion.
ii) Provide security tools and services implemented in the Java
programming
i language.
l
Original security model provided by the Java platform is known as the
sandbox model, in order to provide a very restricted environment in
which to run untrusted code obtained from the open network.
The essence of the model is that local code is trusted to have full
access to vital system resources (such as the file system) while
downloaded remote code (an applet) is not trusted and can access only
the limited resources inside the sandbox.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI21
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI22
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Exercise
Q. using arrays find out the highest number inputted by a user out of
three numbers entered by him.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Multi-Dimensional Arrays
Multidimensional arrays are actually arrays of arrays. They, look
and act like regular multidimensional arrays.
To declare a multidimensional array variable, specify each
additional index using another set of square brackets.
For example, the following declares a two-dimensional array
variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD.
Internally this matrix is implemented as an array of arrays of int.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI23
Conceptual view
Right-Index determines columns
Left-Index
determines
rows
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Exercise
Write a program using 2-D arrays to obtain the following output:
1
12
123
1234
12345
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
STRING ARRAYS
Like arrays of primitive types, Java also allows the creation of
arrays of String type. For Ex:
static String[] r={red",white",blue",green",black};
Q. Write a program to display elements of the above array?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI24
Exercise
Q. Create a class called test to have two integer type two-dimensional
arrays. Write a function to perform addition of the two arrays,
multiplication and then print the result?
Q. Modify the above program to sort array elements input by the
user?
Q. Create a program to copy contents of one array into another
using the following method from System class?
public static void arraycopy(Object src, int srcPos, Object dest, int
destPos, int length)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Class-Introduction
Class is at the core of Java. It is the logical construct upon which
the entire Java language is built because it defines the shape and
nature of an object.
Class construct forms the basis for object-oriented programming in
Java. Any concept you wish to implement in a Java program must
be encapsulated within a class.
A class is a template for an object, and an object is an instance of a
class.
class classname { type instance-variable1;
// ...
type instance-variableN;
type methodname1(parameter-list) { // body of method }
// ...
type methodnameN(parameter-list) {// body of method }}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
Most important point here is that a class defines a new data type
that can be used to create objects of that type.
Circle
centre
radius
circumference()
area()
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI25
Declaring Objects
Obtaining objects of a class is a two-step process:
i) declare a variable of the class type(refers to an object).
ii) acquire an actual physical copy of the object and assign it to that
variable using new operator.
In Java all class objects must be dynamically allocated:
Ex: Box mybox=new Box();
OR
Box mybox;
mybox= new Box();
A constructor defines what occurs when an object of a class is
created.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Declaring Objects
Circle aCircle;
null
Circle bCircle;
null
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI26
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
Before Assignment
aCircle
After Assignment
bCircle
aCircle
bCircle
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Methods
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI27
Constructors
Initializing all variables of a class everytime an instance is
created can be tedious.
Constructors initialize an object immediately upon creation.
A constructor has the same name as the class in which it resides
and is syntactically similar to a method.
Once defined,
defined a constructor is automatically called immediately
after the object is created, before new completes.
Constructors have no return type as their implicit return type is
the class type.
Constructors initialize the internal state of an object, hence code
creating an instance will have a fully initialized usable object
immediately.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Constructor Types
Parameterized
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
this keyword
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI28
U1.
#
Garbage Collection
Objects are dynamically allocated using the new operator. To
destroy such objects and release their memory for later
reallocation java handles this deallocation automatically through
garbage collection.
Garbage Collection works like this: when no references to an
object exist, the object is assumed to be no longer needed, and the
memoryy occupied
p can be reclaimed. Garbage
g collection occurs
sporadically. Thus one does not have to worry about this while
writing programs.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
finalize()
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI29
Exercise
Create a class called time with data members hours,min and sec.
Add members functions to initialise these data members. Add a
function that converts hours, min and sec into sec and returns the
same?
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Method Overloading
In Java, two or more methods within the same class that share
the same name, but have different method declarations are
allowed.
This is known as method overloading. It is one of the ways
Java implements polymorphism.
On invoking an overloaded method, Java uses the type and/or
number of arguments to determine which version of the
method to actually call.
Overloaded methods have different return types, however
return type alone is insufficient to distinguish between two
versions of a method, hence overloaded methods must differ in
type and/or number of their parameters.
Method Overloading supports polymorphism as it is one way
Java implements the one interface, multiple methods
paradigm.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI30
Method Overloading
Automatic type conversions also apply to overloading. Hence as
the previous example does not define any version of test(int )
therefore, when test(int) is called, no matching method is found.
However, Java automatically converts an integer into a double,
and this conversion can be further used to resolve the call.
Hence Java calls test(double).
Value of overloading is that it allows related methods to be
accessed by use of a common name.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Constructor Overloading
Like methods constructors can also be overloaded. Complete
the code below to initialize three Box objects using the
overloaded constructors?
Ex: class Box{ double width, height, depth;
Box(double w,double h,double d)
{width=w height=h depth=d;}
{width=w,height=h,depth=d;}
Box(){width=height=depth=-1;}
Double volume(){return width*height*depth;}}
class BoxDemo{public static void main(String args []){
double vol;
vol=mybox1.volume();
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI31
Argument Passing
Call by Value
Copies the value of an argument into the formal parameter of
subroutines. Changes made to the parameter of the subroutine
have no effect on the argument.
Call by reference
A reference to an argument is passed to the parameter. Inside the
subroutine,
b ti this
thi reference
f
is
i usedd to
t access the
th actual
t l argumentt
specified in the call. Hence changes made to the parameter will
affect the argument used to call the subroutine
When a simple type is passed to a method, it is done by use of
call-by-value. Objects are passed by use of call-by-reference.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Argument PassingExample
class Test{ void meth(int i, intj) {i*=2; j/=2; }}
class callbyvalue {{ Test ob=new test(); int a=15,b=20;
System.out.println(a and b before call: +a+ +b); ob.meth(a,b);
System.out.println (a and b after call: +a+ +b);}}
Q. Point out the difference?
class Test{ int a,b; Test (int i,int j) {a=I; b=j;}
void meth (Test o) {o.a*=2; o.b/=2;}}
class callbyref{public static void main (String args[]){Test ob=new
Test(15,20); System.out.println (ob.a and ob.b before call:+ob.a+
+ob.b); ob.meth(ob); System.out.println (ob.a and ob.b after
call:+ob.a+ +ob.b);}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Returning Objects
A method can also return any type of data, including class types
that one can create.
Ex: class Test{ int a;Test(int i){a=I;}
Test incrByTen(){Test temp=new Test(a+10);
return temp;}}
class RetOb{
public static void main(String args[]){
Test ob1=new Test();
Test ob2;
ob2=ob1.incrByTen(); ob2=ob2.incrByTen();
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI32
Recursion
Is the process of defining something in terms of itself.
Example: class Factorial{ int fact(int n){int result; if (n==1) return 1;
result=fact(n-1)*n;return result;}}
class Recursion{ public static void main(String args[]){ Factorial f=new
Factorial();
System.out.println(Factorial of 3 is+f.fact (3)); }}
A recursive call does not make a new copy of the method. Only the
arguments are new. As eachh recursive
i call
ll returns , the
h old
ld local
l l variables
i bl andd
parameters are removed from the stack, and execution resumes at the point of
the call inside the method.
Recursive versions of many routines may execute a bit more slowly than the
iterative equivalent due to the added overhead of the additional function calls.
Many recursive calls to the same method may result in a stack overrun as with
each new call a new copy of variables is created.
Advantage: Can be used to create clearer and simpler versions of several
algorithms
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
Access Control
Encapsulation links data with code that manipulates it. It also provides
another important attribute: access control i.e. what parts of a program can
access the members of a class in order to prevent misuse.
How a class member can be accessed is determined by the access
specifier ,that modifies its declaration. Java specifies three access
specifiers:public, private and protected. Java also defines a default access
level and protected applies only when inheritance is involved.
Situation
public
protected
default
Accessible to class
from same package?
yes
yes
yes
Accessible to class
from different
package?
yes
No,
No
unless it is
a subclass
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
privat
e
No
No
U1.
#
static
static allows a class member that can be used independently of any instance
of a class. A static member can be accessed before any objects of its class
are created, and without a particular reference to any object.
Both methods and variables can be declared static. Instance variables
declared static are essentially global variables. Thus when objects of a class
are created no copy of a static variable is made.
Methods declared as static have several restrictions:
i. They can only call other static methods
ii. They must only access static data.
iii. They cannot refer to this or super in any way.
A static block is only executed once when the class is first loaded
Example: class staticuse { static int a=5; static int b;
static void meth( int x){System.out.println(X=+x);
System.out.println(a=+a); System.out.println(b=+b);}
static{System.out.println(Static block initialized.);b=a*4;}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI33
final
By declaring a variable as final, prevents its contents from
being modified. That is, contents of a final variable should be
initialized when it is declared(Similar to const in C/C++)
EX: final int FILE_NEW=1;
All parts of your program can use FILE_NEW as if it were
constant without
ih
any fear
f off its
i value
l being
b i modified.
difi d
Keyword final can also be applied to methods but its meaning
differs from that when applied to variables. This usage of final
is generally used with inheritance
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
100 #
U1.
101 #
Inheritance
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI34
Example
class A {int i, j;
void showij() { System.out.println("i and j: " + i + " " + j); }}
class B extends A { int k;
void showk() {System.out.println("k: " + k);}
void sum() {System.out.println("i+j+k: " + (i+j+k)); }}
class SimpleInheritance {
public static void main(String args[]) { A superOb = new A();
B subOb = new B();
superOb.i = 10; superOb.j = 20; // The superclass may be used by itself.
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk(); System.out.println();
System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI35
Using super
i)
ii)
At times one would create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members
private). In this case, there would be no way for a subclass to
directly access or initialize these variables on its own.
Since encapsulation is a primary attribute of OOP, Java provides a
solution to this problem. Whenever a subclass needs to refer to its
immediate superclass,
p
, it can do so byy use of the keyword
y
super.
p
super has two general forms:
calls the superclass constructor.
to access a member of the superclass that has been hidden by a
member of a subclass.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI36
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Method Overriding
In a class hierarchy, when a method in subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass.
When an overridden method is called from within a subclass, it
will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass
will be hidden.
class A { int i, j; A(int a, int b) { i = a; j = b; }
void show(){System.out.println("i and j: " + i + " " + j);}}
class B extends A {int k;
B(int a, int b, int c) {super(a, b); k = c; }
void show() { System.out.println("k: " + k); }}
class Override { public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI37
Abstract Classes
When we define a class to be final, it cannot be extended. In
certain situations, we want properties of classes to be always
extended and used. Such classes are called Abstract Classes.
An Abstract class is a conceptual class.
An Abstract class cannot be instantiated objects cannot be
created.
Abstract classes provides a common root for a group of classes,
nicely tied together in a package.
package Synatx:
abstract class ClassName
{
...
abstract Type MethodName1();
Type Method2()
{
// method body
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Shape
Circle
Rectangle
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI38
final
The keyword final has three uses.
It can be used to create the equivalent of a named constant.
It can be used to prevent overriding
To disallow a method from being overridden, specify final as a
modifier at the start of its declaration. Ex:
class A{final
{
void meth()
() {{System.out.println("This
y
p
(
is a final
method."); }}
class B extends A { void meth() { System.out.println("Illegal!"); }}
It can be used to prevent inheritance.
final class A { // ... }
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Object Class
Object, is a special class defined by Java. All other classes are
subclasses of Object. This means that a reference variable of type
Object can refer to an object of any other class.
Since arrays are implemented as classes, a variable of type Object can
also refer to any array.
Method
Purpose
Object clone()
void finalize ()
Class getClass()
int hashCode()
void notify()
void notifyAll()
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Class
Like many other programming languages in Java a String is a
sequence of characters. But, unlike many other languages that
implement strings as character arrays, Java implements strings as
objects of type String.
Implementing strings as built-in objects allows Java to provide a
full complement of features that make string handling convenient.
For example, Java has methods to compare two strings, search for
a substring, concatenate two strings, and change the case of letters
within a string.
Also, String objects can be constructed a number of ways, making
it easy to obtain a string when needed.
Creating a String object, one actually creates a string that is
immutable. That is, once a String object has been created, you
cannot change the characters that comprise that string.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI39
StringBuffer Class
This may seem to be a serious restriction. However, it is not the
case. One can still perform all types of string operations. The
difference is that each time you need an altered version of an
existing string, a new String object is created that contains the
modifications. The original string is left unchanged and becomes
unreferenced.
This approach is used because fixed, immutable strings can be
p
more efficiently
y than changeable
g
ones.
implemented
For those cases in which a modifiable string is desired, there is a
companion class to String called StringBuffer, whose objects
contain strings that can be modified after they are created.
Both the String and StringBuffer classes are defined in
java.lang. Thus, they are available to all programs automatically.
Both are declared final, which means that neither of these
classes may be subclassed. This allows certain optimizations that
increase performance to take place on common string operations.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Constructors
The String class supports several constructors. To create an
empty String, you call the default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
Frequently, you will want to create strings that have initial values.
The String class provides a variety of constructors to handle this. To
create a String
St i iinitialized
iti li d by
b an array off characters,
h
use the
h
constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string abc.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Constructors
One can specify a subrange of a character array as an initializer
using the following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange
begins, and numChars specifies the number of characters to use.
Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
You can construct a String object that contains the same
character sequence as another String object using this
constructor:
String(String strObj)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI40
Example
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Constructors
Even though Javas char type uses 16 bits to represent the
Unicode character set, the typical format for strings on the
Internet uses arrays of 8-bit bytes constructed from the ASCII
character set.
Because 8-bit ASCII strings are common, the String class
provides constructors that initialize a string when given a
byte array. Their forms are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Extended versions of the byte-to-string constructors are also
defined in which you can specify the character encoding that
determines how bytes are converted to characters.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Length
The length of a string is the number of characters that it
contains. To obtain this value, call the length( ) method,
shown below:
int length( )
The following fragment prints 3, since there are three
characters in the stringg s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI41
U1.
#
U1.
#
Character Extraction
The String class provides a number of ways in which characters can
be extracted from a String object.
The characters that comprise a string within a String object cannot be
indexed as if they were a character array, many of the String methods
employ an index (or offset) into the string for their operation. Like
arrays, the string indexes begin at zero.
To extract a single character from a String, you can refer directly to
an individual character via the charAt( ) method. It has this
general form: char charAt(int where)
where is the index of the character that you want to obtain. The value
of where must be nonnegative and specify a location within the string.
charAt( ) returns the character at the specified location. For ex,
char ch; ch = "abc".charAt(1);
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI42
Character Extraction
getChars( )
To extract more than one character at a time, use the getChars( )
method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
Here, sourceStart specifies the index of the beginning of the
substring and sourceEnd specifies an index that is one past the
substring,
end of the desired substring. Thus, the substring contains the
characters from sourceStart through sourceEnd1.
The array that will receive the characters is specified by target.
The index within target at which the substring will be copied is
passed in targetStart. Care must be taken to assure that the
target array is large enough to hold the number of characters in
the specified substring.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Character Extraction
getBytes( )
There is an alternative to getChars( ) that stores the characters
in an array of bytes. This method is called getBytes( ), and it
uses the default character-to-byte conversions provided by the
platform. Here is its simplest form:
byte[ ] getBytes( )
toCharArray(
toCharArra ( )
To convert all the characters in a String object into a character
array, the easiest way is to call toCharArray( ). It returns an
array of characters for the entire string. It has this general
form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to
use getChars( ) to achieve the same result.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
String Comparison
The String class includes several methods that compare
strings or substrings within strings.
equals( ) and equalsIgnoreCase( )
boolean equals(Object str)
boolean equalsIgnoreCase(String str)
regionMatches( )
g
( startIndex, Stringg str2, int
boolean regionMatches(int
str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex,
String str2, int str2StartIndex, int numChars)
startsWith( ) and endsWith( )
boolean startsWith(String str)
boolean endsWith(String str)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI43
String Comparison
equals( ) Versus ==
the equals( ) method compares the characters inside a String
object. The == operator compares two object references to
see whether they refer to the same instance.
Example:
class EqualsNotEqualTo {public static void main(String args[])
{String s1 = "Hello"; String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
compareTo( )
For sorting applications, one needs to know which String is less
than, equal to, or greater than the next. A string is less than
another if it comes before the other in dictionary order. A string
is greater than another if it comes after the other in dictionary
order.
The method compareTo( ) serves this purpose. It has this
general form:nt compareTo(String str)
int compareToIgnoreCase(String str)
Value
Method
Zero
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Searching Strings
The String class provides two methods that allow you to
search a string for a specified character or substring:
indexOf( ) Searches for the first occurrence of a character or
substring.
lastIndexOf( ) Searches for the last occurrence of a character
or substring.
These two
t o methods are ooverloaded
erloaded in se
several
eral different ways.
a s In
all cases, the methods return the index at which the character or
substring was found, or 1 on failure.
Modifying a String
String objects are immutable, whenever you want to modify
a String, you must either copy it into a StringBuffer or use one
of the following String methods, which will construct a new
copy of the string with your modifications complete.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI44
String Modifications
substring( ): You can extract a substring using substring( ). It has
two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin.
This form returns a copy that begins at startIndex and runs to end of
invoking string.
The second form of substring( ) allows you to specify both the
beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
concat( ): You can concatenate two strings using concat( ), shown
here: String concat(String str)
This method creates a new object that contains the invoking string
with the contents of str appended to the end. concat( ) performs the
same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
StringBuffer
A peer class of String that provides much of the functionality
of strings.
String represents fixed-length, immutable character
sequences. In contrast, StringBuffer represents growable
and writeable character sequences, as it may have characters
and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such
additions and often has more characters preallocated than are
actually needed, to allow room for growth.
Java uses both classes heavily, but many programmers deal only
with String and let Java manipulate StringBuffers behind the
scenes by using the overloaded + operator.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI45
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
length( ) and capacity( )
The
Th currentt length
l th off a StringBuffer
St i B ff can be
b found
f
d via
i the
th
length( ) method, while the total allocated capacity can be
found through the capacity( ) method. They have the following
general forms:
int length( )
int capacity( )
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
StringBuffer reverse( )
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
StringBuffer replace(int startIndex, int endIndex, String str)
String substring(int startIndex)
String substring(int startIndex, int endIndex)
Many other StringBuffer methods were added by Java2
ver1.4
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI46
Java uses simple types, such as int and char, for performance
reasons. These data types are not part of the object hierarchy. They are
passed by value to methods and cannot be directly passed by
reference.
Also, there is no way for two methods to refer to the same instance of
an int.
At ti
times, you will
ill needd to
t create
t an object
bj t representation
t ti for
f one off
these simple types.
In order to make primitive types act like objects, Java offers wrapper
classes
A wrapper class is an object that stores one item, a primitive
There is a wrapper class for all 8 of the primitive types
In essence, these classes encapsulate, or wrap, the simple types within
a class. Thus, they are commonly referred to as type wrappers.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Number
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI47
MIN_VALUE
NaN
Not a Number
POSITIVE_INFINITY
Positive Infinity
NEGATIVE_INFINITY
Negative Infinity
TYPE
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI48
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Several different methods are also defined by Byte, Short, Integer and
Long.
Example:
g into binary,
y, hexadecimal,, and octal.
//Convert an integer
class StringConversions { public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " + Integer.toBinaryString(num));
System.out.println(num + " in octal: " + Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " +
Integer.toHexString(num));}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Character
MIN_RADIX
MAX_VALUE
MIN_VALUE
TYPE
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI49
Character
U1.
#
Boolean
Boolean is a very thin wrapper around boolean values,
which is useful mostly when you want to pass a boolean
variable by reference.
It contains the constants TRUE and FALSE, which define
true and false Boolean objects. Boolean also defines the
TYPE field, which is the Class object for boolean. Boolean
d fi
defines
th
these constructors:
t t
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false. In
the second version, if boolString contains the string true (in
uppercase or lowercase), then the new Boolean object will be
true. Otherwise, it will be false.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Boolean
Boolean defines the methods
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI50
Packages
Packages are containers for classes that are used to keep the class
namespace compartmentalized.
For example, a package allows you to create a class named List, which
you can store in your own package without concern that it will
collide with some other class named List stored elsewhere.
Packages are stored in a hierarchical manner and are explicitly
imported
p
into new class definitions.
Packages and interfaces are two of the basic components of a Java
program. In general, a Java source file can contain any (or all) of the
following four internal parts:
A single package statement (optional)
Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package (optional)
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Packages
Until now, the name of each example class was taken from the same
name space. This means that a unique name had to be used for each
class to avoid name collisions. As a result without some way to
manage the name space, you could run out of convenient, descriptive
names for individual classes. One also needs some way to be assured
that the name you choose for a class will be reasonably unique and
not collide with class names chosen by other programmers.
Thankfully, Java provides a mechanism for partitioning the class
name space into more manageable chunks. This mechanism is the
package.
The package is both a naming and a visibility control mechanism.
You can define classes inside a package that are not accessible by
code outside that package. You can also define class members that are
only exposed to other members of the same package. This allows
your classes to have intimate knowledge of each other, but not expose
that knowledge to the rest of the world.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Defining a Package
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI51
Storing Packages
Java uses file system directories to store packages. For example,
the .class files for any classes you declare to be part of
MyPackage must be stored in a directory called
MyPackage. Remember that case is significant, and the
directory name must match the package name exactly.
More than one file can include the same package statement.
Th package
The
k
statement
t t
t simply
i l specifies
ifi to
t which
hi h package
k
the
th
classes defined in a file belong. It does not exclude other classes
in other files from being part of that same package.
You can create a hierarchy of packages. To do so, simply
separate each package name from the one above it by use of a
period. The general form of a multileveled package statement is
shown here:
package pkg1[.pkg2[.pkg3]];
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Classpath
The full path to the classes directory, <path_two>\classes, is called
the class path, and is set with the CLASSPATH system variable.
Both the compiler and the JVM construct the path to your .class files
by adding the package name to the class path. For example, if
<path_two>\classes is your class path, and the package name is
com.example.graphics, then the compiler and JVM look for .class
files in <path_two>\classes\com\example\graphics.
<path two>\classes\com\example\graphics
A class path may include several paths, separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM
search the current directory and the JAR file containing the Java
platform classes so that these directories are automatically in your
class path.
To set the CLASSPATH variable, use these commands (for example):
In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI52
U1.
#
main1.java
package main;
import main.main1;
public class main1
{int n=1;
private int n_pri =20;
ppublic int n_pub=40;
_p
protected int n_pro=30;
public main1()
{System.out.println("Base Constructor:");
System.out.println("Value of private member:"+n_pri);
System.out.println("Value of public member:"+n_pub);
System.out.println("Value f protected member:"+n_pro);
System.out.println("Value of member without specifier:"+n); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
samepackage.java
package main;
public class samepackage
{ public samepackage()
{main1 m= new main1();
System.out.println("Same Package Constructor:");
//class only
//System.out.println("Value of private member:"+m.n_pri);
System.out.println("Value of public member:"+m.n_pub);
System.out.println("Value f protected member:"+m.n_pro);
System.out.println("Value of member without specifier:"+m.n);
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI53
subclass.java
package main;
public class subclass extends main1{
public subclass()
{System.out.println("subclass constructor:");
//class only
//System.out.println("Value
//System.out.println(
Value of private member:"+n
member: +n_pri);
pri);
System.out.println("Value of public member:"+n_pub);
System.out.println("Value f protected member:"+n_pro);
System.out.println("Value of member without specifier:" +n);
}}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
demopack.java
//instantiate the various classes in main
package main;
public class demopack{
public static void main(String args[])
{main1 m1= new main1();
subclass m2= new subclass();
samepackage m3= new samepackage(); }}
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI54
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI55
Interfaces
Through the use of the interface keyword, Java allows you
to fully abstract the interface from its implementation. Using
interface, you can specify a set of methods which can be
implemented by one or more classes.
The interface, itself, does not actually define any
implementation. Although they are similar to abstract classes,
interfaces have an additional capability: A class can
implement more than one interface.
Using interface, you can specify what a class must do, but
not how it does it. Interfaces are syntactically similar to
classes, but they lack instance variables, and their methods are
declared without any body.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Defining an Interface
General Form:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2
fi l
2 = value;
l
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;}
access is either public or not used.
Each class that includes an interface must implement all of the
methods.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Defining an Interface
Variables can be declared inside of interface declarations. They are
implicitly final and static, meaning they cannot be changed by
the implementing class. They must also be initialized with a
constant value. All methods and variables are implicitly public if
the interface, itself, is declared as public.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI56
Implementing Interfaces
Once an interface has been defined, one or more classes can
implement that interface.
To implement an interface, include the implements clause in a
class definition, and then create the methods defined by the
interface.
The ggeneral form of a class that includes the implements
p
clause
looks like this:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body}
access is either public or not used.
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, by Ms. Ritika Wason
U1.
#
Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi-63, Ritika Wason
UI57