Chapter 4
Chapter 4
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];
Example
int mark[];
int[] total;
float average[];
int count[];
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.
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]
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};
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);
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.)
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,
is shorthand for
int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;
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.
The output is
0: 1001
1: 1002
2: 1003
3: 5
4: 7
5: 11
6: 13
This method uses a tuned version of the QuickSort algorithm that is claimed to be
very efficient on most data sets.
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
int [][]mark;
int mark[][];
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
x[1] x[1][3]
x[2] x[2][0]
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
substring(int beginIndex,
String int endIndex) Returns a new string that is a substring of this string.
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);
}
}
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
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):
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.
1) The most common method is a //. You use this for a comment that will run from the
// to the end of the line.
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
/**
* 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
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...
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.