Lab 3
Lab 3
OBJECT-ORIENTED PROGRAMMING
LAB 3: ARRAYS CLASS, STRING CLASS
I. Objective
After completing this tutorial, you can:
• Understand how to program with Arrays class.
• Understand how to program with String class.
3. toString(ptype[ ] a)
Return the string representation of the contents of the specified array, the resulting string consists of a
list of the array's elements, separated by a comma and a space, enclosed in square brackets ("[ ]"). It
returns null if the array is null.
Example:
4. sort(ptype[ ] a)
Sorts the array into ascending order. The method uses the total order imposed by the
appropriate compareTo() method for floating point values, and all NaN values are considered
equivalent and equal. This method is not defined for boolean and short.
Example:
1. length()
A String in Java is an object, which contains methods that can perform certain operations on strings. For
example, the length of a string can be found with the length() method:
2. charAt(int index)
You can reference the individual characters in a string by using the method charAt() with the same
index that you would use for an array.
3. compareTo(String str)
You should not use the “==” operator to test whether two strings are equal. Using the “==” operator
determines only whether the references to the strings are the same; it does not compare the contents of
the String instances. You can compare strings by using the compareTo()method. Not only can you
determine whether two strings are equal, but you can determine which of two strings comes before the
other according to the Unicode table.
4. concat(String str)
You can use the concat() method to concatenate two strings. You can also concatenate two strings to
form another string by using the “+” operator.
"Hello".concat(" Wolrd");
Besides adding two strings together, you can also concatenate a string and a value of a primitive type
together by using the + operator.
IV. Exercises
1. Write a Java program (Do not use the Arrays class, use the primitive array like Lab 2):
• Write a function to remove the first specific element from an array and return true, if the
element does not exist in an array return false.
• Write a function to insert an element at a specific position into an array. (After insertion
you can replace the last element with the element before)
(Ex: arr = [1,2,4,3] insert 5 at position 2 returns [1,2,5,4])
• Write a function to find the duplicate values of an array of integer values.
(Ex: arr = [1,3,1,3,2,4] returns [1,3])
• Write a function to remove the duplicate values of an array of integer values.
(Ex: arr = [1,3,1,3,2,4] returns [1,3,2,4])
2. To create an integer 2-dimensional array (matrix), you can use the following statements: