Java - Unit 2 - Stringbuffer
Java - Unit 2 - Stringbuffer
Classes
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Note: The data, or variables, defined within a class are called instance
variables. The code contained within methods. Collectively, the methods
and variables defined within a class arecalled members of the class.
Simple Class
class Box {
double width;
double height; 24 bytes –mybox width
double depth;
}
A class defines a new type of data. In this case, the new data type is called Box
create a Box object,
Box mybox = new Box(); // create a Box object called mybox
Creating an object contains its own copy of each instance variable defined by the
class.
Every Box object will contain its own copies of the instance variables width,
height, and depth. To access these variables, you will use the dot (.) operator.
The dot operator links the name of the object with the name of an instance
variable.
For Ex:
mybox.width = 100;
Simple Class - Example
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box. Volume is 3000.0
public class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Simple Class - Example
class Box {
double width;
double height;
double depth;
}
public class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box(); Volume is 3000.0
Box mybox2 = new Box(); Volume is 162.0
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's Note: mybox1’s data is completely
instance variables */
mybox2.width = 3; separate from the data contained in
mybox2.height = 6; mybox2
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Declaring Objects
Declare an object of type Box:
Box mybox = new Box();
or
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
After firstline executes,mybox contains the value null, which indicates that
it does not yet point to an actual object
After the second line executes, mybox holds the memory address of the
actual Box object.
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
Any changes made to the object through b2 will affect the object to which b1 is referring, since they are
the same object.
After firstline executes,mybox contains the value null, which indicates that
it does not yet point to an actual object
After the second line executes, mybox holds the memory address of the
actual Box object.
Assigning Object Reference Variables
class Box {
double width;
double height;
double depth;
}
public class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = mybox1; Volume is 3000.0
double vol; Volume is 162.0
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is ― + vol);
}
}
Assigning Object Reference Variables
class Box {
double width;
double height; For example:
double depth;
}
Box b1 = new Box();
public class BoxDemo2 { Box b2 = b1;
public static void main(String args[]) {
Box mybox1 = new Box(); // ...
Box mybox2 = mybox1;
double vol;
b2 = null;
// assign values to mybox1's instance variables Here, b2 has been set to null,
mybox1.width = 10;
mybox1.height = 20; but b1 still points to the original
mybox1.depth = 15; object.
/* assign different values to mybox2's
instance variables */ Alhough b1 and b2 both refer to
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
the same object, they are not
linked in any other way.
mybox2.width = 3;
mybox2.height = 6; For example, a null assignment to
mybox2.depth = 9;
// compute volume of first box
b1 will simply unhook b1 from
vol = mybox1.width * mybox1.height * mybox1.depth; the original object
System.out.println("Volume is " + vol);
mybox2=null; without affecting the object or
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
affecting b2.
System.out.println("Volume is " + vol);
}
Volume is 3000.0
} Volume is 162.0
Volume is 162.0
Introducing Methods
classes consist of two things: instance variables and methods.
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
Output
depth = 10; Constructing Box
}
// compute and return volume
Constructing Box
double volume() { Volume is 1000.0
return width * height * depth;
}
Volume is 1000.0
}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
Output
} Volume is 3000.0
// compute and return volume
double volume() {
Volume is 162.0
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
1. AREA AND PERIMETER OF CIRCLE- Practicals
import java.io.*;
public class circle
{
public static void main(String args[]) throws IOException
{
double radius;
double area;
double perimeter;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the radius: ");
String t=in.readLine(); Output
radius= Double.parseDouble(t); Enter the radius: 4
area=3.14*radius*radius;
perimeter=2*3.14*radius;
Area of circle: 50.24
System.out.println("Area of circle: "+area); Perimeter of circle: 25.12
System.out.println("Perimeter of circle: "+perimeter);
}
}
this Keyword
when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
this keyword resolves any name space collisions that might occur between
instance variables and local variables.
Note: this version of OverloadDemo does not define test(int). Therefore, when test( ) is called with an integer argument inside
Overload, no matching method is found. However, Java can automatically convert an integer into a double, and this
conversion can be used to resolve the call.
3. Overloading Methods - Practicals
class areaclass
{
void area()
{
int r=5;
System.out.println("The area of circle with radius 5 is :"+3.14*r*r);
}
void area(int a)
{
System.out.println("area of a circle with radius "+a+"is= "+3.14*a*a);
}
void area(int a,int b)
{
System.out.println("area of a rectangle with length and breadth:"+a+" "+b+"is "+a*b);
}
double area(double a,double b)
{
Output
return(1.0/2.0)*a*b; The area of circle with radius 5 is :78.5
}
} area of a circle with radius 10is= 314.0
public class overloadarea
{
area of a rectangle with length and
public static void main(String args[]) breadth:10 20is 200
{
areaclass ob=new areaclass(); area of triangle is :15.0
double result;
ob.area();
ob.area(10);
ob.area(10,20);
result= ob.area(5.0,6.0);
System.out.println("area of triangle is :"+result);
}
}
Overloading Constructors
public class OverloadCons {
class Box {
public static void main(String args[]) {
double width;
// create boxes using the various constructors
double height;
Box mybox1 = new Box(10, 20, 15);
double depth;
Box mybox2 = new Box();
// constructor used when all dimensions
Box mycube = new Box(7);
specified
double vol;
Box(double w, double h, double d) {
// get volume of first box
width = w;
vol = mybox1.volume();
height = h;
System.out.println("Volume of mybox1 is " + vol);
depth = d;
// get volume of second box
}
vol = mybox2.volume();
// constructor used when no dimensions
System.out.println("Volume of mybox2 is " + vol);
specified
// get volume of cube
Box() {
vol = mycube.volume();
width = -1; // use -1 to indicate
System.out.println("Volume of mycube is " + vol);
height = -1; // an uninitialized
}
depth = -1; // box
}
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume Output
double volume() { Volume of mybox1 is 3000.0
return width * height * depth; Volume of mybox2 is -1.0
}
} Volume of mycube is 343.0
Using Objects as Parameters
• The situation changes when objects are passed by what is effectively call-
by-reference. when a variable is created of a class type, a reference to
an object is created, the parameter that receives it will refer to the same
object as that referred to by the argument
Argument Passing
A method can return any type of data, including class types that you create.
// Returning an object.
class Test {
int a; ob2 –
Test(int i) { a=12
a = i;
} Output
Test incrByTen() { Ob1 – a =2
Test temp = new Test(a+10); ob1.a: 2
return temp;
}
ob2.a: 12
} ob2.a after second increase: 22
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
Recursion
Instance variables declared as static are, essentially, global variables. When objects of its class are
declared, no copy of a static variable is made. Instead, all instances of the class share the same static
variable.
class StaticDemo
Methods declared as static have several restrictions:
{
•They can only call other static methods. static int a = 42;
•They must only access static data. static int b = 99;
•They cannot refer to this or super in any way. static void callme()
class UseStatic {
System.out.println("a = " + a);
{ static int a = 3; Static block initialized. }
static int b; x = 42 }
static void meth(int x) a=3 class StaticByName
{ System.out.println("x = " + x); {
b = 12 public static void main(String args[])
System.out.println("a = " + a);
{StaticDemo.callme();
System.out.println("b = " + b); }
System.out.println("b = " + StaticDemo.b);
static }
{System.out.println("Static block initialized."); }
b = a * 4;
} a = 42
public static void main(String args[]) b = 99
{meth(42);
}
}
final
A variable can be declared as final. Doing so prevents its contents from being
final int YES = 1;
final int NO = 0;
final double PI =3.14;
Nested and Inner Classes
A class within another class; such classes are known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing class.
• If class B is defined within class A, then B does not exist independently of A.
• A nested class has access to the members, including private members, of the
class in which it is nested.
• Enclosing class does not have access to the members of the nested class.
Nested and Inner Classes
String(char chars[ ], int startIndex, int numChars) – start Index specifies the index at which
the subrange begins, and numChars specifies the number of characters to use
Ex : char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes with the characters ―cde‖
String(StringstrObj) - Construct a String object that contains the same character sequence
as another String object
String
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
asciiChars specifies the array of bytes. The second form allows you to specify a subrange.
•Once created, a string cannot be changed: none of its methods changes the
string.
•Such objects are called immutable.
•Immutable objects are convenient because several references can point to the
same object safely
Less efficient — you need to create a new string and throw away the old one even for small
changes
word ―java"
―Java"
String
// index 012345678901
String s1 = “Java Program";
String s2 = “HERBERT";
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // g
System.out.println(s1.substring(7, 10)) // “ogr"
String s3 = s2.substring(2, 5);
System.out.println(s3.toLowerCase()); // “rbe"
String
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 thespecified location.
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.
String methods – Comparison
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.
String methods – Comparison
class strcomparison
{
public static void main(String args[]){
String s1="Sita";
String s2="Sita";
String s3="Ram";
String s4="Hello World";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s4.regionMatches(6, "world", 0, 4));//false
System.out.println(s4.regionMatches(true, 6, "world", 0,
4));//true
}
}
String methods
String concat(String)
String trim()
String replace(char original,char replacement)
static String valueOf(double num) “10.45”
static String valueOf(long num)
static String valueOf(char chars[])
static String valueOf(char chars[],int startindex,int numchars)
static String valueOf(Object ob)
14.Program for string manipulation.
import java.io.*;
class strmanp else if (Character.isDigit(ch))
{ digits++;
public static void main(String[] args) throws else if (Character.isWhitespace(ch))
IOException { blanks++;
else
String str; spchar++;
int vowels=0, digits=0, blanks=0, cons=0, }
spchar=0; System.out.println("Vowels : " + vowels);
char ch; System.out.println("Constants : " +
DataInputStream inp=new cons);
DataInputStream(System.in); System.out.println("Digits : " + digits);
System.out.print("Enter a string : "); System.out.println("Blanks : " + blanks);
str=inp.readLine(); System.out.println("Special Character :
for(int i=0;i<str.length();i++) " + spchar);
{ }
ch=str.charAt(i); }
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||
ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch=='u'
|| ch=='U')
vowels++;
else if (Character.isLetter(ch))
cons++;
Command-Line Arguments
Sometimes we want to pass information into a program when you run it. A command-line
argument is the information that directly follows the program’s name on the command
line when it is executed.
To access the command-line arguments inside a Java program is quite easy— they are
stored as strings in a String array passed to the args parameter of main( ). The first
command-line argument is stored at args[0], the second at args[1], and so on.
– StringBuffer()
– StringBuffer(int size)
– StringBuffer(String str)
string
StringBuffer Operations
• length - Returns the length of this string buffer.
int length()
• capacity - Returns the current capacity of the String buffer. The capacity is
the amount of storage available for newly inserted characters. (16 additional
character is added automatically)
int capacity()
string
StringBuffer Operations
• charAt - -charAt( ) returns the character at the specified location(index).
char charAt(int index)
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
string
StringBuffer Operations
Class Substr {
removed"); }
System.out.println(str);
substr=din.readLine();
System.out.println("number of substring
strlen=str.length();
removed "+ ctr);
substrlen=substr.length();
}
strlen=strlen-substrlen; }
Wrapper Classes
The java.lang package contains wrapper classes that correspond to each primitive
type.
This makes it possible to have class types that behave somewhat like primitive types.
Wrapper classes also contain a number of useful predefined constants and static
methods Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
void Void
Wrapper Classes
The following declaration creates an Integer object which represents the integer 40
as an object
Integer age = new Integer(40);
An object of a wrapper class can be used in any situation where a primitive value will
not suffice
Primitive values could not be stored in such containers, but wrapper objects could be
Wrapper Classes
Wrapper classes also contain static methods that help manage the associated type
For example, the Integer class contains a method to convert an integer stored in a
String to an int value:
num = Integer.parseInt(str);
A class that is inherited is called a superclass. The class that does the inheriting is called
a subclass. Therefore, a subclass is a specialized version of a superclass.
It inherits all of theinstance variables and methods defined by the superclass and adds its
own, unique elements.
Terminology
subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
What really happens?
When an object is created using new, the system must allocate enough
memory to hold all its instance variables.
This includes any inherited instance variables
In this example, we can say that an Employee "is a kind of" Person.
An Employee object inherits all of the attributes, methods and
associations of Person
Person
- name: String
Person
- dob: Date
name = "John
Smith"
dob = Jan 13, 1954 Employee
is a kind of name = "Sally Halls"
Employee dob = Mar 15, 1968
- employeeID: int employeeID = 37518
- salary: int salary = 65000
- startDate: Date startDate = Dec 15,
2000
Inheritance in Java
Class
The class called Object
Object
Constructors and Initialization
}
Object References and Inheritance
BankAccount
anAccount
name = "Craig"
accountNumber = 123456
OverdraftAccount
name = "John"
account1 accountNumber = 3323
limit = 1000.0
Polymorphism
In the previous slide, the two variables are defined to have the same type
at compile time: BankAccount
However, the types of objects they are referring to at runtime are
different