0% found this document useful (0 votes)
13 views19 pages

Chapter 4

The document provides an overview of arrays, strings, and JavaDoc comments in Java programming. It explains how to declare, create, and initialize arrays, including one-dimensional and multi-dimensional arrays, as well as the use of the 'for each' loop for iterating through array elements. Additionally, it covers string manipulation, constructors, and methods associated with strings in Java.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

Chapter 4

The document provides an overview of arrays, strings, and JavaDoc comments in Java programming. It explains how to declare, create, and initialize arrays, including one-dimensional and multi-dimensional arrays, as well as the use of the 'for each' loop for iterating through array elements. Additionally, it covers string manipulation, constructors, and methods associated with strings in Java.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Arrays, Strings and JavaDoc Comments 4.

Arrays, String and JavaDoc Comments


Arrays
An array is a data structure that stores a collection of values of the same data type
that shares a common name; you can access each individual element value through an
integer index (or) sub script in brackets after the array.
In java, arrays and strings are handled as objects and memory is allocated using
new operator.
Example
To access the 3rd element in the array mark[] the following statement can be used.
mark[2]
The complete set of values is referred to as an array; the individual values are
called elements. Array can be of any variable type.
4.1 One Dimensional Array
A list of items can be given one variable name using only one subscript and such
a variable is called single- subscripted variable (or) a one dimensional array.
Example
X[0],X[1],x[2],x[3],x[4],………x[n]
The subscript also begin with number. That is
X[0]
To represent a set of five marks as (65,50,75,55,80) by an array variable number, then we
create the variable number as follows.
int mark[]=new int[5];
The computer reserves these five storage locations as shown below:
mark[0]
mark[1]
mark[2]
mark[3]
mark[4]
The values to the array elements can be assigned as follows.
mark[0]=65;
mark[1]=50;
mark[2]=75;
mark[3]=55;
mark[4]=80;
This would cause the array number to store the values.
mark[0] 65
mark[1] 50
mark[2] 75
mark[3] 55
mark[4] 80
4.2 Java Programming Paradigms

These elements may be used in programs just like any other java variables for
example, the following are valid state.
int total=mark[0]+ mark[1]+ mark[2]+ mark[3]+ mark[4];

4.1.1 Creating an Array


Like any other variables, arrays must be declared and created in the computer
memory before they are used. Creation of an array involves three steps:
1. Declaring the array
2. Creating memory locations
3. Putting values into the memory locations

4.1.2 Declaring an Array


An array can be declared by specifying the data type followed by [] with array
name. no memory space is allocated.
Syntax
datatype arrayname[];
(or)
datatype[] arrayname;

Example
int mark[];
int[] total;
float average[];
int count[];

4.1.3 Creating Memory Locations


Once the array is declared, we need to create in the memory. Java allows us to
create arrays using new operator only, as shown below.
Syntax
arrayname=new datatype[size];

Example
mark =new int[5];
average=new float[2];

These lines create necessary memory locations for the arrays number and average
by designate them as int and float respectively.
Now, the variable numbers refers to an array of 5th integer and average refers to
an array of 2nd floating points values.
Arrays, Strings and JavaDoc Comments 4.3

It is also possible to combine the two steps declaration and creation, into one
statement.

int number[]=new int[5];

Statement Result
mark

intintnumber[]; 
number[]; points
pointsno where
nowhere
Creating of an array in memory

Number = new int[5];
Points to int object
mark[0]
mark[1]
mark[2]
mark[3]
mark[4]

Figure 4.1 Creating of an array in memory

4.1.4 Initialization of Arrays


The final step is to put values into the array created. This process is known as
initialization. This is done using array subscripts as shown below:

arrayname[subscript]=value;

Example

mark[0]=65;
mark[1]=50;
mark[2]=75;
mark[3]=55;
mark[4]=80;

Note:
Java creates arrays starting with the subscript of 0(zero) and ends with a value one less
than the size specified.
4.4 Java Programming Paradigms

We can also initialize arrays automatically in the same way as ordinary variables
when they are declared as shown below.
datatype arrayname[]={list of values};

The array initializer is a list of values separated by commas and surrounded by


curly braces (note that no size is given). The compiler allocates enough space for all the
elements specified in the list.
int mark[]={65,50,75,55,80};

It is possible to assign an array object to another.


Example
int a[]={1,2,3};
int b[]= a;

b=a; are valid in java. Both the arrays will have the same values.
For loops may be used to initialize large size arrays.
Example
………………….

………………….

for(int i=0;i<100;i++)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
.........
.........

The first fifty elements of the array sum are initialized to zero while the remaining
is initialized to 1.0.
4.1.5 The "for each" Loop
JDK 5.0 introduces a powerful looping construct that allows you to loop through
each element in an array (as well as other collections of elements) without having to
trouble with index values.
The enhanced for loop
for (variable : collection) statement
Arrays, Strings and JavaDoc Comments 4.5

sets the given variable to each element of the collection and then executes the statement
(which, of course, may be a block). The collection expression must be an array or an
object of a class that implements the Iterable interface, such as ArrayList.
For example,
for (int element : a)
System.out.println(element);

prints each element of the array a on a separate line.


You should read this loop as "for each element in a". The designers of the Java
language considered using keywords such as foreach and in. But this loop was a late
addition to the Java language, and in the end nobody wanted to break old code that
already contains methods or variables with the same names (such as System.in).
Of course, you could achieve the same effect with a traditional for loop:
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);

However, the "for each" loop is more concise and less error prone. (You don't
have to worry about those pesky starts and end index values.)

4.1.6 Array Initializers and Anonymous Arrays


Java has shorthand to create an array object and supply initial values at the same
time. Here's an example of the syntax at work
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };

Notice that you do not call new when you use this syntax.
You can even initialize an anonymous array:
new int[] { 17, 19, 23, 29, 31, 37 }

This expression allocates a new array and fills it with the values inside the braces.
It counts the number of initial values and sets the array size accordingly. You can use this
syntax to reinitialize an array without creating a new variable. For example,

smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 }

is shorthand for
int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

4.1.7 Array Copying


You can copy one array variable into another, but then both variables refer to the
same array:
int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12; // now smallPrimes[5] is also 12
4.6 Java Programming Paradigms

Figure 4.2 shows copying an array variable and the result. If you actually want to
copy all values of one array into another, you use the arraycopy method in the System
class. The syntax for this call is
System.arraycopy(from, fromIndex, to, toIndex, count);

The two arrays must have sufficient space to hold the copied elements.
For example, the following statements, whose result is illustrated in figure 4.3 Copying
values between arrays, set up two arrays and then copy the last four entries of the first
array to the second array. The copy starts at position 2 in the source array and copies four
entries, starting at position 3 of the target.

Figure 4.2 Copying an array variable

Figure 4.3 Copying values between arrays

int[] smallPrimes = {2, 3, 5, 7, 11, 13};


int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
Arrays, Strings and JavaDoc Comments 4.7

System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 4);


for (int i = 0; i < luckyNumbers.length; i++)
System.out.println(i + ": " + luckyNumbers[i]);

The output is
0: 1001
1: 1002
2: 1003
3: 5
4: 7
5: 11
6: 13

4.1.8 Command-Line Parameters


You have already seen one example of Java arrays repeated quite a few times.
Every Java program has a main method with a String[] args parameter. This
parameter indicates that the main method receives an array of strings, namely, the
arguments specified on the command line.
For example, consider this program
public class Message
{
public static void main(String[] args)
{
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + a[i]);
System.out.println("!");
}
}
If the program is called as
java Message -g cruel world

then the args array has the following contents:


args[0]: "-g"
args[1]: "cruel"
args[2]: "world"

The program prints the message


Goodbye, cruel world!
4.8 Java Programming Paradigms

4.1.9 Array Sorting


To sort an array of numbers, you can use one of the sort methods in the Arrays
class:
int[] a = new int[10000];
. . .
Arrays.sort(a)

This method uses a tuned version of the QuickSort algorithm that is claimed to be
very efficient on most data sets.

4.1.10 Array Length


In java, all arrays store the allocated size in a variable named length. We can
obtain the length of the array a using a.length.
Example
int asize=a.length;

import java.util.*;
public class arraysort
{
public static void main(String[] args)
{
int mark[] = {65,50,75,55,80};
int l = mark.length;
int i,j,t;
System.out.print("Given marks : ");
for (i = 0;i < l;i++ )
{
System.out.print(" " + mark[i]);
}
System.out.println("\n");
System.out.print("Ascending order of the mark: ");
Arrays.sort(mark);
for(i = 0;i < l;i++)
{
System.out.print(" " + mark[i]);
}
}}
Program 4.1 Example for array sort
Output
E:\program\array>java arraysort
Given marks : 65 50 75 55 80
Ascending order of the mark: 50 55 65 75 80
Arrays, Strings and JavaDoc Comments 4.9

4.2 Multi-Dimensional Arrays


In Java, multidimensional arrays are actually arrays of arrays. This will look like
matrix (or) table which will have rows and column. These, as you might expect, look and
act like regular multidimensional arrays. However, as you will see, there are a couple of
subtle differences. To declare a multidimensional array variable, specify each additional
index using another set of square brackets as follows:
Declaring two dimensional array

int [][]mark;
int mark[][];

Creating two dimensional array

int mark[][]=new int[2][2];

This allocates a 2 by 2 array and assigns it to mark. Internally this matrix is


implemented as an array of arraysof int. Conceptually, this array will look like the one
shown in figure 4.4 below:
Initialization of two dimensional arrays
int mark[][]={{50,55},{65,75}};

And matrix will be viewed and represented as

Column 0 Column 1

[0],[0] [0],[1]
Row 0 50 55

[1,0] [1],[1]
Row 1 65 75
Figure 4.4 Representation of a Two Dimensional Array in Memory.
class TwoDArray
{
public static void main(String[] args)
{
int mark[][]={{50,55},{65,75}};
int i, j;
4.10 Java Programming Paradigms

// Array indices
/* - Print 2-dim array a - */
// Print elements in row i
for ( i = 0 ; i < mark.length ; i++ )
{
// Print column j in row i
for ( j = 0 ; j < mark[i].length ; j++ )
{
System.out.print( mark[i][j] + " " );
}
System.out.println();
}
}
}
Program 4.2 Example for two dimensional array
Output
E:\program\array>javac TwoDArray.java
E:\program\array>java TwoDArray
50 55
65 75

4.3 Ragged Array


Java has no multi-dimensional array at all; it has only one dimensional array.
Multidimensional arrays are represented as array of arrays.
It is also possible to make arrays by representing different row have different columns are
called ragged array.
By representing
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[3];
x[2]=new int[1];
The matrix will be represented as
x[0]  x[0][1]

x[1]  x[1][3]

x[2]  x[2][0]

Figure 4.5 Variable size arrays


Arrays, Strings and JavaDoc Comments 4.11

4.4 Strings
String is a sequence of character. Java library provides the string class to create
and manipulate strings. In Java, strings are class objects and implemented using two
classes, namely String and String Buffer. The String class implements immutable
character strings, which are read-only once the string object has been created and
initialized.

Creating String
Example
String s=”Java Program”;

String Constructor

Constructors Description
String() Initializes a newly created String object so that it
represents an empty character sequence.
String(char[] value) Allocates a new String so that it represents the sequence
of characters currently contained in the character array
argument.
String(char[] value, Allocates a new String that contains characters from a
int offset, int count) subarray of the character array argument.
String(int[] codePoints, Allocates a new String that contains characters from a
int offset, int count) subarray of the Unicode code point array argument.
Table 4.1 String Constructors

String Methods
Frequently used string methods are
Datatype Method Description
char charAt(int index) Returns the char value at the specified index.
int compareTo(String anotherString) Compares two strings lexicographically.
compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case
int
differences.
concat(String str) Concatenates the specified string to the end of this
String
string.
copyValueOf(char[] data) Returns a String that represents the character sequence
static String
in the array specified.
copyValueOf(char[] data, Returns a String that represents the character sequence
static String
int offset, int count) in the array specified.
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
4.12 Java Programming Paradigms

boolean equals(Object anObject) Compares this string to the specified object.


equalsIgnoreCase(String anotherS Compares this String to another String, ignoring case
boolean
tring) considerations.
getBytes() Encodes this String into a sequence of bytes using the
byte[] platform's default charset, storing the result into a new
byte array.
int hashCode() Returns a hash code for this string.
indexOf(int ch, int fromIndex) Returns the index within this string of the first
int occurrence of the specified character, starting the
search at the specified index.
int length() Returns the length of this string.
replace(char oldChar, Returns a new string resulting from replacing all
String
char newChar) occurrences of oldChar in this string with newChar.
split(String regex) Splits this string around matches of the given regular
String[]
expression.
startsWith(String prefix)
boolean Tests if this string starts with the specified prefix.

substring(int beginIndex,
String int endIndex) Returns a new string that is a substring of this string.

char[] toCharArray() Converts this string to a new character array.


toLowerCase() Converts all of the characters in this String to lower
String
case using the rules of the default locale.
toString() This object (which is already a string!) is itself
String
returned.
toUpperCase() Converts all of the characters in this String to upper
String
case using the rules of the default locale.
trim() Returns a copy of the string, with leading and trailing
String
whitespace omitted.
static String valueOf(char c) Returns the string representation of the char argument.
Table 4.2 String Methods

import java.lang.String.*;
class stringex
{
public static void main(String args[])
{
String s=new String("Java");
Arrays, Strings and JavaDoc Comments 4.13

System.out.println("String s="+s);
String s1=new String("program");
String ss1="Program";
System.out.println("String s1="+s1);
String con=s+s1;
System.out.println("concenated string of (s +s1)="+con);
String s3="project";
System.out.println("String s3="+s3);
String con1=s.concat(s3);
System.out.println("concenated string (s.concat(s3))="+con1);
System.out.println("To Lowercase of con is="+con.toLowerCase());
System.out.println("To UpperCase of con is="+con.toUpperCase());
System.out.println("To Trim string="+s.trim());
String sn=s.replace('J','L');
System.out.println("Replaced Strings="+sn);
System.out.println("s1.equals(ss1)="+s1.equals(ss1));
System.out.println("s1.equalsIgnoreCase(s2)="+s1.equalsIgnoreCase(ss1));
System.out.println("TheIndex of(a)="+con.indexOf('a'));
System.out.println("TheIndex of(a)="+con.indexOf('a',3));
System.out.println("The Length of con="+con.length());
byte ascii[]={74,65,86,65};
String byteascii = new String(ascii);
System.out.println("The character of ascii values are="+byteascii);
System.out.println("Character="+con.charAt(5));
System.out.println("substring="+con.substring(5));
System.out.println("substring from to="+con.substring(5,8));
StringBuilder ss2=new StringBuilder("javaprogram");
ss2.delete(4,11);
System.out.println("delete="+ss2);
}
}

Program 4.3 Example for string methods in java


Output
String s=Java
String s1=program
concenated string of (s +s1)=Javaprogram
String s3=project
concenated string (s.concat(s3))=Javaproject
To Lowercase of con is=javaprogram
To UpperCase of con is=JAVAPROGRAM
To Trim string=Java
4.14 Java Programming Paradigms

Replaced Strings=Lava
s1.equals(ss1)=false
s1.equalsIgnoreCase(s2)=true
TheIndex of(a)=1
TheIndex of(a)=3
The Length of con=11
The character of ascii values are=JAVA
Character=r
substring=rogram
substring from to=rog
delete=java

StringBuffer
StringBuffer is a mutable sequence of characters. It is like a String but the
contents of the StringBuffer can be modified after creation.
Method Description
capacity() Returns the current capacity of the String buffer.
length() Returns the length (character count) of this string buffer.
charAt(int index) The specified character of the sequence currently represented
by the string buffer, as indicated by the index argument, is
returned.
setCharAt(int index, The character at the specified index of this string buffer is set to
char ch) ch
toString() Converts to a string representing the data in this string buffer
insert(int offset, char Inserts the string representation of the char argument into this
c) string buffer.
delete(int start, int end) Removes the characters in a substring of this StringBuffer
replace(int start, int Replaces the characters in a substring of this StringBuffer with
end, String str) characters in the specified String.
reverse() The character sequence contained in this string buffer is
replaced by the reverse of the sequence.
append(String str) Appends the string to this string buffer.
setLength(int Sets the length of this String buffer.
newLength)
Table 4.3 StringBuffer Method

public class StringBufferFunctionsDemo


{
public static void main(String[] args)
{
// Examples of Creation of Strings
Arrays, Strings and JavaDoc Comments 4.15

StringBuffer strBuf1 = new StringBuffer("Bobby");


StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16
System.out.println("strBuf1 : " + strBuf1);
System.out.println("strBuf1 capacity : " + strBuf1.capacity());
System.out.println("strBuf2 capacity : " + strBuf2.capacity());
System.out.println("strBuf3 capacity : " + strBuf3.capacity());
System.out.println("strBuf1 length : " + strBuf1.length());
System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2));
// A StringIndexOutOfBoundsException is thrown if the index is not
valid.
strBuf1.setCharAt(1, 't');
System.out.println("strBuf1 after setCharAt 1 to t is : "
+ strBuf1);
System.out.println("strBuf1 toString() is : " + strBuf1.toString());
strBuf3.append("beginner-java-tutorial");
System.out.println("strBuf3 when appended with a String : "
+ strBuf3.toString());
strBuf3.insert(1, 'c');
System.out.println("strBuf3 when c is inserted at 1 : "
+ strBuf3.toString());
strBuf3.delete(1, 'c');
System.out.println("strBuf3 when c is deleted at 1 : "
+ strBuf3.toString());
strBuf3.reverse();
System.out.println("Reversed strBuf3 : " + strBuf3);
strBuf2.setLength(5);
strBuf2.append("jdbc-tutorial");
System.out.println("strBuf2 : " + strBuf2);
// We can clear a StringBuffer using the following line
strBuf2.setLength(0);
System.out.println("strBuf2 when cleared using setLength(0): "
+ strBuf2);
}
}
Program 4.4 Example for string buffer methods in java
Output
strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
4.16 Java Programming Paradigms

strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 : jdbc-tutorial
strBuf2 when cleared using setLength(0):

4.5 Documentation Comments

The JDK contains a very useful tool, called javadoc, that generates HTML
documentation from your source files. In fact, the on-line API documentation is simply
the result of running javadoc on the source code of the standard Java library.

Comments in Java, like comments in most programming languages, do not show


up in the executable program. Java has three ways of marking comments.

1) The most common method is a //. You use this for a comment that will run from the
// to the end of the line.

System.out.println("We will not use 'Hello, World!'"); // is this too cute?

2) When longer comments are needed, you can mark each line with a //
Example
//int k=10;
//int c=k+10;

3) You can use the /** and */ comment for multiple lines
/** this
is
example
for multiple line
*/

If you add comments that start with the special delimiter /** to your source code,
you too can easily produce professional-looking documentation. This is a very nice
scheme because it lets you keep your code and documentation in one place.
Arrays, Strings and JavaDoc Comments 4.17

A tag starts with an @, such as @author or @param. The first sentence of the
free-form text should be a summary statement. The javadoc utility automatically
generates summary pages that extract these sentences.

Comment Insertion
The javadoc utility extracts information for the following items:
 Packages
 Public classes and interfaces
 Public and protected methods
 Public and protected fields

Types of Comments
1 Class Comments
2 Method Comments
3 Field Comments
4 General Comments
5 Package and Overview Comments
6 Comment Extraction
Class Comments
The class comment must be placed after any import statements, directly before the class
definition.
Example
/** This is Example for class Passenger */
class Passenger
{
…….
…….
}

Method Comments
Each method comment must immediately precede the method that it describes. In
additionto the general-purpose tags, you can use the following tags:
 @param variable description
This tag adds an entry to the “parameters” section of the current method. The
description can span multiple lines and can use HTML tags. All @param tags for
one method must be kept together.
 @return description
This tag adds a “returns” section to the current method. The description can span
multiple lines and can use HTML tags.
 @throws class description
This tag adds a note that this method may throw an exception
4.18 Java Programming Paradigms

Here is an example of a method comment:


/**
* To calculate the total amount traveled by the customer.
* @param by x represents the no of passenger
* @return the totalamount
*/
int calculateAmount(int x)
{
noofPassenger=x;
int totalAmount=spare*noofPassenger;
return(totalAmount);
}
Field Comments
You only need to document public fields—generally that means static constants.
For example:

/**
* The leap year value
*/
public static final int leapyear = 366;
General Comments
The following tags can be used in class documentation comments:

 @author name
This tag makes an “author” entry. You can have multiple @author tags, one for
each author.
 @version text
This tag makes a “version” entry. The text can be any description of the current
version.
 @since text
This tag makes a “since” entry. The text can be any description of the version that
introduced this feature. For example, @since version 1.7.1
 @deprecated text
This tag adds a comment that the class, method, or variable should no longer be
used. The text should suggest a replacement. For example:
@deprecated Use <code>setVisible(true)</code> instead
 @see reference
This tag adds a hyperlink in the “see also” section. It can be used with both
classes and methods.
Arrays, Strings and JavaDoc Comments 4.19

Package and Overview Comments


Class, method, and variable comments directly into the Java source files, delimited by
/** . . . */ documentation comments. However, to generate package comments, you need
to add a separate file in each package directory. You have two choices:

1. Supply an HTML file named package.html. All text between the tags
<body>...</body> is extracted.
2. Supply a Java file named package-info.java. The file must contain an initial
Javadoccomment, delimited with /** and */, followed by a package statement. It
should contain no further code or comments.

Comment Extraction
Here, docDirectoryis the name of the directory where you want the HTML files to
go. Follows these steps:
1. Change to the directory that contains the source files you want to document.
2. Run the command
javadoc -d docDirectorynameOfPackage // for a single package.
Or
javadoc -d docDirectory nameOfPackage1 nameOfPackage2...

to document multiple packages.

Review Questions
Part-A(2 Marks)
1) List out the type of arrays.
2) How will you declare an array?
3) What is an array?
4) What is ragged array?
5) What is multidimensional array?
6) What is a string buffer class and how does it differs from string class?
7) List out four javadoc comments.

Part-B
1) Explain one dimensional array in Java.
2) Explain few string operations in Java. With example program.
3) Discuss java documentation comments.

You might also like