Unit 1 - 24 Batch Notes - PPSX
Unit 1 - 24 Batch Notes - PPSX
UNIT V
Advantages of GUI over CUI ,The AWT class hierarchy, Introduction to Swings, Swings
Elements:- JComponent, JFrame, user interface components- JLabels, JButton, JScrollbars,
text components, check box, check box groups, choices, lists panels – scrollpane, menubar,
graphics, layout, managers –border, grid, flow, card and grid bag.
Event handling: Delegation event model, closing a Frame, mouse and keyboard events,
Adapter classes.
Applications: developing calculator, developing feedback form, developing bio data.
UNIT VI
Applets – Concepts of Applets, differences between applets and applications, life
cycle of an applet, types of applets, creating applets, passing parameters to applets.
Applications: Developing of simple advertisements.
Networking – Basics of network programming, addresses, ports, sockets, simple
client server program, multiple clients, sending file from server to client.
Applications: One to one Chat application
Text books:
References:
• Core Java 2, Vol 1, Fundamentals, Cay. S. Horstmann and Gary Cornell, seventh
Edition, PearsonEducation.
• Core Java 2, Vol 2, Advanced Features, Cay. S. Horstmann and Gary Cornell,
Seventh Edition, PearsonEducation
UNIT-1
4
UNIT-I
JAVA BASICS
History of Java
Java buzzwords
Data types
Variables
Simple java program
scope and life time of variables
Operators, expressions, control statements
Type conversion and casting
Arrays
Classes and objects – concepts of classes, objects
Constructors, methods
Access control
This keyword
Garbage collection
Overloading methods and constructors
Parameter passing
Recursion
String handling .
5 String Tokenizer
History of Java
Java started out as a research project.
8
Green Team
9
Java Logo
10
Versions of Java
Version Codename Year Features Added
J2SE 1.2 Playground Dec8, 1998 JIT compiler, Collections, IDL & CORBA, strictfp, Java
Plug-in.
J2SE 1.3 Kestrel May8, 2000 HotSpot JVM, JavaSound, Java Naming and Directory
Interface, Java Platform Debugger Architecture.
J2SE 1.4 Merlin Feb6, 2002 Preferences API, Logging API, assert, image I/O API,
security and cryptography extensions.
J2SE 5.0 Tiger Sep30, 2004 Generics, annotations, Autoboxing, Enumerations, Varargs,
Enhanced for each.
JAVA SE 6 Mustang Dec11, 2006 JDBC 4.0, JVM improvements, Improved JAXB, Improved
web services, Support for older Win9x versions dropped.
Major updates to Java
JAVA SE 7 Dolphin July28, 2011
11
JAVA SE 8 - 2012 -
Java Platforms
There are three main platforms for Java:
12
Java Terminology
Java Development Kit:
It contains one (or more) JRE's along with the various
development tools like the Java source compilers, bundling and
deployment tools, debuggers, development libraries, etc.
14
15
Java Development Kit (JDK)
16
classpath and path
17
17
18
19
20
21 21
22 22
Java Execution Procedure
Class Loader Java Class
Java Byte Code
Libraries
Source Verifier
Java
Byte
codes Java Just-in-time
Java
move Interpreter Compiler
Compiler
locally
or
through Run Time System
n/w
Java Java OS W32
Win Solaris
Byte codes
MAC Others
23 Hardware
Java Virtual Machine
Class loader subsystem: A mechanism for loading
types (classes and interfaces) given fully qualified
names.
As the program runs, the virtual machine places all objects the
program instantiates onto the heap.
As each new thread comes into existence, it gets its own pc register
(program counter) and Java stack.
27
Java program Compilation & Execution steps
28
Binary form of a .class file(partial)
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
0000: cafe babe 0000 002e 001a 0a00 0600 0c09 ................
0010: 000d 000e 0800 0f0a 0010 0011 0700 1207 ................
0020: 0013 0100 063c 696e 6974 3e01 0003 2829 .....<init>...()
0030: 5601 0004 436f 6465 0100 046d 6169 6e01 V...Code...main.
0040: 0016 285b 4c6a 6176 612f 6c61 6e67 2f53 ..([Ljava/lang/S
0050: 7472 696e 673b 2956 0c00 0700 0807 0014 tring;)V........
0060: 0c00 1500 1601 000d 4865 6c6c 6f2c 2057 ........Hello, W
0070: 6f72 6c64 2107 0017 0c00 1800 1901 0005 orld!...........
0080: 4865 6c6c 6f01 0010 6a61 7661 2f6c 616e Hello...java/lan
0090: 672f 4f62 6a65 6374 0100 106a 6176 612f g/Object...java/
00a0: 6c61 6e67 2f53 7973 7465 6d01 0003 6f75 lang/System...ou ...
29
Object Oriented Programming Concepts
Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
30
A class is collection of objects of similar type or it is a template.
Ex: fruit mango;
class object
Objects are instances of the type class.
The wrapping up of data and functions into a single unit ( called class) is
known
as encapsulation. Data encapsulation is the most striking features of a class.
Inheritance is the process by which objects of one class acquire the properties
of another class. The concept of inheritance provides the reusability.
31
Polymorphism:
It allows the single method to perform different actions based on the
parameters.
32
Object-Oriented Languages Types
1.Object-based programming language: It supports
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
Disadvantage : They do not support inheritance and dynamic binding
Ex: Ada
33
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use
of existing classes.
The principle of data hiding helps the programmer to build secure programs.
34
Applications of oop
Real-time systems
Object-oriented databases
CAD/CAM systems
35
What is the Difference b/w OO and OB Languages?
In Object based languages inheritance is not supported so
that dynamic polymorphism also not supported.
E.g. VB,VC++.
36
Java is a pure oop or not ?
37
Differences b/w C++ and Java
C++ Java
38
C++ Java
39
Features of Java (Java Buzz Words)
Simple
Object Oriented
Compile, Interpreted and High Performance
Portable
Robust
Secure
Multithreaded
Dynamic
Distributed
Architecture-Neutral
40
Java Features
Simple
No pointers
No Operator Overloading
Automatic garbage collection
Rich pre-defined class library
Object Oriented
Focus on the data (objects) and methods manipulating the data
All methods are associated with objects
Potentially better code organization and reuse
41
Java Features
Compile, Interpreted and High Performance
Java compiler generates byte-code, not native machine
code
The compiled byte-codes are platform-independent
Java byte codes are translated on the fly to machine
readable instructions in runtime (Java Virtual Machine)
Easy to translate directly into native machine code by
using a just-in-time compiler.
Portable
Same application runs on all platforms
The sizes of the primitive data types are always the same
42 The libraries define portable interfaces
Java Features
Robust/Reliable
Extensive compile-time and runtime error checking
No pointers but real arrays. Memory corruptions or
unauthorized memory accesses are impossible
Automatic garbage collection tracks objects usage over
time
Secure
Java’s robustness features makes java secure.
Access restrictions are forced (private, public)
43
Java Features
Multithreaded
It supports multithreaded programming.
Need not wait for the application to finish one task
before beginning another one.
We can write Java programs that deal with many tasks at
once by defining multiple threads.
Dynamic
Libraries can freely add new methods and instance
variables without any effect on their clients
Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
44
Java Features
Distributed
Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols.
Allows objects on two different computers to execute
procedures remotely by using package called Remote
Method Invocation (RMI).
Architecture-Neutral
Goal of java designers is “write once; run anywhere,
any time, forever.”
There is no implementation dependent features e.g. size
of primitive types is fixed.
45
Keywords
abstract continue for new
switch
boolean do if private
this
Boolean
Integer Float Character
char
boolean
float double
51
public class IntDemo{
public static void main(String args[]){
System.out.println(" For an Short");
System.out.println(" For an Integer "); System.out.println("Size is :
System.out.println("Size is : "+Integer.SIZE); "+Short.SIZE);
long l1 = Long.MAX_VALUE;
byte b1 = Byte.MAX_VALUE; long l2 = Long.MIN_VALUE ;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Max value is : "+b1); System.out.println("Min Value is : "+l2);
System.out.println("Min Value is : "+b2);
}
}
52
public class FloatDemo{
public static void main(String args[]){
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
53
public class CharDemo{
public static void main(String args[]){
int f1 = Character.MAX_VALUE;
long f2 = Character.MIN_VALUE ;
Types
Instance Variable
Class Variable
Local Variable
Parameters
55
Local variables :
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block
is entered and the variable will be destroyed once it exits the
method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method,
constructor or block.
• There is no default value for local variables so local variables
should be declared and an initial value should be assigned before
the first use.
56
Instance variables :
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name
inside the class.
• However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName
57
Class/Static variables :
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when
the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName
58
class Variables{
int i;
System.out.println("i value is: "+v1.i);
public int j;
System.out.println("i value is: "+v2.i);
static long l=10; System.out.println("i value is: "+v3.i);
public static float f; System.out.println(“J value is: "+v1.j);
char c; v1.l=20;
boolean b; v2.l=30;
void display(int a){ v3.l=40;
System.out.println("l value is: "+v1.l);
i=a;
System.out.println("l value is: "+v2.l);
System.out.println("i value in display: "+i);
System.out.println("l value is: "+v3.l);
}
public static void main(String args[]){ System.out.println("f value is: "+f);
double d=0.0; System.out.println("c value is: "+v1.c);
//public double d=0.0; invalid System.out.println("b value is: "+v1.b);
Variables v1=new Variables();
System.out.println("d value is: "+d);
Variables v2=new Variables();
}
Variables v3=new Variables(); }
v1.display(100);
v1.i=2;
v2.i=3;
59 v3.i=4;
class Variables{
int i;//instance variable System.out.println("i value is:
public int j ;//instance variable "+v1.i);
static long l=10;//class variable System.out.println("i value is:
public static float f;//class variable "+v2.i);
char c;//instance variable System.out.println("i value is:
"+v3.i);
boolean b;//instance variable
System.out.println(“j value is:
void display(int a){
"+v1.j);
i=a; v1.l=20;
System.out.println("i value in display: v2.l=30;
"+i); v3.l=40;
} System.out.println("l value is:
public static void main(String args[]){ "+v1.l);
double d=0.0;//local variable System.out.println("l value is:
//public double d=0.0; invalid
"+v2.l);
System.out.println("l value is:
Variables v1=new Variables();
"+v3.l);
Variables v2=new Variables();
Variables v3=new Variables(); System.out.println("f value is:
v1.display(100); "+f);
v1.i=2; System.out.println("c value is:
60 v2.i=3; "+v1.c);
System.out.println("b value is:
v3.i=4;
Sample Program
class HelloWorld {
public static void main (String args []) {
System.out.println (“Welcome to Java
Programming…..”);
}
}
}
void display(){
System.out.println("display:main");
}
}
64
The Scope and Lifetime of Variables
Scope
The scope of a declared element is the portion of the program where the
element is visible.
Lifetime
The lifetime of a declared element is the period of time during which it is
alive.
A block begins with an opening curly brace and ends by a closing curly
brace.
65
Variables declared inside a scope are not accessible to code
outside.
Scopes can be nested. The outer scope encloses the inner
scope.
Variables declared in the outer scope are visible to the inner
scope.
Variables declared in the inner scope are not visible to the
outside scope.
66
public class Scope
{
public static void main(String args[]){
int x; //know to all code within main
x=10;
if(x==10){ // starts new scope
int y=20; //Known only to this block
//x and y both known here
System.out.println("x and y: "+x+" "+y);
x=y+2;
}
// y=100; // error ! y not known here
//x is still known here
System.out.println("x is "+x);
}
}
67
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Boolean Logical Operators
68
Arithmetic Operators(1)
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
69
Arithmetic Operators(2)
Operator Result
++ Increment
+= Addition
assignment
–= Subtraction
assignment
*= Multiplication
assignment
/= Division
assignment
%=
70
Modulus assignment
Example:
class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
71
class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
72
Bitwise Operators(1)
bitwise operators can be applied to the integer
types, long, int, short, byte and char.
These operators act upon the individual bits of
their operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
73
Bitwise Operators(2)
Operator Result
|= Bitwise OR
assignment
^= Bitwise exclusive
OR assignment
76
Relational Operators
The relational operators determine the relationship
that one operand has to the other.
They determine equality and ordering.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or
equal to
<= Less than or equal to
77
Example:
78
Boolean Logical Operators(1)
Operator Result
class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
else
System.out.println(“left parameter
failed");
80
}
Boolean Logical Operators(2)
Operator Result
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-
then-else
81
82
public class TernaryOperatorDemo
{
public static void main(String args[])
{
int x=10,y=12;
int z;
z= x > y ? x : y;
System.out.println(“Z=“+z);
}
83
Operator Precedence
84
Expressions
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
85
Control Statements
86
Selection Statements
88
Iteration Statements
while(condition) do
{ {
// body of
loop // body of loop
}
}while (condition);
label:
----
----
break label; //it’s like goto
statement
93
Type Conversion and Casting
Types of Conversions:
1.Widening conversion
2.Narrowing conversion
94
Widening Conversion
Ex: char and boolean are not compatible with each other.
96
class Widening{
public static void main(String args[]){
short s;
int i1,i2;
byte b1=10,b2=20;
s=b1; //byte to short
i1=b2; //byte to int
System.out.println("byte to short conversion");
System.out.println(b1+ " " + s);
System.out.println("byte to int conversion");
System.out.println(b2+" "+i1);
char c='a';
i2=c; //char to int
System.out.println("char to int conversion");
System.out.println(c+" "+i2);
}
}
97
Narrowing Conversion
In general, the narrowing primitive conversion can occur in
these cases:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float
98
public class Narrowing{
public static void main(String args[]){
byte b=2;
int i=257;
double d=323.142;
System.out.println("int to byte conversion");
b= (byte)i; //int to byte
System.out.println("i and b values: "+i+" "+b);
System.out.println("double to int conversion");
i=(int)d; //double to int
System.out.println("d and i values: "+d+" "+i);
System.out.println("double to byte conversion");
b=(byte)d; //double to byte
System.out.println("d and b values: "+d+" "+b);
}
}
99
Arrays
An array is a group of like-typed variables that are
referred to by a common name.
The operator new is used for dynamic memory
allocation.
One-Dimensional Arrays:
type varname[];
varname = new type[size];
type varname[]=new type[size];
Ex: int month[];
Ex: month= new int[12];
Ex: int varname[]=new int[size];
10
0
Multidimensional Arrays
int twoD[][]=new int[4][5];
10
1
If month is a reference to an array, month. length will
give you the length of the array.
Initialization:
int x[] = {1, 2, 3, 4};
char []c = {‘a’, ‘b’, ‘c’};
double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
Jagged Array:
10
2
import java.util.Scanner;
class ArrayEx{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int a[]={10,20,30,40,50};
char []c={'a','b','c','d','e'};
int b[]=new int[5];
for(int i=0;i<5;i++){
System.out.print(a[i]+" ");
System.out.println(c[i]+" ");
}
System.out.println("Enter the Integer elements into array :")
for(int i=0;i<5;i++){
b[i]=input.nextInt();
}
System.out.println("The Integer elements in array are :");
for(int i=0;i<5;i++){
System.out.print(b[i]+" ");
10 }
3
foreach syntax
for(data_type variable : array | collection)
{}
class ForEachExample
{
public static void main(String args[])
{
int arr[]={1,2,3,4,5};
for(int i:arr) {
System.out.println(i);
}
}
}
Concepts of Classes, Objects
10
5
General Form of Class
class classname {
type instance-variable1;
//...
type instance-variableN;
static type variable1;
type methodname1(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list){
// body of method
}
}
10
6
class Box{ Declaring an Object
double width;
double height;
double depth;
}
Representation 1:
Box mybox;
mybox=new Box();
Representation 2:
Box mybox=new
Box();
110
A constructor is a special member function whose task is to 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.
default :
When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.
private:
A private member is accessible only to the class in which it is
defined.
Use private keyword to create private members.
117
public:
Any class, in any package has access to a class's public
members.
To declare a public member, use the keyword public.
protected:
Allows the class itself, subclasses, and all classes in the same
package to access the members.
To declare a protected member, use the keyword protected.
118
//Example for access control
class AccessTest {
class Test {
int a; // default public static void main(String args[]) {
access
public int b; // public Test ob = new Test();
access
// These are OK, a and b may be accessed directly
private int c; // private ob.a = 10;
access ob.b = 20;
/*protected applies only
when inheritance is involved*/ // This is not OK and will cause an error
//ob.c = 100; // Error!
120
class OverloadDemo { //method overloading
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a; class Overload {
} public static void main(String args[]) {
} OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
121 System.out.println("Result of ob.test(123.25): " + result);
} }
//Constructor Overloading
class CDemo{ public static void main(String args[]){
int value1; CDemo d1 = new CDemo();
CDemo d2 = new CDemo(30);
int value2;
CDemo d3 = new CDemo(30,40);
CDemo(){
d1.display();
value1 = 10;
d2.display();
value2 = 20; d3.display();
System.out.println("Inside 1st }
Constructor"); }
}
CDemo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
CDemo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
122
}
import java.util.Scanner;
import java.util.Scanner;
class ScannerTest{
class ScannerTest{
public static void main(String args[]){
int rollno=sc.nextInt();
int rollno=sc.nextInt();
System.out.println("Enter your name");
System.out.println("Enter your name");
String name=sc.next();
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
sc.close();
}
} }
Method
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as a string.
But you can have formal parameters to methods, which overlap with the
names of the class’ instance variables.
this can be used to resolve any name collisions that might occur between
instance variables and formal variables.
When a formal variable has the same name as an instance variable, the formal
variable hides the instance variable.(when this is used)
In this method, changes made to the actual parameter will affect
the actual parameter used to call the method.
131
// Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
Output:
class CallByValue {
a and b before call: 15 20
public static void main(String args[]) { a and b after call: 15 20
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);
}
}
132
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void meth(Test o) { // pass an object
o.a *= 2;
Output:
a and b before call: 15 20
a and b after call: 30 10
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); 133
class Box{ //call by reference class OverloadCons2 {
double width,height,depth; public static void main(String args[]) {
Box(Box ob) { Box mybox1 = new Box(10, 20, 15);
width = ob.width; Box mybox2 = new Box();
height = ob.height; Box mycube = new Box(7);
depth = ob.depth; Box myclone = new Box(mybox1);
} double vol;
Box(double w, double h, double d){
width = w; vol = mybox1.volume();
height = h; System.out.println("Volume of mybox1 is " + vol);
depth = d;
} vol = mybox2.volume();
Box(){ System.out.println("Volume of mybox2 is " + vol);
width = -1;
height = -1; vol = mycube.volume();
depth = -1; System.out.println("Volume of cube is " + vol);
}
Box(double len) { vol = myclone.volume();
width = height = depth = System.out.println("Volume of clone is " + vol);
len; }
} }
double volume() {
134 return width * height *
depth;
Recursion
Recursion is the process of defining
something in terms of itself.
13
5
class Factorial{
int fact(int n){
int result;
if(n==1)
return 1;
else
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));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
136
}
Garbage Collection
Garbage collection is done automatically in java.
String
Once an object is created, no modifications can be done on that.
StringBuffer
Modifications can be allowed on created object.
StringTokenizer
Used to divide the string into substrings based on tokens.
141
String
In java a string is a sequence of characters. They are objects of type String.
Once a String object has been created, we can not change the characters that
comprise in the string.
Strings are unchangeable once they are created so they are called as
immutable.
You can still perform all types of string operations. But, a new String object
is created that contains the modifications. The original string is left
unchanged.
String(char chars[])
String(String strobj)
143
String Constructors
String s= new String(); //To create an empty String call the default constructor.
String( char chars[], int startIndex, int numChars) //To create a string by specifying
positions from an array of characters
char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String s=new String(chars,2,3); //This initializes s with characters
“cde”.
14
6
Special String Operations
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( ), startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Changing the Case of Characters Within a String
147
Special String Operations
String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s); // He is 9 years old.
151
String Comparison
boolean equals(Object str)
//To compare two strings for equality. It returns true if the strings contain the same
characters in the same order, and false otherwise.
boolean equalsIgnoreCase(String str)
//To perform a comparison that ignores case differences.
15
2
String Comparison
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
numChars)
153
String Comparison
class RegionTest{
public static void main(String args[]){
String str1 = "This is Test";
String str2 = "THIS IS TEST";
if(str1.regionMatches(5,str2,5,3)) {
// Case: pos1,secdString,pos1,len
System.out.println("Strings are Equal");
}
else{
System.out.println("Strings are NOT Equal");
}
}
}
Output:
Strings are NOT Equal
154
String Comparison
boolean startsWith(String str) //to determine whether a given String
begins with a specified string.
equals( ) Versus ==
// It compares the characters inside a String object
//To compare two object references to see whether they refer to the same155
String Comparison
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
//String s2 = s1;
System.out.println(s1.equals(s2));
System.out.println( s1 == s2);
}
}
Output:
true
false
156
String Comparison
int compareTo(String str)
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than
str.
Zero The two strings are equal.
157
String Comparison
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now aid all come country for good is men
of
the the their time to to
158
Searching Strings
indexOf( ) //Searches for the first occurrence of a character or
substring.
lastIndexOf( ) //Searches for the last occurrence of a character or
substring.
int indexOf(int ch) //To search for the first occurrence of a character.
int lastIndexOf(int ch) //To search for the last occurrence of a character.
int indexOf(String str) //To search for the first or last occurrence of a substring.
In all cases, the methods return the index at which the character or substring
159
was found, or –1 on failure.
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo { Here is the output of this program:
public static void main(String args[]) { Now is the time for all good men
String s = "Now is the time for all good men " +"to to come to the aid of their country.
come to the aid of their country."; indexOf(t) = 7
System.out.println(s); lastIndexOf(t) = 65
indexOf(the) = 7
System.out.println("indexOf(t) = " +s.indexOf('t')); lastIndexOf(the) = 55
System.out.println("lastIndexOf(t) = " indexOf(t, 10) = 11
+s.lastIndexOf('t')); lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
System.out.println("indexOf(the) = " +s.indexOf("the")); lastIndexOf(the, 60) = 55
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));
160
Modifying a String
String substring(int startIndex)
//To extract a substring, startIndex specifies the beginning index
String substring(int startIndex, int endIndex)
// Here endIndex specifies the stopping point.
//endIndex-1
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String result = org.substring(0, 2);
System.out.println(result);
}
}
Output:
Th
161
String concat(String str)
//To concatenate two strings, concat( ) performs the same function as +.
String s1 = "one";
String s2 = s1.concat("two");
String s1 = "one";
String s2 = s1 + "two";
163
import java.io.*;
public class valueOfDemo {
166
StringBuffer Constructors
StringBuffer( )
// The default constructor (the one with no parameters)
reserves room for 16 characters without reallocation.
StringBuffer(int size)
// accepts an integer argument that explicitly sets the size
of the buffer.
StringBuffer(String str)
// str + reserves room for 16 more characters without
reallocation.
167
Methods
length( ) and capacity( )
setLength( )
charAt( ) and setCharAt( )
getChars( )
append( )
insert( )
reverse( )
delete( ) and deleteCharAt( )
replace( )
substring( )
168
int length( ) //The current length of a StringBuffer can be found via the length( ) method
int capacity( ) //The total allocated capacity can be found through the capacity( ) method.
172
//The insert( ) method inserts one string into another.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
Output:
I like Java!
173
StringBuffer reverse( )
// reverse the characters within a StringBuffer object using reverse( )
// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
174
StringBuffer delete(int startIndex, int endIndex) // to delete characters.
StringBuffer deleteCharAt(int loc)
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Output:
After delete: This a test.
After deleteCharAt: his a test.
175
StringBuffer replace(int startIndex, int endIndex, String str);
//It replaces one set of characters with another set inside a StringBuffer object.
// The replacement string is passed in str.
// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output: After replace: This was a test.
To use StringTokenizer
Specify an input string and a delimiter string.
StringTokenizer(String str)
Methods
int countTokens( ) //returns number of tokens in the string.
boolean hasMoreTokens( ) //checks whether tokens are there or
not
String nextToken( ) //returns the token in the string
178
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo{
//static String str = "Hello Welcome to Java Programming";
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
//StringTokenizer st = new StringTokenizer(str);
//StringTokenizer st = new StringTokenizer(str,",");
StringTokenizer st = new Output:
StringTokenizer(str,",",true); Hello
while(st.hasMoreTokens()) { ,
String tokens = st.nextToken(); Welcome
,
System.out.println(tokens + "\n");
to
} ,
} Java
} ,
179 Programming
Exercise1:
18
0
import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+“is: "+sum);
}
}
Output:
Enter sum of integers: 10+20+30+40
Sum of 10+20+30+40 is: 100
181