Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
BITS Pilani
Pilani Campus
Array of Objects &
Strings
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus
Array of Objects
Array of Objects
class Account{
int acc;
String name;
float amount;
void insert(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amount = amt;
}
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Array of Objects
class TestAccount{
public static void main(String[] args){
Account[] a= new Account[3];
for(int i=0;i<3;i++)
{
a[i]= new Account();
a[i].insert(Integer.parseInt(args[3*i]), args[3*i+1], Float.parseFloat(args[3*i+2]));
a[i].display();
}
Output:
}}
111 abc 1000.0
222 bcd 2000.0
333 cde 5000.0
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Strings
Unicode
• Unicode is a universal international standard character
encoding that is capable of representing most of the
world's written languages.
• In Unicode, character holds 2 byte, so java also uses 2
byte for characters.
• lowest value:\u0000
• highest value:\uFFFF
BITS Pilani, Pilani Campus
Need for Unicode
• Before Unicode, there were many language standards:
• ASCII for the United States. (default character set)
• ISO 8859-1 for Western European Language.
• KOI-8 for Russian.
• GB18030 and BIG-5 for chinese, and so on.
• Problem:
• A particular code value corresponds to different letters in
the various language standards.
• Variable length: Some common characters are encoded as
single bytes, other require two or more byte.
BITS Pilani, Pilani Campus
String creation
String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
• Construct a string object by passing another string
object.
String str2 = new String(str);
BITS Pilani, Pilani Campus
More on Strings
• Java string is a sequence of characters. They are objects
of type String.
• Once a String object is created it cannot be changed.
Stings are Immutable.
• To get changeable strings use the class called
StringBuffer.
• String and StringBuffer classes are declared final, so
there cannot be subclasses of these classes.
• The default constructor creates an empty string.
String s = new String();
BITS Pilani, Pilani Campus
String Constructors
• String(byte[] byte_arr) – default character set (ASCII)
byte[] b_arr = {74, 97, 118, 97};
String str =new String(b_arr); // JAVA
• String(byte[] byte_arr, Charset char_set)
byte[] b_arr = {0x4a, 0x61, 0x76, 0x61};
Charset cs = Charset.forName("UTF-8");
String str = new String(b_arr, cs);
• Refer (List of character set supported by Java):
https://
docs.oracle.com/javase/8/docs/technotes/guides/intl/e
ncoding.doc.html
BITS Pilani, Pilani Campus
String Constructors
• String(byte[] byte_arr, String char_set_name)
byte[] b_arr = {0x4a, 0x61, 0x76, 0x61};
String str = new String(b_arr, "UTF-8");
• String(byte[] byte_arr, int start_index, int length)
• String(byte[] byte_arr, int start_index, int length, Charset
char_set)
• String(byte[] byte_arr, int start_index, int length, String
char_set_name)
• String(char[] char_arr)
• String(char[] char_array, int start_index, int count)
BITS Pilani, Pilani Campus
Go to menti.com
Use code: 92 31 73 9
BITS Pilani, Pilani Campus
Example
public class StringExamples
{
public static void main(String[] args)
{
String s1 = "JAVA";
String s2 = "JAVA";
System.out.println(s1 == s2); Output : true
String s3 = new String(“JAVA”);
System.out.println(s2 == s3); Output : false
}
}
System.out.println(s2.equals(s3));
// Output: true
BITS Pilani, Pilani Campus
Example
public class StringExamples
{
public static void main(String[] args)
{
String s1 = "JAVA";
String s2 = "JAVA";
s1 = s1 + "J2EE";
Output : false
System.out.println(s1 == s2);
}
}
BITS Pilani, Pilani Campus
What happens in memory?
BITS Pilani, Pilani Campus
Are Strings created using new
operator also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");
System.out.println(s1); //Output : JAVA
s1.concat("J2EE");
System.out.println(s1); //Output : JAVA
}
}
BITS Pilani, Pilani Campus
Are Strings created using new
operator also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");
System.out.println(s1); //Output : JAVA
String s2=s1.concat("J2EE");
System.out.println("s1: "+s1+" s2: "+s2); //Output : s1: JAVA s2: JAVAJ2EE
}
}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
String Buffer
StringBuffer Constructors
String Buffer represents growable and writable character
sequences. The size grow automatically to accommodate
characters and substring insert or append operations.
Constructor Description
public StringBuffer() create an empty StringBuffer
create a StringBuffer with initial room
public StringBuffer(int capacity)
for capacity number of characters
create a StringBuffer containing the
public StringBuffer(String str)
characters from str
BITS Pilani, Pilani Campus
Capacity of the String
Buffer
• If the number of character increases from its current capacity, it
increases the capacity by (oldCapacity*2)+2
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity());
sb.append(" Programming");
System.out.println(sb.capacity());
sb.append("is ea");
System.out.println(sb.capacity()); Output:
20
StringBuffer sb1 = new StringBuffer(5); 20
sb1.append("Program"); 42
System.out.println(sb1.capacity()); 12
sb1.append(“ming"); 12
System.out.println(sb1.capacity());
BITS Pilani, Pilani Campus
ensureCapacity of the
StringBuffer
StringBuffer sb = new StringBuffer("Java is my favourite language");
System.out.println(sb.capacity());
sb.ensureCapacity(10);
System.out.println(sb.capacity());
Output:
45
sb.ensureCapacity(50);
45
System.out.println(sb.capacity()); 92
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
String Tokenizer
String Tokenizer
• java.util.StringTokenizer class allows you to break a
string into tokens
• default delimiter set, which is " \t\n\r\f" : the space character, the tab character,
the newline character, the carriage-return character, and the form-feed character.
Constructor Description
StringTokenizer(String str) creates StringTokenizer with
specified string.
StringTokenizer(String str, String creates StringTokenizer with
delim) specified string and delimeter.
StringTokenizer(String str, String creates StringTokenizer with
delim, boolean returnValue) specified string, delimeter and
returnValue. If return value is true,
delimiter characters are considered
to be tokens. If it is false, delimiter
characters serve to separate tokens.
BITS Pilani, Pilani Campus
Methods
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String delim) returns the next token, after switching to
the new delimiter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type
is Object.
int countTokens() returns the total number of tokens.
BITS Pilani, Pilani Campus
String Tokenizer - Example
import java.util.StringTokenizer;
public class test{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is \t khan \n");
int i=0,j;
j = st.countTokens();
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
i++;
Output:
} my
System.out.println("i: "+i+"and j: "+j); name
System.out.println( st.countTokens()); is
} khan
i: 4 and j: 4
} 0
BITS Pilani, Pilani Campus
String Tokenizer - Example
import java.util.StringTokenizer;
public class Test{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name/ is \t khan \n");
int i=0,j;
j = st.countTokens();
while (st.hasMoreTokens()) {
System.out.println(st.nextToken("/"));
i++; Output:
} my name
is khan
System.out.println("i: "+i+"and j: "+j);
System.out.println( st.countTokens()); i: 2and j: 4
} 0
}
BITS Pilani, Pilani Campus
Review Questions
• StringTokenizer stuff = new StringTokenizer("abc,def,ghi");
System.out.println(stuff.nextToken() );
Output:
abc,def,ghi
• StringTokenizer stuff = new StringTokenizer("abc,def,ghi", ",");
System.out.println(stuff.nextToken());
Output:
abc
BITS Pilani, Pilani Campus
Review Questions
• StringTokenizer stuff = new StringTokenizer( "abc+def+ghi", "+", true );
System.out.println( stuff.nextToken() );
System.out.println( stuff.nextToken() );
Output:
abc
+
• StringTokenizer stuff = new StringTokenizer( "abc def+ghi", "+");
System.out.println( stuff.nextToken() );
System.out.println( stuff.nextToken() );
Output:
abc def
ghi
BITS Pilani, Pilani Campus
Review Questions
• StringTokenizer st = new StringTokenizer( "abc+def:ghi", "+:",
true );
while(st.hasMoreTokens()){
System.out.println(st.nextToken()); }
Output:
abc
+
def
:
ghi
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Self Reading: String Methods
(Few important methods are discussed. Refer the
Textbook for the remaining methods)
Length and Append
• The length() method returns the length of the string.
System.out.println(“Hello World”.length());
// prints 11
• The + operator is used to concatenate two or more strings.
String myname = “Harry”
String str = “My name is ” + myname+ “.”;
• For string concatenation the Java compiler converts an
operand to a String whenever the other operand of the + is
a String object.
BITS Pilani, Pilani Campus
String Methods-Character
Extraction
• Characters in a string can be extracted in a number of ways.
• public char charAt(int index)
– Returns the character at the specified index. An index
ranges from 0 to length() - 1.
char ch;
ch = "Hello World".charAt(4);
String s1 = new String("Hello World");
ch=s1.charAt(4);
Output:
o
BITS Pilani, Pilani Campus
String Methods-Character
Extraction
• public void getChars(int start, int end, char[]
destination, int destination_start)
s1 = "Hello World";
char ch[]=new char[20];
s1.getChars(0, 11, ch, 0);
• public byte[] getBytes()
• public char[] toCharArray()
s1 = "Hello World";
char ch[]=s1.toCharArray();
BITS Pilani, Pilani Campus
String Methods
To compare two string objects
• boolean equals( Object otherObj)
• boolean equalsIgnoreCase (String anotherString)
• int compareTo( String anotherString): Compares two
string lexicographically.
s1 = "World"; Output:
s2 = "Hello"; 15
p=s1.compareTo(s2);
• This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.
BITS Pilani, Pilani Campus
String Methods
• int compareToIgnoreCase( String anotherString)
• Compares two string lexicographically, ignoring case considerations.
• String toLowerCase()
• Converts all characters to lower case
• String toUpperCase()
• Converts all characters to upper case
• String trim()
• Returns the copy of the String, by removing whitespaces at both ends. It does
not affect whitespaces in the middle.
• String replace (char oldChar, char newChar)
• Returns new string by replacing all occurrences of oldChar with newChar
BITS Pilani, Pilani Campus
String Methods
• public boolean endsWith(String suf)
• Return true if the String has the specified suffix.
• public boolean startsWith(String pre)
• Returns true if the String has the specified prefix
s1 = "Hello World";
s2 = "World";
System.out.println(s1.endsWith(s2));
BITS Pilani, Pilani Campus
String Methods
• public boolean regionMatches(int start_OString, String
another, int start_AString, int no_of_char)
• public boolean regionMatches(boolean ignore_case,
int start_OString, String another, int start_AString, int
no_of_char)
s1 = "HellO World";
s2 = "hello";
System.out.println(s1.regionMatches(1, s2, 1, 4));
System.out.println(s1.regionMatches(true, 1, s2, 1,
4));
BITS Pilani, Pilani Campus
String Methods
• String substring (int i) – returns the substring from the
ith index
s1 = new String("Hello World"); Output:
s2=s1.substring(4); o World
System.out.println(s2);
• String substring (int i, int j): Returns the substring from
i to j-1 index.
s1 = new String("Hello World");
s2=s1.substring(4,7); Output:
System.out.println(s2); oW
BITS Pilani, Pilani Campus
String Methods
• String concat( String str) – Concatenates the string ‘str’ to
the object invoking the method.
s1 = "Hello ";
Output:
s2 = "World";
s1: :Hello s2 :Hello World
s2=s1.concat(s2);
System.out.println("s1: :"+s1+"s2 :"+s2);
• int indexOf (String s) – returns index of the first occurrence of
the specified string;
•Returns -1 if not found
s1 = "World, Hello World, Hello";
Output:
s2 = "Hello";
7
p=s1.indexOf(s2);
BITS Pilani, Pilani Campus
String Methods
• int indexOf (String s, int i) – returns index of the first
occurrence of the specified string, starting at the specified
index
s1 = "World, Hello World, Hello";
s2 = "Hello"; Output:
p=s1.indexOf(s2,8); 20
• int lastIndexOf( int ch): Returns the index within the
string of the last occurrence of the specified string.
s1 = "World, Hello World, Hello";
s2 = "Hello";
p=s1.lastIndexOf(s2); Output:
20
BITS Pilani, Pilani Campus
String Methods
• public int codePointAt(int index)
• returns the Unicode point of an index
s1 = "Hallo World"; Output:
97
p=s1.codePointAt(1);
• public int codePointBefore(int index)
• public boolean contains(String str)
• Returns true if the invoking string object contains ‘str’
s1 = "Hello World";
s2 = “World";
System.out.println(s1.contains(s2));
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
String Buffer Methods
String Buffer - Methods
Methods Description
StringBuffer append( char c ) append c to the end of the StringBuffer
convert i to characters, then append them
StringBuffer append( int i )
to the end of the StringBuffer
convert L to characters, then append them
StringBuffer append( long L )
to the end of the StringBuffer
convert f to characters, then append them
StringBuffer append( float f )
to the end of the StringBuffer
convert d to characters, then append them
StringBuffer append( double d )
to the end of the StringBuffer
append the characters in s to the end of the
StringBuffer append( String s )
StringBuffer
return the current capacity (capacity will
int capacity()
grow as needed).
char charAt( int index ) get the character at index.
StringBuffer delete( int start, int end) delete characters from start to end-1
StringBuffer deleteCharAt( int index) delete the character at index
BITS Pilani, Pilani Campus
String Buffer - Methods
Methods Description
insert character c at index (old characters move over to
StringBuffer insert( int index, char c)
make room).
StringBuffer insert( int index, String st) insert characters from st starting at position i.
convert i to characters, then insert them starting at
StringBuffer insert( int index, int i)
index.
convert L to characters, then insert them starting at
StringBuffer insert( int index, long L)
index.
convert f to characters, then insert them starting at
StringBuffer insert( int index, float f)
index.
convert d to characters, then insert them starting at
StringBuffer insert( int index, double d)
index.
int length() return the number of characters presently in the buffer.
StringBuffer reverse() Reverse the order of the characters.
void setCharAt( int index, char c) set the character at index to c.
return a String object containing the characters in the
String toString()
StringBuffer. BITS Pilani, Pilani Campus