0% found this document useful (0 votes)
34 views29 pages

Java Training Handout Arrays - Methods-Strings

Uploaded by

awanjiku156
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views29 pages

Java Training Handout Arrays - Methods-Strings

Uploaded by

awanjiku156
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

In This is Handout

• 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

It is in such cases that arrays come in and very handy.

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

Consider the array myarr below


5 8 45 51 3 35 16 13 25 23 29

Qn What is the index of the following elements


1. 5
2. 35
3. 29
4. 13
Qn What is the length of the array

Advantage of Java Array


• Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
• Random access: We can get any data located at any index position.
Disadvantage of Java Array
• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in java.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array

Single Dimensional Array


• Declaring an Array
1. dataType[] arr; (or) Single Dimensional Array
2. dataType []arr; (or)
3. dataType arr[]; 5 8 45 51 3 35 16 13 25 23 29

Example
int[] ages; or int []ages; or int ages[];

• Instantiating of an Array in java


1. arr=new datatype[size];

Example
ages=new int[10];

Example1: Single dimensional array:


In this example we are going to declare, instantiate, initialize and traverse an array.
class ArrayExample1 {
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array element
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
}//End of main
}// End of Class

Example2: Single dimensional array; Working with loops:


In this example we are going to declare, instantiate, initialize and traverse an array.
class ArrayExample2{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation

//A for loop to populate the array


for(int j =0;j<a.length;j++){//length is the property of array
a[j]=j*3;
}
//Using a for loop to printing array element
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}//End of main
}// End of Class

Example3: Declaration, Instantiation and Initialization Array


We can declare, instantiate and initialize the java array together by:
class Example3{
public static void main(String args[]){
int a[]={33,3,4,5,44,61};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Example4: Array of Strings


We want to create an array containing the 7 units a student do in a semester.
class Example4{
public static void main(String args[]){
//declaration, instantiation and initialization
int []units={“CMT 301”,“CMT 310”,“CMT 311”,“CMT 312”,“CMT 304”,“CMT 303”,“CMT 305”};
//printing array
for(int i=0;i<units.length;i++)//length is the property of array
System.out.println(units[i]);
}
}

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..

Unit Code Unit Name Marks Grade


1………… …………… …….. ……...
2…………. ……………. …….. ………

Avg Marks ……… Avg Grade ……….

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;

Example5 of Multidimensional array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
class Example5{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{5,8,45,51},{3,55,16,13},{25,23,29,23}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" "); //printing the element along the row
}
System.out.println(); //printing a new line so that we can start prining the next row
}
} Sums
}
Qn7 Modify Example5 above to become Exercise5 such that the program 5 8 45 51
prints the sum of all the row values at the end of each row as indicated below. 3 35 16 13
25 23 29 23
Qn8 Modify Exercise6 above to become Exercise7 such that this time the 5 8 45 51
program prints out the sum of all the column values at the end of each column as
indicated below. 3 35 16 13
25 23 29 23
Qn9 Modify Exercise7 above to become Exercise8 such that this time the
program prints out the the column values sum and the row sums.

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.

Example5 : More Application of 2 D Arrays: Addition of 2 matrices


Let's see a simple example that adds two matrices.
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Java - Methods
A method is a collection of statements that are grouped together to perform an operation.
When you call the method the statements are executed.

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
}

The syntax shown above includes:


• modifier: It defines the access type of the method and it is optional to use.
• returnType: Method may return a value.
• nameOfMethod: This is the method name. The method signature consists of the method name
and the parameter list.
• Parameter List: The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
• method body: The method body defines what the method does with statements.
Example:
Here is a method called max(). It takes two parameters n1 and n2 and returns the maximum between
the two:
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

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.

public class CallingMethod{


method1(){}
method2(){}

methodn(){}

public static void main(String[] args) {


int x=45, y=67;
//Calling method sum

int s=sum(x,y);
System.out.println(“Sum is”+ sum);
}//End of main

public static int sum(int a, int b){


return a+b;
}//End of sum
othermethod1(){}
othermethod2(){}

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;
}
}

The void Keyword:


• The void keyword allows us to create methods which do not return a value. Here, in the
following example we're considering a void method RankPoints.
• Call to a void method must be a statement i.e. RankPoints(255.7);. It is a Java statement which
ends with a semicolon as shown below.
Example:
public class ExampleVoid {
public static void main(String[] args) {
RankPoints(255.7);// Calling the method. Note that it is a statement
}
// An example of a void method
public static void RankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}
else if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}

Passing Parameters by Value:


If a method requires some arguments, parameters must be passed in the same order as their respective
parameters in the method specification.
In java Parameters can only be passed by value . not call by reference is may be used in c++ and C
Passing Parameters by Value means calling a method with a parameter. Through this the argument
value is passed to the parameter.
Example:
The following program shows an example of passing parameter by value. The values of the arguments
remains the same even after the method invocation.
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a =" +a + " and b= " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now,Before and After swapping values will be same
here**:");
System.out.println("After swapping, a = " +a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a="+a+ " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a+ " b = " + b);
}
}

This would produce the following result:


Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

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;
}
}

This would produce the following result:


inimum Value = 6
inimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given same name but with
different parameters.

TASK : Methods , Overloaded Methods


1. Using method overloading write a program that can evaluate the area and perimeter of any
rectangle
2. Repeat question 1 above for the total surface area and volume of a cuboid.
3. You are required to write a program that output the volume of any sphere. How many methods
other than the main cab used to solve the problem?
Using Command-Line Arguments:
Sometimes you will want to pass information into a program when you run it.
This is accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's name on the
command line when it is executed. The arguments are stored as strings in the String array passed to
main( ).
Example:
The following program displays all of the command-line arguments that it is called with:
public class CommandLine {
public static void main(String args[]){
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +args[i]);
}
}
}
Try executing this program as shown here:
$java CommandLine this is a command line 200 -100
This would produce the following result:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Passing Array to method in java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Classes, Objects & Constructors
In object oriented programming,a program is made up objects that communicates together through a
technique refered to as message passing.
Object are created in a process called instantiation. An object is defined as an instance of a class.
instantiation is done using a method called constructor.

A class is a programming construct that specify the relevant properties and behvior of an object for the
problem being solved.

Remember how we use class Scanner.


Scanner scan=new Scanner(System.in);

Class Object Constructor Argument;


A constructor is a special type of a method that initializes an object when it is created. Constructors are
at the heart of OOP.

• 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 Using Constructors


import java.util.Scanner;
class Rectangle {
int width; int length;
// A constructor to initialize the class data members
Rectangle() {
width= 10;
length= 15;
}
//Parameterized constructor
Rectangle(int w,int l) {
width=w;
length=l;
}
}

//Class RectMain to implement the Rectangle class


public class RectMain {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
Rectangle r1 = new Rectangle(); //Creating an object r1 using constructor without parameters
System.out.println("The area of the rectangle is "+r1.width*r1.length);
System.out.println("Enter the width");
int wid=scan.nextInt();
System.out.println("Enter the length");
int len=scan.nextInt();
Rectangle r2 = new Rectangle(wid,len);//Object r2 using constructor with parameters
System.out.println("The area of the new rectangle is " +r2.width*r2.length);
}
}

The this keyword


this is a keyword in Java which is used to reference to the object of the current class, within an instance
method or a constructor. Using this you can refer the members of a class such as constructors, variables
and methods.
Note. The keyword this is used only within instance methods or constructors
In general the keyword this is used to -Differentiate the instance variables from local variables if
they have same names, within a constructor or a method.

Example: Referencing an instance variable


class Student{
int age;
Student(int age){
this.age=age;
}
}

Example: Explicit constructor invocation


With this keyword you can call one type of constructor( e.g parameterized constructor ) from within
another in a class.
It is known as explicit constructor invocation
class Student{
int age
Student(){
this(20);//explicit constructor invocation .
}
Student(int age){
this.age=age;
}
}

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");
}

public void print(){


//Local variable num
int num=20;
//Printing the local variable
System.out.println("value of local variable num is : "+num);
//Printing the instance variable
System.out.println("value of instance variable num is : "+this.num);
//Invoking the greet method of a class
this.greet();
}

public static void main(String[] args){


//Instantiating the class
This_Example obj1=new This_Example();
//Invoking the print method
obj1.print();
//Passing a new value to the num variable through parameterized constructor
This_Example obj2=new This_Example(30);
//Invoking the print method again
obj2.print();
}

}
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
}

double result =numbers[0];


for(int i = 1; i < numbers.length;i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
This would produce the following result:
The max value is 56.5
The max value is 3.0

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

The finalize( ) Method:


It is possible to define a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize( ), and it can be used to ensure that an object
terminates cleanly.
In most cases this is used when an object may have some resources open. This include resources such
as : Open Files, Open Network sockets of FIFOS.
A finalize() will be called to make sure that an open file owned by that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method.
The Java runtime calls that method whenever it is about to recycle an object of that class.
You specify inside the finalize() method, you will specify those actions that must be performed before
an object is destroyed.
The finalize( ) method has this general form:
protected void finalize(){
// finalization code here
file.close()
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its
class.

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

class Marks{ public String grading(){


int cat1, cat2; String gde;
int exam; if(exam>=70)
Marks(){// Constructor gde="A";
cat1=(int)Math.ceil(Math.random()*20); else
cat2=(int)Math.ceil(Math.random()*10); if(exam>=60)
exam=(int)Math.ceil(Math.random()*70); gde="B";
}//End of constructor else
public int getCat1(){ if(exam>=50)
return cat1; gde="C";
}//End of geCat1 else
public int getCat2(){ if(exam>=40)
return cat2; gde="D";
}//End of geCat2 else
public int getExam(){ gde="F";
return exam; return gde;
}//End of getExam }
}// End of Class Marks

public class MarksMain{


public static void main(String [] args){
Marks []mk=new Marks[7];// Marks for seven the seven subjects

// Populating the array


for(int i=0; j<mk.length; i++){
mk[i]= new Marks();// Calling the Marks constructor
}

// Processing the array


for(int j=0; j<mk.length; j++){
int tcats=mk[j].getCat1()+mk[j].getCat2();
int texam=tcats+mk[j].getExam();
String gde=mk[j].grading();
String out="\t"+mk[j].getCat1()+"\t"+mk[j].getCat2()+"\t"+tcats+"\t"+mk[j].getExam()+"\t"+texam+"\t"+gde;
System.out.format(" $10s %n",out);
}//End for loop

}//End of main
}//End of Class MarksMain
Example: A Method That receives an Array Of Objects

class Marks{ public String grading(){


int cat1, cat2; String gde;
int exam; if(exam>=70)
Marks(){// Constructor gde="A";
cat1=(int)Math.ceil(Math.random()*20); else
cat2=(int)Math.ceil(Math.random()*10); if(exam>=60)
exam=(int)Math.ceil(Math.random()*70); gde="B";
}//End of constructor else
public int getCat1(){ if(exam>=50)
return cat1; gde="C";
}//End of geCat1 else
public int getCat2(){ if(exam>=40)
return cat2; gde="D";
}//End of geCat2 else
public int getExam(){ gde="F";
return exam; return gde;
}//End of getExam }
}// End of Class Marks

public class MarksMain{


public static void main(String [] args){
Marks []mk=new Marks[7];// Marks for seven the seven subjects

// Populating the array


for(int i=0; j<mk.length; i++){
mk[i]= new Marks();// Calling the Marks constructor
}

// Calling the method to process the array


processMarks(mk);
}//End of main

// A method that receives an array of Marks


public static void processMarks( Marks [] marks){
for(int j=0; j<marks .length; j++){
int tcats=marks[j].getCat1()+marks[j].getCat2();
int texam=tcats+marks[j].getExam();
String gde=marks[j].grading();
String out="\t"+marks[j].getCat1()+"\t"+marks[j].getCat2()+"\t"+tcats+"\t"+marks[j].getExam()
+"\t"+texam+"\t"+gde;
System.out.format(" $10s %n",out);
}//End for loop
}
}//End of Class MarksMain
Example: A Method That Creates and Returns an Array Of Objects

class Marks{ public String grading(){


int cat1, cat2; String gde;
int exam; if(exam>=70)
Marks(){// Constructor gde="A";
cat1=(int)Math.ceil(Math.random()*20); else
cat2=(int)Math.ceil(Math.random()*10); if(exam>=60)
exam=(int)Math.ceil(Math.random()*70); gde="B";
}//End of constructor else
public int getCat1(){ if(exam>=50)
return cat1; gde="C";
}//End of geCat1 else
public int getCat2(){ if(exam>=40)
return cat2; gde="D";
}//End of geCat2 else
public int getExam(){ gde="F";
return exam; return gde;
}//End of getExam }
}// End of Class Marks

public class MarksMain{


static Marks []mks;// Declaring a an arra of marks.
public static void main(String [] args){

// Calling the createMarks( ) method


mks=createMarks( ) ;

// Calling the method to process the array


processMarks(mks);
}//End of main

// A method that receives an array of Marks


public static void processMarks( Marks [] marks){
for(int j=0; j<marks .length; j++){
int tcats=marks[j].getCat1()+marks[j].getCat2();
int texam=tcats+marks[j].getExam();
String gde=marks[j].grading();
String out="\t"+marks[j].getCat1()+"\t"+marks[j].getCat2()+"\t"+tcats+"\t"+marks[j].getExam()
+"\t"+texam+"\t"+gde;
System.out.format(" $10s %n",out);
}//End for loop
}//End of Method

// A method that creates and returns an array of Marks


public static Marks [] createMarks( ){
Marks []mk=new Marks[7];// Marks for seven the seven subjects
//Populating the array with marks onject
for(int i=0; j<mk.length; i++){
mk[i]= new Marks();/ / Calling the Marks constructor
}

return mk;
}//End for method createMarks

}//End of Class MarksMain


TASK:Methods & Array Of Object
Consider a cylinder of radius r, and height h. Given r and h one can always calculate the volume and total surface area of
the cylinder.
i. Write down the formula for calculating the volume of a cylinder.
ii. Write down the formula for calculating the total surface area of a cylinder.
Construct a class Cylinder with appropriate data members and method members ( Fully defined setter and getter) to enable
you to generate the volume and total surface area of a cylinder. Include a none parameterised constructor that initializes the
radius and height to a maximum of 5.6 and 11.8 cm respectively and are randomly generated. Include also a parameterised
constructor that makes the program flexible .

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:

Radius Height Volume S. Area

….... ….. …. ….

….... ….. …. ….

….... ….. …. ….

….... ….. …. ….

Sum of Volumes Sum of S. Areas


Java - Character Class
In development, we come across situations where we need to use objects instead of primitive data
types. In order to achieve this, Java provides wrapper class Character for primitive data type char.
The Character class offers a number of useful class (i.e., static) methods for manipulating characters.
You can create a Character object with the Character constructor:

Character ch = new Character('a');


or without a constructors as in
char ch = 'a';
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

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:

Escape Sequence Description


\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.

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);

static String copyValueOf(char[] data):Returns a String that represents the character


sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count):
char[] Str1 = {'h','e','l','l','o',' ','w','o','r','l','d'};
String Str2 = ""; Returned String: hello
Str2 = Str2.copyValueOf( Str1 ); world
System.out.println("Returned String: " + Str2); Returned String: llo wo
Str2 = Str2.copyValueOf( Str1, 2, 6 );
System.out.println("Returned String: " + Str2);
}
boolean endsWith(String suffix):Tests if this string ends with the suffix.
String Str = new String("This is really not immutable!!");
boolean retVal; Returned Value = true
retVal = Str.endsWith( "immutable!!" ); Returned Value = false
System.out.println("Returned Value = " + retVal );
retVal = Str.endsWith( "immu" );
System.out.println("Returned Value = " + retVal );
boolean equalsIgnoreCase(String anotherString):Compares this String to
another String, ignoring case considerations.
String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!"); Returned Value = true
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!"); Returned Value = true
boolean retVal; Returned Value = true
retVal = Str1.equals( Str2 );
System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("Returned Value = " + retVal );
retVal = Str1.equalsIgnoreCase( Str4 );
System.out.println("Returned Value = " + retVal );
byte getBytes():Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
String Str1 = new String("Welcome to Java Strings tutorial training");
try{ Returned Value
byte[] Str2 = Str1.getBytes(); [B@192d342
System.out.println("Returned Value " + Str2 ); Returned Value
Str2 = Str1.getBytes( "UTF-8" ); [B@15ff48b
System.out.println("Returned Value " + Str2 ); Returned Value
Str2 = Str1.getBytes( "ISO-8859-1" ); [B@1b90b39
System.out.println("Returned Value " + Str2 );
}catch( UnsupportedEncodingException e){
System.out.println("Unsupported character set");
}
//Note with interest the use of try and catch statements
int hashCode():Returns a hash code for this string wich is computed as: Hashcode for Str :
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 1186874997
Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^
indicates exponentiation. (The hash value of the empty string is zero.)
String Str1 = new String("Welcome to Java Strings tutorial training");
System.out.println("Hashcode for Str :" + Str.hashCode() );

• 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. ….......... …....... ….........

Average Age …........

You might also like