Java Training Handout Arrays - Methods-Strings
Java Training Handout Arrays - Methods-Strings
• Java Array.isarray
• Java Methods
• Classes and Constructors and Objects
• Java Strings
Java Array
• In most cases we want a software solution that can handle a large number of values of the same
type.
• Consider the case of 60 students in a class where each must sit for a cat. Imagine creating a
large set of variables to store each students cat1 marks. Such a statement would look like:
• int st1cat, st1cat, st2cat, st3cat, st4cat, st5cat,............. st60cat;
That would be an tedious and time wasting and ultimately will make programming unwelcome
Definition
An array is a collection of similar type of elements that have contiguous memory location.
• Java array is an object the contains elements of similar data type.
• It is a data structure which can store only fixed set of elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index and last element is n-
1 index if the array is of size n
Example
int[] ages; or int []ages; or int ages[];
Example
ages=new int[10];
Qn3 Modify Example4 above to become Exercise1 above to also contains the actual unit names of
seven units done in semester.The program should be able to print the unit code and the corresponding
unit name in a tabular form as shown below.
Unit Code Unit Name
1………… ……………
2…………. …………….
Qn4. Modify Exercise1 above to become Exercise2 that contains another array “marks” that contains
seven marks acquired by a student semester. The program should be able to print the unit code and the
unit name and the corresponding marks in a tabular form as shown below.
Unit Code Unit Name Marks
1………… …………… ……..
2…………. ……………. ……..
Qn5. Modify Exercise2 above to become Exercise3 such that it use the grading nested if-else
structure to work out the grade for each marks. The program should be able to print the unit code and
the unit name marks and the the corresponding grade in a tabular form as shown below.
Unit Code Unit Name Marks Grade
1………… …………… …….. ……...
2…………. ……………. …….. ………
Qn6. Modify Exercise3 above to become Exercise4 such that the program should be able to print the
unit code and the unit name marks and the the corresponding grade in a tabular form as shown below
but also the average marks and average grade is indicated below..
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
Declaration
DataType[][] arrayName 5 8 45 51
3 35 16 13 Rows
dataType [][]arrayRefVar;(or)
dataType arrayRefVar[][];(or) 25 23 29 23
dataType []arrayRefVar[];
Columns
Instantiate Multidimensional Array
int[][] arr=new int[3][4];//3 row and 4 column
Example to initialize Multidimensional Array
arr[0][0]=5;
arr[0][1]=8;
arr[0][2]=45;
arr[0][3]=51;
arr[1][0]=3;
arr[1][1]=55;
arr[1][2]=16;
arr[1][2]=13;
arr[2][0]=25;
arr[2][1]=23;
arr[2][2]=29;
arr[2][2]=23;
Qn10 Modify Exercise7 above to become Exercise8 such that this time the program prints out the the
column values sum and the row sums.
Qn11. Refer to Qn 10 corresponding to Exercise4 . Modify the program such that instead of having
the array you now have a two dimensional array that contains the unit code ,the unit name and marks.
The Program show then printout the same result including the grade.
Methods(functions in C++, C, PHP ) are the most basic building block of a program. They are so
significant that every programming student should make all effort to see that they are able to work with
methods at all times.
In this Lesson:
• Creating Methods
• Calling Methods
• Types of Methods
◦ Method overloading
◦ Constructors
◦ Returning and None returning methods
• Passing Arguments to Methods
◦ passing primitive types
◦ Passing an array of primitive types
◦ Passing an object
◦ Passing an array of objects
• Returning Methods
◦ Returning primitive types
◦ Returning an array of primitive types
◦ Returning an object
◦ Returning an array of objects
Creating Method:
Considering the following example to explain the syntax of a method:
public static int methodName(int a, int b) {
// body
}
Here,
• public static : modifier.
• int: return type
• methodName: name of the method
• a, b: formal parameters
• int a, int b: list of parameters
The definition follows the general syntax below.
modifier returnType nameOfMethod (Parameter List) {
// method body
}
return min;
}
Method Calling:
For using a method, it should be called. There are two ways in which a method is called depending on
whether the method
1. Returns a value or
2. Returns nothing (no return value).
• A method can only be defined and called within a class.
• In an executing class the method can be called within the main method as shown in the example
below.
methodn(){}
int s=sum(x,y);
System.out.println(“Sum is”+ sum);
}//End of main
othermethodn(){}
}//End of class
When a program invokes a method, the program control gets transferred to the called method. This
called method then returns control to the caller in two conditions, when:
• return statement is executed. ( For a returning method)
• reaches the method ending closing brace. ( For a returning method)
Example to demonstrate how to define a method and how to call it:
public class ExampleMinNumber{
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Method Overloading:
Method overloading in java occur when a class has two or more methods by same name but
different parameters .
Lets consider the example shown before for finding minimum numbers of integer type. If, lets say we
want to find minimum number of double type. Then the concept of Overloading will be introduced to
create two or more methods with the same name but different parameters.
The below example explains the same:
public class ExampleOverloading{
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
A class is a programming construct that specify the relevant properties and behvior of an object for the
problem being solved.
• It has the same name as its class and is syntactically similar to a method.
• However, constructors have no explicit return type.
• All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero.
• However, once you define your own constructor, the default constructor is no longer used.
Example:
Here is a simple example that uses a constructor without parameters:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
You would call constructor to initialize objects as follows:
public class ConsMain {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parametarized Constructor
Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a
constructor in the same way that they are added to any other method, just declare them inside the
parentheses after the constructor's name.
Example:
Here is a simple example that uses a constructor with parameter:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
You would call constructor to initialize objects as follows:
public class ConsMain {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
This would produce the following result:
10 20
Example
Here is an example that uses this keyword to access the members of a class.
public class This_Example {
//Instance variable num
int num=10;
This_Example(){
System.out.println("This is an example program on keyword this ");
}
This_Example(int num){
this();//Invoking the default constructor
//Assigning the local variable num to the instance variable num
this.num=num;
}
public void greet(){
System.out.println("Hi Welcome to Java Programming");
}
}
What would be the out put?
TASK
1. Consider class Marks that contains the marks of a student consisting of cat1(/15), cat2(/25) and
exam(/60). Write a program that makes use of methods:
i. A constructor Marks() that initializes the default values of cat1 to 2 , cat2 to 4 and exam to 10.
ii. A parameterized constructor Marks(int cat1,int cat2,int exam) that set the instance variables to the
corresponding argument values. ( use the this keyword)
iii. catsum() that returns the sum of cats,
iv. aggmarks() that returns the sum of cats and exam
v. grade() that receives the aggmarks and returns the corresponding grade
The program should make use of the methods to output a given marks as show below
CAT1 tab CAT2 tab EXAM tab GRADE
2. Repeat question 3 for 8 marks ( You can assume a student taking eight units and is examined). Hint: use a loop
Variable Arguments(var-args):
From JDK 1.5 java enables you to pass a variable number of arguments of the same type to a method.
The parameter in the method is declared as follows:
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length
parameter may be specified in a method, and this parameter must be the last parameter.
Any regular parameters must precede it.
Example: A Vriable Argument Method returns the maximum value of any size array
public class MaxMain {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
// Variable array method that returns the maximum value of any size array.
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;// Will terminate the method call
}
TASKS
1. Modify the example above to work for the minimum value
2. Modify the example above to work for the sum of all values
3. Modify the example above to work for the average value of all values
Exercise
For each of the question 1-6 below, write a program to implement it.
1. A farmer uses his farm as follows. Wheat-20%, Maize-30%, Grazing 35% and the remaining
sunflower farming. Write a method that receives the number of hectares in a farm and the out
put in a tabular format the number of acres allocated for each of the farming need above.
2. A simple interest rate at a bank is 12%. Write a function that receives the amount deposited and
the interest desired and then return the number of years that it will take to earn the interest.
3. Write a method that receives the integer values of a, b, c, and p and then use the value to output
the value of the following expressions. The output should include the expression whose value is
shown.
4. 2(3a+b), 6(3b+2p-2a) , (3bx2p)/2a, (6((3b+2p)-(2a+2b))/(2pXb))1/5
5. Write a method that receives the litres of water and then output the capacities in m3 and in cm3.
6. Write a method that receives the diameter and height of a cylindrical tank and then return the
litres of water the tank can hold.
A Quadratic Equation
A quadratic equation is an equation of the form y=ax2+bx+c where a, and b are the coefficients and c is
a constants.
The solution of such a question can be determined by evaluating the determinant b2-4ac as follows:
a) If the det=b2-4ac=0 then the equation has two equal roots.
b) If the det=b2-4ac>0 then the equation has two real roots.
c) If the det=b2-4ac<0 then the equation has no real roots.
The roots in case of a and b above are evaluated using the formula (-b (+-)(det)1/2)/2a
6. Write a method det() that receives a,b and c and returns the determinant.
7. Write a method the roots() that receives the values a, b and c and then makes use of the method
det() above to evaluate the roots of any quadratic equation.
8. Write a program to evaluate the method above
Example:Working With Array Of Objects
}//End of main
}//End of Class MarksMain
Example: A Method That receives an Array Of Objects
return mk;
}//End for method createMarks
Write java program that uses a method createCylinders() to creates and return an array that store 20 cylinders. It uses
another method processCylinders() that receives an array of cylinders and process it to get the radius r , the height h , the
corresponding volume and surface areas of each of the cylinder. The program uses the method getVolume() that receives a
cylinder object and returns the volume, the method getSAraea() that receives cylinder object and returns the surface area of
the cylinder. The program prints details in a tabular as shown:
….... ….. …. ….
….... ….. …. ….
….... ….. …. ….
….... ….. …. ….
Escape Sequences:
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
The newline character (\n) has been used frequently in this tutorial in System.out.println() statements to
advance to the next line after the string is printed.
Following table shows the Java escape sequences:
Example:
If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes:
public class Test {
public static void main(String args[]) {
System.out.println("She said \"Hello!\" to me.");
}
}
Task
Modify the above code to print out single quotes and back slash in text.
Character Methods:
Here is the list of the important instance methods that all the subclasses of the Character class
implement:
Methods Description and Example OUTPUT
isLetter() :Determines whether the specified char value is a letter.
public class Test {
public static void main(String args[]) { true
System.out.println(Character.isLetter('c')); false
System.out.println(Character.isLetter('5'));
}
}
isDigit() :Determines whether the specified char value is a digit.
public class Test {
public static void main(String args[]) { false
System.out.println(Character.isDigit('c')); true
System.out.println(Character.isDigit('5'));
}
}
isWhitespace() :Determines whether the specified char value is white space.
public class Test{
public static void main(String args[]){ false
System.out.println(Character.isWhitespace('c')); true
System.out.println(Character.isWhitespace(' ')); true
System.out.println(Character.isWhitespace('\n')); true
System.out.println(Character.isWhitespace('\t'));
}
}
isUpperCase() :Determines whether the specified char value is uppercase.
public class Test{
public static void main(String args[]){ false
System.out.println( Character.isUpperCase('c')); true
System.out.println( Character.isUpperCase('C')); false
System.out.println( Character.isUpperCase('\n')); false
System.out.println( Character.isUpperCase('\t'));
}
}
isLowerCase() :Determines whether the specified char value is lowercase.
toUpperCase() :Returns the uppercase form of the specified char value.
toLowerCase() :Returns the lowercase form of the specified char value.
public class Test{
public static void main(String args[]){ c
System.out.println(Character.toLowerCase('c')); c
System.out.println(Character.toLowerCase('C'));
}
}
toString() :Returns a String object representing the specified character valuethat is, a
one-character string.
public class Test{
public static void main(String args[]){
c
System.out.println(Character.toString('c'));
C
System.out.println(Character.toString('C'));
}
}
Java - Strings Class
• Strings are widely used in programming. Most of the data in the world is in a form of string
• A string is a sequence of characters.
• In Java strings are immutable objects and therefore has it own methods and cannot be changed
in place
• The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
• Here the compiler creates a String object with its value in this case, "Hello world!'.
• As with any other object, you can create String objects by using the new keyword and a
constructor.
• The String class has a number constructors that allow you to provide the initial value of the
string using different sources, such as an array of characters.
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray); // Using the constructor
System.out.println( helloString );
}
}
String Length:
• Methods used to obtain information about an object are known as accessor methods.
• String has an accessor length() method thatreturns the number of characters in the string.
Example use of length()
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in:
"My name is ".concat("James Okongo");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!" which results in: "Hello, world!"
Let us look at the following example:
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Creating Format Strings:
• You can use printf() and format() methods to print output with formatted numbers.
• The String class has an equivalent class method, format(), that returns a String object rather
than a PrintStream object.
• Using String's static format() method allows you to create a formatted string that you can reuse,
as opposed to a one-time print statement. For example, instead of:
System.out.printf("The value of the float variable is %f, while the value of the
integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
you can write:
String fs;
fs = String.format("The value of the float variable is %f, while the value of the
integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Methods:
Here is the list of methods supported by String class and examples to illustrate
Methods , Description and Examples OUTPUT
String concat(String str): Concatenates the specified string to the end of this string.
String s = "Strings are immutable"; Strings are immutable
s = s.concat(" all the time"); all the time
System.out.println(s);
• public int indexOf(int ch): Returns the index within this string of the first occurrence of
the specified character or -1 if the character does not occur.
• 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 or -1 if the
character does not occur.
• int indexOf(String str): Returns the index within this string of the first occurrence of the
specified substring. If it does not occur as a substring, -1 is returned.
• int indexOf(String str, int fromIndex): Returns the index within this string of the
first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is
returned.
String Str1 = new String("Welcome to Java Strings Class Training");
String SubStr1 = new String("Class");
String SubStr2 = new String("Tutorial");
System.out.print("Found Index :" ); Found Index :4
System.out.println(Str.indexOf( 'o' )); Found Index :9
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o', 5 ));
Found Index :11
System.out.print("Found Index :" ); Found Index :-1
System.out.println( Str.indexOf( SubStr1 )); Found Index :-1
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1, 15 ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( SubStr2 ));
•int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified
character or -1 if the character does not occur.
• public int lastIndexOf(int ch, int fromIndex): Returns the index of the last occurrence of the
character in the character sequence represented by this object that is less than or equal to
fromIndex, or -1 if the character does not occur before that point.
• public int lastIndexOf(String str): If the string argument occurs one or more times as a substring
within this object, then it returns the index of the first character of the last such substring is
returned. If it does not occur as a substring, -1 is returned.
• public int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the specified index.
String Str1 = new String("Welcome to Java Strings Class Training");
String SubStr1 = new String("Class" );
String SubStr2 = new String("Training" );
System.out.print("Found Last Index :" ); Found Last Index :27
System.out.println(Str.lastIndexOf( 'o' )); Found Last Index :4
System.out.print("Found Last Index :" ); Found Last Index :11
System.out.println(Str.lastIndexOf( 'o', 5 )); Found Last Index :……….
System.out.print("Found Last Index :" ); Found Last Index :…..
System.out.println( Str.lastIndexOf( SubStr1 ));
System.out.print("Found Last Index :" );
System.out.println( Str.lastIndexOf( SubStr1, 15 ));
System.out.print("Found Last Index :" );
System.out.println(Str.lastIndexOf( SubStr2 ));
boolean matches(String regex):Tells whether or not this string matches the given regex
String Str = new String("Welcome to Java Strings Class Training");
System.out.print("Return Value :" ); Return Value :true
System.out.println(Str.matches("(.*)Training(.*)")); Return Value :false
System.out.print("Return Value :" );
Return Value :true
System.out.println(Str.matches("Classes"));
System.out.print("Return Value :" );
System.out.println(Str.matches("Welcome(.*)"));
boolean regionMatches(boolean ignoreCase, int toffset, String other, int
ooffset, int len) :Tests if two string regions are equal.
Explanations:
• toffset -- the starting offset of the subregion in this string.
• other -- the string argument.
• ooffset -- the starting offset of the subregion in the string argument.
• len -- the number of characters to compare. Return Value :true
• ignoreCase -- if true, ignore case when comparing characters. Return Value :false
String Str = new String("Welcome to Java Strings Class Training"); Return Value :true
String Str2 = new String("Class");
String Str3 = new String("Training");
System.out.print("Return Value :" );
System.out.println(Str1.regionMatches(11, Str2, 0, 9));
System.out.print("Return Value :" );
System.out.println(Str1.regionMatches(11, Str3, 0, 9));
System.out.print("Return Value :" );
System.out.println(Str1.regionMatches(true, 11, Str3, 0, 9));
String replace(char oldChar, char newChar):Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.
String Str = new String("Welcome to Java Strings Class Training");
System.out.print("Return Value :" );
System.out.println(Str.replaceAll("(.*)Java(.*)","SCala" ));
String replaceAll(String regex, String replacement):Replaces each substring
of this string that matches the given regular expression with the given
replacement. What is the output?
String Str = new String("Welcome to Java Strings In Java Class");
System.out.print("Return Value :" );
System.out.println(Str.replaceAll("(.*)Java(.*)","Scala" ));
String[] split(String regex):Splits this string around matches of the given regular expression.
String[] split(String regex, int limit):Splits this string around matches of the given regular expression to the limit given
boolean startsWith(String prefix):Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset):Tests if this string starts with the specified prefix
beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex):Returns a new character sequence that is a subsequence of this
sequence.
String substring(int beginIndex):Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex):Returns a new string that is a substring of this
string.
String Str = new String("Welcome to Java Strings tutorial training"); What is the output?
System.out.print("Return Value :" );
System.out.println(Str.substring(10) );
System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
char[] toCharArray():Converts this string to a new character array. Give an Example!
String toLowerCase():Converts all of the characters in this String to lower case using the rules
Give an Example!
of the default locale.
String toLowerCase(Locale locale):Converts all of the characters in this String to lower case
Give an Example!
using the rules of the given Locale.
String toString():This object (which is already a string!) is itself returned. Give an Example!
String toUpperCase():Converts all of the characters in this String to upper case using the rules
Give an Example!
of the default locale.
String toUpperCase(Locale locale):Converts all of the characters in this String to upper case
Give an Example!
using the rules of the given Locale.
String trim():Returns a copy of the string, with leading and trailing whitespace omitted.
String Str=new String(" Welcome to Java Strings tutorial training ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
static String valueOf(primitive data type x):Returns the string representation of the
passed data type argument depending on the passed parameters
• valueOf(boolean b): Returns the string representation of the boolean argument.
• valueOf(char c): Returns the string representation of the char argument.
• valueOf(char[] data): Returns the string representation of the char array argument.
• valueOf(char[] data, int offset, int count): Returns the string representation of
a specific subarray of the char array argument.
• valueOf(double d): Returns the string representation of the double argument.
• valueOf(float f): Returns the string representation of the float argument.
• valueOf(int i): Returns the string representation of the int argument.
• valueOf(long l): Returns the string representation of the long argument.
• valueOf(Object obj): Returns the string representation of the Object argument.
double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };
System.out.println("Return Value : " + String.valueOf(d) );
System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) ); What is the outputs?
Exercise
1. Write A Program that receives a long string of text and then:
(a) Print the number of words in the string
(b) Print the longest word in the string.
(c) Print the number of non whit space characters in the string.
(d) Print the number of all characters in the string.
(e) Print the size of the string in bytes.
(f) Prompts the user for a string pattern and then returns the position in the string where the pattern start.
(g) Repeats f above but this time returns the number of time the pattern has been found in the text.
(h) Repeats f above but this time uppercase all the patterns as they are found in the text.
2. To improve password security in a network environment, a user account password should be at least 12 characters long,
have at least three uppercase characters and at least two digits. Write a java program that reads as an argument from the
command line and uses a function to validate it against the above rules.
3. Write a java program that prompts the user for the date of birth of a patient and the uses a function to return the age of
the patient.
4. Modify program 3 above such that it generate the date of births of 20 patients randomly, stores them into a string array.
The array is passed to a function that process the age of every patient printing them out.
5. Modify program 4 above such the randomly generated date of births of the 20 patients, are stored into the second
column of a 2 X 2 dimensional array that initially containing populated patients full names in the first column them into a
string array. The array is passed to a function that process the age of every patient printing them out against each name in a
tabular form in the format:
Full Name DoB Age
1.…........... …....... ….......
2.…........... …....... …........
3. ….......... …....... ….........