0% found this document useful (0 votes)
54 views

Object Oriented Programming With Java: Department of Ce/It Unit-2 Array & String OOPJ (01CE0403)

The document discusses various topics related to arrays and strings in Java including: 1) Arrays can be initialized in multiple ways such as manually assigning values or using a for loop. 2) The String class in Java allows string operations like concatenation, comparison, extraction of characters etc. Strings are immutable. 3) Common string methods include length(), charAt(), indexOf(), substring() which allow retrieving portions of strings in various ways.

Uploaded by

frek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Object Oriented Programming With Java: Department of Ce/It Unit-2 Array & String OOPJ (01CE0403)

The document discusses various topics related to arrays and strings in Java including: 1) Arrays can be initialized in multiple ways such as manually assigning values or using a for loop. 2) The String class in Java allows string operations like concatenation, comparison, extraction of characters etc. Strings are immutable. 3) Common string methods include length(), charAt(), indexOf(), substring() which allow retrieving portions of strings in various ways.

Uploaded by

frek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Department of

CE/IT

Object Oriented Unit-2


Array & String
Programming with OOPJ (01CE0403)

Java

By: Prof. Ankita


Chavda
 Group of like-typed variables
 Referred by a common name

Arrays
 type var-name[ ]; // OR type[ ] var name;
int month_days[];
 array-var = new type[size];
One-
month_days = new int[12];
Dimensional
Arrays  Example:
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
1. int array1[] = {5,10,15,20,25};
2. int array1[] = new int[5];
for(j=0;j<5;j++)
array1[j] = j+5;
Initialization 3. int array1[] = new int[5];

of Array array1[0]=5;
array1[1]=10;
array1[2]=15;
array1[3]=20;
array1[4]=25;
class Testarray{
public static void main(String args[]){

int a[]=new int[5];//declaration and


instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
Example a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is
the property of array
System.out.println(a[i]);
}
}
 int twoD[][] = new int[4][5];

Multi-
dimensional
Arrays
Jagged Array
Three
Dimensional
Array
 The java.lang.String class provides a lot of methods to work
on string.
 By these methods, we can perform operations on string such
as trimming, concatenating, converting, comparing,
replacing strings etc.
 Java implements strings as objects of type String class
 Once a String object is created it cannot be changed. Stings
are Immutable.
String Class
 To get changeable strings use the class called StringBuffer.
 String anyString = null;
 Array of String:
 String names[ ] = new String[5];
 Initialization of array of String:
 String names[ ]= {“Red”, “Orange”, “Yellow”, “Green”,
“Blue”, “Indigo”, “Violet”};
1. Default Constructor:
 String str = new String( );

String Class
Constructors 2. String object using an array of Characters
 String(char charArray[ ] )
 char Name[ ] = {‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
 String strName = new String(Name);
3. String Object Initialized by range from char array
 String(char charArray[ ], int startindex, int
no_of_char)
 char Name[ ] = {‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
 String strName = new String(Name, 3, 3);
String Class
Constructors 4. String object using another String Object:
 String (String strObject);
 char Name[ ] = {‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
 String strName = new String(Name);
 String strName2 = new String(strName);
 String Literals:
 char Name[ ] = {‘J’, ‘A’, ‘V’, ‘A’, ‘P’, ‘R’, ‘O’, ‘G’};
String Class  String strName = new String(Name);
OR
 String strName = “JAVAPROG”;
 The length() method returns the length of the string.
Ex: System.out.println(“Hello”.length()); // prints 5
 The + operator is used to concatenate two or more strings.
String Eg: String myname = “Harry”;
Operations 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.
 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


String ranges from 0 to length() - 1. The first character of the
Operations sequence is at index 0, the next at index 1, and so on, as
for array indexing.

char ch;
ch = “abc”.charAt(1); // ch = “b”
 getChars() - Copies characters from this string into the
destination character array.
public void getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)

 srcBegin - index of the first character in the string to


copy.
String  srcEnd - index after the last character in the string to
Operations copy.
 dst - the destination array.
 dstBegin - the start offset in the destination array.
 Ex:
 String string1 = “JAVA PROGRAMMING”;
 char substring[ ] = new char[4];
 string1.getChars(5,9,substring,0);
 equals() - Compares the invoking string to the specified object.
The result is true if and only if the argument is not null and is a
String object that represents the same sequence of characters as
the invoking object.
 public boolean equals(Object anObject)
String
Operations  equalsIgnoreCase()- Compares this String to another String,
ignoring case considerations. Two strings are considered equal
ignoring case if they are of the same length, and corresponding
characters in the two strings are equal ignoring case.
 public boolean equalsIgnoreCase(String anotherString)
 startsWith() – Tests if this string starts with the specified
prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true

 endsWith() - Tests if this string ends with the specified suffix.


public boolean endsWith(String suffix)
String
“Figure”.endsWith(“re”); // true
Operations
String str1 = “JAVA”;
String str2 = “JAVA PROGRAMMING”;
String str3 = “MING”;
str2.startWith(str1);
str2.endsWith(str3);
 startsWith() -Tests if this string starts with the specified
prefix beginning at a specified index.
public boolean startsWith(String prefix, int toffset)
String prefix - the prefix.
toffset - where to begin looking in the string.
Operations
“figure”.startsWith(“gure”, 2); // true
 compareTo() - Compares two strings lexicographically.
 The result is a negative integer if this String object
lexicographically precedes the argument string.
 The result is a positive integer if this String object
lexicographically follows the argument string.
String
 The result is zero if the strings are equal.
Operations  compareTo returns 0 exactly when the equals(Object)
method would return true.
public int compareTo(String anotherString)
public int compareToIgnoreCase(String str)
 indexOf – Searches for the first occurrence of a character or
substring. Returns -1 if the character does not occur.

 public int indexOf(int ch)- Returns the index within this


string of the first occurrence of the specified character.
String  public int indexOf(String str) - Returns the index within this
Operations string of the first occurrence of the specified substring.

String str = “How was your day today?”;


str.indexof(‘t’);
str.indexof(“was”);
 public int indexOf(int ch, int fromIndex)- Returns the index
within this string of the first occurrence of the specified
character, starting the search at the specified index.

String  public int indexOf(String str, int fromIndex) - Returns the


index within this string of the first occurrence of the
Operations specified substring, starting at the specified index.

String str = “How was your day today?”;


str.indexof(‘a’, 6);
str.indexof(“was”, 2);
 lastIndexOf() –Searches for the last occurrence of a
character or substring. The methods are similar to indexOf().

 substring() - Returns a new string that is a substring of this


string. The substring begins with the character at the
String specified index and extends to the end of this string.
Operations  public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"

 public String substring(int beginIndex, int endIndex)


Eg: "smiles".substring(1, 5) returns “mile”
 concat() - Concatenates the specified string to the end of
this string.
 If the length of the argument string is 0, then this String
object is returned.
String  Otherwise, a new String object is created, containing the
Operations invoking string with the contents of the str appended to it.

public String concat(String str)


"to".concat("get").concat("her") returns "together"
 replace()- Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

 public String replace(char oldChar, char newChar)

String "mesquite in your cellar".replace('e', 'o') returns "mosquito


in your collar"
Operations
 trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.
 public String trim()
String s = “ Hi Mom! “.trim(); returns “Hi Mom!”
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given begin index.
4 String substring(int beginIndex, int returns substring for given begin index and end index.
endIndex)
5 boolean contains(CharSequence s) returns true or false after matching the sequence of char
value.
6 static String join(CharSequence returns a joined string.
delimiter, CharSequence... elements)
Summary 7 boolean equals(Object another) checks the equality of string with the given object.
8 boolean isEmpty() checks if string is empty.
9 String concat(String str) concatenates the specified string.
10 static String equalsIgnoreCase(String compares another string. It doesn't check case.
another)
11 String[] split(String regex) returns a split string matching regex.
12 int indexOf(int ch) returns the specified char value index.
13 int indexOf(String substring) returns the specified substring index.
14 String toLowerCase() returns a string in lowercase.
15 String toUpperCase() returns a string in uppercase.
 A StringBuffer is like a String, but can be modified.
 The length and content of the StringBuffer sequence can be
changed through certain method calls.
 StringBuffer defines three constructors:
String Buffer
 StringBuffer()
 StringBuffer(int size)
 StringBuffer(String str)
 The principal operations on a StringBuffer are the append
and insert methods, which are overloaded so as to accept
data of any type.

 Here are few append methods:


String Buffer StringBuffer append(String str)
StringBuffer append(int num)

 The append method always adds these characters at the


end of the buffer.
 The insert method adds the characters at a specified point.

 Here are few insert methods:


StringBuffer insert(int index, String str)
String Buffer StringBuffer insert(int index, char ch)

 Index specifies at which point the string will be inserted into


the invoking StringBuffer object.
 delete() - Removes the characters in a substring of this
StringBuffer. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to
String Buffer end, no changes are made.

public StringBuffer delete(int start, int end)


 replace() - Replaces the characters in a substring of this
StringBuffer with characters in the specified String.
public StringBuffer replace(int start, int end, String str)

String Buffer  substring() - Returns a new String that contains a


subsequence of characters currently contained in this
StringBuffer. The substring begins at the specified index and
extends to the end of the StringBuffer.
public String substring(int start)
 reverse() - The character sequence contained in this string
buffer is replaced by the reverse of the sequence.

public StringBuffer reverse()

String Buffer
 length() - Returns the length of this string buffer.

public int length()


 capacity() - Returns the current capacity of the String buffer.
The capacity is the amount of storage available for newly
inserted characters.

public int capacity()


String Buffer
 charAt() - The specified character of the sequence currently
represented by the string buffer, as indicated by the index
argument, is returned.

public char charAt(int index)


 getChars() - Characters are copied from this string buffer
into the destination character array dst. The first character
to be copied is at index srcBegin; the last character to be
copied is at index srcEnd-1.
public void getChars(int srcBegin, int srcEnd, char[] dst,
String Buffer int dstBegin)

 setLength() - Sets the length of the StringBuffer.


public void setLength(int newLength)
No. Method Description
1 length() The length of a StringBuffer can be found by the
length( ) method
2 capacity() the total allocated capacity can be found by the
capacity( ) method.
3 append() It is used to add text at the end of the existence text
4 insert() It is used to insert text at the specified index position.
5 reverse() It can reverse the characters within a StringBuffer
Summary 6 delete(int startIndex,
object
It can delete characters within a StringBuffer by using
int endIndex) the methods delete( )
7 replace() t can replace one set of characters with another set
8 indexOf(String str) This method returns the index within this string of the
first occurrence of the specified substring.
9 lastIndexOf(String str) This method returns the index within this string of the
last occurrence of the specified substring.
10 substring(int start) This method returns a new String that contains a
subsequence of characters
StringBuffer sb = new StringBuffer(“Hello”);
sb.length(); // 5
sb.capacity(); // 21
(16 characters room is
added if no size is specified)
sb.charAt(1); // e
String Buffer sb.setCharAt(1,’i’); // Hillo
Example sb.setLength(2); // Hi
sb.append(“l”).append(“l”); // Hill
sb.insert(0, “Big “); // Big Hill
sb.replace(3, 11, “ ”); // Big
sb.reverse(); // gib
 Random method : This method generates a random double
value greater than or equal to 0.0 and less than 1.0 (0 <=
Math.random() <1.0)
 Ex. (int)(Math.random() * 10) - - > Returns a random
Math.random() integer between 0 and 9.
 a + Math.random() * b - - > Returns a random number
between a and a + b, excluding a + b.
 Ex. 50 + (int)(Math.random() * 50) - - > Returns a
random integer between 50 and 99.
 Each java primitive has a corresponding wrapper class
 A wrapper class is simply a class that encapsulates a single,
immutable value.

Wrapper Class  Type wrapping is important because Java classes and


methods operates on classes rather than fundamental
types.
 Purpose of wrapper class is to allow fundamental types to be
represented as objects.
Primitive Data Type Wrapper Class

boolean Boolean
byte Byte
char Character
short Short
Wrapper Class
int Integer
long Long
float Float
double Double
void Void
 Each wrapper class implements methods specific to each
data type except void class.
 Common methods implemented in all wrapper class:
 ClassType(type)
Wrapper Class  type typeValue( )
 int hashCode( )
 String toString( )
 boolean equals(Object obj)
 static boolean valueOf(String s)
1. ClassType(type):
 Ex. Character c1 = new Character(‘x’);
2. typeValue( ):
 Ex. char c2 = c1.charValue( );
Common
3. toString( ):
Methods in  Ex. System.out.println(c1.toString( ));
Wrapper Class 4. equals( ):
 Ex. S1.equals(s2);
5. valueOf( ):
 Ex. Byte b1= valueOf(“101”,2);
 Boolean Class:
 static boolean getBoolean(String name)

Boolean,  Byte Class:


Byte, Short  static byte parseByte( String s, int radix)
 static byte parseByte( String s)
Class
 Short Class:
 shortValue( )
 isLowerCase( ) & isUpperCase( )
 static boolean isLowerCase(char ch)
 static boolean isUpperCase(char ch)
 Ex. Character c= new Character(‘g’);
 boolean isLower = Character.isLowerCase(c);
Character  isDigit( )
class  static boolean isDigit(char ch)
 Ex. boolean isDigit = Character.isDigit(‘7’);
 isSpace( )
 static boolean isSpace(char ch)
 Ex. boolean isSpace = Character.isSpace(‘\t’);
 toLowerCase( ) & toUpperCase( )
 static char toLowerCase(char ch)
 static char toUpperCase(char ch)
 Ex. char c1 = Character.toUpperCase(‘g’);
char c2 = Character.toLowerCase(‘M’);
 digit( )
Character  static int digit(char ch, int radix)
 Ex. char c1 = ‘4’;
class char c2 = ‘c’;
int four = Character.digit(c1,10);
int twelve = Character.digit(c2,16);
 forDigit( )
 static char forDigit(int digit, int radix)
int i=9;
char c = Character.forDigit(I,10);
 Integer & Long Class
 parseInt( )
 static int parseInt(String s, int radix)
 static int parseInt(String s)
 Ex. Integer i = new Integer(17);
Integer &  float f = i.floatValue();
Long Class
 getInteger( )
 static Integer getInteger(String name)
 static Integer getInteger(String name, int val)
 static Integer getInteger(String name, Integer val)
 Float & Double Class:
 isNaN( )
 boolean isNaN( )
 static boolean isNaN(float v)
 Ex. Double d1 = new Double(23.70);
 System.out.println(“is d1 is not a number?”
Float & +d1.isNaN());
Double Class  isInfinite( )
 boolean isInfinite( )
 static boolean isInfinite(float v)
 Void Class:
 void class has no constructors or methods & only one
member constant TYPE.
 The automatic conversion of primitive data type into its
corresponding wrapper class is known as autoboxing.
 For example, byte to Byte, char to Character, int to Integer,
long to Long, float to Float, boolean to Boolean, double to
Double, and short to Short.
 Since Java 5, we do not need to use the valueOf() method of
wrapper classes to convert the primitive into objects.
public class WrapperExample1
Autoboxing {
public static void main(String args[])
{
int a=20;
Integer i=Integer.valueOf(a);
//converting int into Integer explicitly
Integer j=a;
//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);


Source: javapoint.com }
}
 The automatic conversion of wrapper type into its
corresponding primitive type is known as unboxing. It is the
reverse process of autoboxing.
 Since Java 5, we do not need to use the intValue() method of
wrapper classes to convert the wrapper type into primitives.

public class WrapperExample2


{
Unboxing public static void main(String args[])
{
Integer a=new Integer(3);
int i=a.intValue();
//converting Integer to int explicitly
int j=a;
//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}

Source: javapoint.com
Thank you

You might also like