Monday 26 November 2012

Java Programming - Playing with Java

Java Programming - Playing with Java
Structure
3.1 Introduction
Objectives
3.2 Operators
3.3 Arithmetic Operators
3.3.1 Increment and Decrement operators
3.3.2 Comparison Operators
3.3.3 Logical Operators
3.3.4 Operator Precedence
Self Assessment Questions
3.4 Control Flow Statements
3.4.1 If-else statement
3.4.2 Switch Statement
3.4.3 ‗for‘ Loop
3.4.4 While Statement
3.4.5 ‗do….while‘ statement
3.4.6 ‗Break‘ statement
3.4.7 ‗Continue‘ Statement
Self Assessment Questions
3.5 Arrays
3.6 Summary
3.7 Terminal Questions
3.1 Introduction
There are many constructs in java to implement conditional execution for eg flow of a program can be controlled using the if construct. The if construct allows selective execution of statements depending on the value of the expressions associated with the if construct.Similarly repetitive tasks can be
Java Programming Unit 3
Sikkim Manipal University Page No. 28
done using for constructs which would be discussed in detail in the following subsections
Then sorting of data can done using arrays which represents a number of variables that occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All the elements in an array must be of the same data type.
Objectives
In this chapter, you will learn about the:
 Operators
 Control Statements
 Arrays
 Strings
3.2 Operators
3.3 Arithmetic Operators
The following arithmetic operations can be performed in Java
Op
Use
Meaning
+
op1+op2
Adds op1 and op2
-
op1-op2
Subtracts op2 from op1
*
op1*op2
Multiplies op1 and op2
/
op1/op2
Divides op1 by op2
%
op1 % op2
Computes the remainder of dividing op1 by op2
Java program to add two numbers and print the result
Java Programming Unit 3
Sikkim Manipal University Page No. 29
Figure 3.1
The compilation and running of the program is shown in figure 3.2
Figure 3.2
3.3.1 Increment and Decrement operators
The increment operator is ++ and decrement operator is –. This is used to add 1 to the value of a variable or subtract 1 from the value of a variable. These operators are placed either before the variable or after the variable name. The example below shows the use of these operators.
Java Programming Unit 3
Sikkim Manipal University Page No. 30
Figure 3.3
Figure 3.4
When the operator ++ is placed after the variable name, first assignment of the value of the variable takes place and then the value of the variable is incremented. This operation is also called post increment. Therefore the value of y1 will remain as 5 and the value of x1 will be 6.When the operator is placed before the variable, first increment of the variable takes place and then the assignment occurs. Hence the value x2 and y2 both will be 6. This operation is also called as pre increment. Similarly – – operator can be
Java Programming Unit 3
Sikkim Manipal University Page No. 31
used to perform post decrement and pre decrement operations. If there is no assignment and only the value of variable has to be incremented or decremented then placing the operator after or before does not matter.
3.3.2 Comparison Operators
Op
Meaning
Example
= =
Equal
op1 = = op2
!=
Not Equal
op1 != op2
<
Less than
op1 < op2
>
Greater than
op1 > op2
<=
Less than or equal
op1 <= op2
>=
Greater than or equal
op1 >= op2
3.3.3 Logical Operators
Op
Use
Return true if
&&
op1 && op2
If both are true
||
op1 || op2
If one is true
!
!op
Op is false
&
Op1 & op2
If both are true , always evaluates op1 and op2
|
Op1 | op2
If one is true, always evaluates op1 and op2
3.3.4 Operator Precedence
When more than one operator is used in an expression, Java has established operator precedence to determine the order in which the operators are evaluated. For example, consider the following expression.
Result=10+5*8-15/5
In the above expression multiplication and division operation have higher priority the addition and multiplication. Hence they are performed first.
Java Programming Unit 3
Sikkim Manipal University Page No. 32
After that the right hand side becomes 10+40-3.
Addition and subtraction has the same priority. When the operators are having the same priority, they are evaluated from left to right in the order they appear in the expression. Hence the value of the result will become 47. In general the following order is followed when evaluating an expression.
 Increment and decrement operations.
 Arithmetic operations.
 Comparisons.
 Logical operations.
 Assignment operations.
To change the order in which expressions are evaluated, parentheses are placed around the expressions that are to be evaluated first. When the parentheses are nested together, the expressions in the innermost parentheses are evaluated first. Parentheses also improve the readability of the expressions. When the operator precedence is not clear, parentheses can be used to avoid any confusion.
Examples
Figure 3.5
Java Programming Unit 3
Sikkim Manipal University Page No. 33
Self Assessment Questions
1. What is the use of Arithmetic Operator?
2. What are the different types of Comparison Operator?
3.4 Control Flow Statements
Following statements are used to control the flow of execution in a program.
1. Decision Making Statements\
 If-else statement
 Switch – case statement
2. Looping Statement
 For loop
 While loop
 Do-while loop
3. Other statement
 Break
 Continue
 Label
3.4.1 If-else statement
The if statement is Java's conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is any expression that returns a boolean value. The else clause is optional.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be executed. For example, consider the following:
Java Programming Unit 3
Sikkim Manipal University Page No. 34
Figure 3.6
Most often, the expression used to control the if will involve the relational operators. However, this is not technically necessary. It is possible to control the if using a single boolean variable, as shown in this code fragment:
boolean dataAvailable;
// ...
if (dataAvailable)
ProcessData();
else
waitForMoreData();
Remember, only one statement can appear directly after the if or the else. If you want to include more statements, you'll need to create a block, as in this fragment:
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
Java Programming Unit 3
Sikkim Manipal University Page No. 35
bytesAvailable -= n;
} else
waitForMoreData();
Here, both statements within the if block will execute if bytesAvailable is greater than zero. Some programmers find it convenient to include the curly braces when using the if, even when there is only one statement in each clause. This makes it easy to add another statement at a later date, and you don't have to worry about forgetting the braces. In fact, forgetting to define a block when one is needed is a common cause of errors. For example, consider the following code fragment:
int bytesAvailable;
// ...
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else
waitForMoreData();
bytesAvailable = n;
It seems clear that the statement bytesAvailable = n; was intended to be executed inside the else clause, because of the indentation level. However, as you recall, whitespace is insignificant to Java, and there is no way for the compiler to know what was intended. This code will compile without complaint, but it will behave incorrectly when run.
The preceding example is fixed in the code that follows:
int bytesAvailable;
// ...
Java Programming Unit 3
Sikkim Manipal University Page No. 36
if (bytesAvailable > 0) {
ProcessData();
bytesAvailable -= n;
} else {
waitForMoreData();
bytesAvailable = n;
}
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the ifelse-
if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. The final else acts as a
Java Programming Unit 3
Sikkim Manipal University Page No. 37
default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.
Here is a program that uses an if-else-if ladder to determine which season a particular month is in.
// Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[ ]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
Java Programming Unit 3
Sikkim Manipal University Page No. 38
You might want to experiment with this program before moving on. As you will find, no matter what value you give month, one and only one assignment statement within the ladder will be executed.
3.4.2 Switch Statement
The switch statement is Java's multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.
As such, it often provides a better alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the
Java Programming Unit 3
Sikkim Manipal University Page No. 39
expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of "jumping out" of the switch.
Example
Figure 3.7
The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple
Java Programming Unit 3
Sikkim Manipal University Page No. 40
cases without break statements between them. For example, consider the following program:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[ ]) {
for(int i=0; i<12 class="" data-blogger-escaped-..........="" data-blogger-escaped-.........="" data-blogger-escaped-........="" data-blogger-escaped-.......="" data-blogger-escaped-......="" data-blogger-escaped-.....="" data-blogger-escaped-...="" data-blogger-escaped-0:="" data-blogger-escaped-1.="" data-blogger-escaped-10="" data-blogger-escaped-1:="" data-blogger-escaped-1="" data-blogger-escaped-2.="" data-blogger-escaped-2:="" data-blogger-escaped-3.10="" data-blogger-escaped-3.11="" data-blogger-escaped-3.4.3="" data-blogger-escaped-3.4.4="" data-blogger-escaped-3.4.5="" data-blogger-escaped-3.8="" data-blogger-escaped-3.9="" data-blogger-escaped-3.="" data-blogger-escaped-3:="" data-blogger-escaped-3="" data-blogger-escaped-4.="" data-blogger-escaped-41="" data-blogger-escaped-42="" data-blogger-escaped-43="" data-blogger-escaped-44="" data-blogger-escaped-45="" data-blogger-escaped-46="" data-blogger-escaped-47="" data-blogger-escaped-4:="" data-blogger-escaped-5.="" data-blogger-escaped-5:="" data-blogger-escaped-5="" data-blogger-escaped-6:="" data-blogger-escaped-7:="" data-blogger-escaped-8:="" data-blogger-escaped-9:="" data-blogger-escaped-a="" data-blogger-escaped-above="" data-blogger-escaped-all.="" data-blogger-escaped-all="" data-blogger-escaped-allows="" data-blogger-escaped-always="" data-blogger-escaped-among="" data-blogger-escaped-an="" data-blogger-escaped-and="" data-blogger-escaped-another.="" data-blogger-escaped-any="" data-blogger-escaped-are="" data-blogger-escaped-args="" data-blogger-escaped-arise="" data-blogger-escaped-as="" data-blogger-escaped-at="" data-blogger-escaped-be="" data-blogger-escaped-because="" data-blogger-escaped-becomes="" data-blogger-escaped-begin="" data-blogger-escaped-beginning.="" data-blogger-escaped-being="" data-blogger-escaped-below="" data-blogger-escaped-between="" data-blogger-escaped-block="" data-blogger-escaped-body="" data-blogger-escaped-boolean="" data-blogger-escaped-bottom="" data-blogger-escaped-braces.="" data-blogger-escaped-braces="" data-blogger-escaped-break="" data-blogger-escaped-by="" data-blogger-escaped-called="" data-blogger-escaped-can="" data-blogger-escaped-case="" data-blogger-escaped-cases.="" data-blogger-escaped-cases="" data-blogger-escaped-char="" data-blogger-escaped-choice="" data-blogger-escaped-code="" data-blogger-escaped-coded="" data-blogger-escaped-common.="" data-blogger-escaped-compared="" data-blogger-escaped-compiler="" data-blogger-escaped-compiles="" data-blogger-escaped-condition="" data-blogger-escaped-conditional="" data-blogger-escaped-conflict="" data-blogger-escaped-conflicts="" data-blogger-escaped-consider="" data-blogger-escaped-constants.="" data-blogger-escaped-constants="" data-blogger-escaped-control="" data-blogger-escaped-controlling="" data-blogger-escaped-count="" data-blogger-escaped-course="" data-blogger-escaped-create="" data-blogger-escaped-curly="" data-blogger-escaped-default:="" data-blogger-escaped-defines="" data-blogger-escaped-depending="" data-blogger-escaped-desirable="" data-blogger-escaped-differs="" data-blogger-escaped-do-while.="" data-blogger-escaped-do-while="" data-blogger-escaped-do="" data-blogger-escaped-does="" data-blogger-escaped-each="" data-blogger-escaped-efficient="" data-blogger-escaped-elp="" data-blogger-escaped-enclosed="" data-blogger-escaped-end="" data-blogger-escaped-equality="" data-blogger-escaped-equivalent="" data-blogger-escaped-especially="" data-blogger-escaped-evaluate="" data-blogger-escaped-evaluates="" data-blogger-escaped-even="" data-blogger-escaped-example="" data-blogger-escaped-execute="" data-blogger-escaped-executed="" data-blogger-escaped-executes="" data-blogger-escaped-execution="" data-blogger-escaped-expression.="" data-blogger-escaped-expression="" data-blogger-escaped-expressions.="" data-blogger-escaped-false="" data-blogger-escaped-faster="" data-blogger-escaped-features="" data-blogger-escaped-figure="" data-blogger-escaped-first="" data-blogger-escaped-flower="" data-blogger-escaped-following="" data-blogger-escaped-follows="" data-blogger-escaped-for="" data-blogger-escaped-form:="" data-blogger-escaped-form="" data-blogger-escaped-fortunately="" data-blogger-escaped-fragment="" data-blogger-escaped-from="" data-blogger-escaped-fundamental="" data-blogger-escaped-general="" data-blogger-escaped-generates="" data-blogger-escaped-gives="" data-blogger-escaped-group="" data-blogger-escaped-has="" data-blogger-escaped-have="" data-blogger-escaped-help="" data-blogger-escaped-here:="" data-blogger-escaped-here="" data-blogger-escaped-hoose="" data-blogger-escaped-how="" data-blogger-escaped-however="" data-blogger-escaped-i="" data-blogger-escaped-identical="" data-blogger-escaped-if-elses.="" data-blogger-escaped-if="" data-blogger-escaped-ifs.="" data-blogger-escaped-immediately="" data-blogger-escaped-implements="" data-blogger-escaped-important="" data-blogger-escaped-in="" data-blogger-escaped-included="" data-blogger-escaped-increment="" data-blogger-escaped-initial="" data-blogger-escaped-initially="" data-blogger-escaped-inner="" data-blogger-escaped-inside="" data-blogger-escaped-insight="" data-blogger-escaped-inspect="" data-blogger-escaped-instruction="" data-blogger-escaped-int="" data-blogger-escaped-interesting="" data-blogger-escaped-into="" data-blogger-escaped-is="" data-blogger-escaped-it="" data-blogger-escaped-iteration="" data-blogger-escaped-iterationstatements:="" data-blogger-escaped-its="" data-blogger-escaped-j="" data-blogger-escaped-java.io.ioexception="" data-blogger-escaped-java="" data-blogger-escaped-jump="" data-blogger-escaped-just="" data-blogger-escaped-knowledge="" data-blogger-escaped-knows="" data-blogger-escaped-languages="" data-blogger-escaped-large="" data-blogger-escaped-last="" data-blogger-escaped-least="" data-blogger-escaped-less="" data-blogger-escaped-level.="" data-blogger-escaped-like="" data-blogger-escaped-line="" data-blogger-escaped-list="" data-blogger-escaped-logic="" data-blogger-escaped-long="" data-blogger-escaped-looks="" data-blogger-escaped-loop.="" data-blogger-escaped-loop="" data-blogger-escaped-looping="" data-blogger-escaped-loops:="" data-blogger-escaped-loops="" data-blogger-escaped-main="" data-blogger-escaped-manipal="" data-blogger-escaped-match="" data-blogger-escaped-may="" data-blogger-escaped-menu="" data-blogger-escaped-more="" data-blogger-escaped-most="" data-blogger-escaped-much="" data-blogger-escaped-multiple="" data-blogger-escaped-must="" data-blogger-escaped-n="" data-blogger-escaped-need="" data-blogger-escaped-nested.="" data-blogger-escaped-nested="" data-blogger-escaped-nests="" data-blogger-escaped-next="" data-blogger-escaped-no.="" data-blogger-escaped-no="" data-blogger-escaped-not="" data-blogger-escaped-note:="" data-blogger-escaped-numbers="" data-blogger-escaped-of="" data-blogger-escaped-on:="" data-blogger-escaped-on="" data-blogger-escaped-once.="" data-blogger-escaped-once="" data-blogger-escaped-one:="" data-blogger-escaped-one="" data-blogger-escaped-only="" data-blogger-escaped-or="" data-blogger-escaped-other="" data-blogger-escaped-otherwise="" data-blogger-escaped-outer="" data-blogger-escaped-output:="" data-blogger-escaped-output="" data-blogger-escaped-own="" data-blogger-escaped-page="" data-blogger-escaped-part="" data-blogger-escaped-particularly="" data-blogger-escaped-passes="" data-blogger-escaped-path="" data-blogger-escaped-perfectly="" data-blogger-escaped-point="" data-blogger-escaped-prints="" data-blogger-escaped-process="" data-blogger-escaped-produced="" data-blogger-escaped-program="" data-blogger-escaped-programming="" data-blogger-escaped-public="" data-blogger-escaped-rather="" data-blogger-escaped-repeat.="" data-blogger-escaped-repeated.="" data-blogger-escaped-repeats="" data-blogger-escaped-results="" data-blogger-escaped-run="" data-blogger-escaped-s="" data-blogger-escaped-same="" data-blogger-escaped-saw="" data-blogger-escaped-select="" data-blogger-escaped-selecting="" data-blogger-escaped-selection="" data-blogger-escaped-sequence="" data-blogger-escaped-set="" data-blogger-escaped-shown="" data-blogger-escaped-sikkim="" data-blogger-escaped-simple="" data-blogger-escaped-simply="" data-blogger-escaped-since="" data-blogger-escaped-single="" data-blogger-escaped-sometimes="" data-blogger-escaped-statement.="" data-blogger-escaped-statement1="" data-blogger-escaped-statement2="" data-blogger-escaped-statement="" data-blogger-escaped-statements="" data-blogger-escaped-static="" data-blogger-escaped-such="" data-blogger-escaped-summary="" data-blogger-escaped-supplies="" data-blogger-escaped-switch.="" data-blogger-escaped-switch="" data-blogger-escaped-system.in.read="" data-blogger-escaped-system.out.print="" data-blogger-escaped-system.out.println="" data-blogger-escaped-system="" data-blogger-escaped-table="" data-blogger-escaped-target="" data-blogger-escaped-terminates.="" data-blogger-escaped-termination="" data-blogger-escaped-test="" data-blogger-escaped-than="" data-blogger-escaped-that:="" data-blogger-escaped-that="" data-blogger-escaped-the="" data-blogger-escaped-then="" data-blogger-escaped-there="" data-blogger-escaped-therefore="" data-blogger-escaped-this="" data-blogger-escaped-those="" data-blogger-escaped-three="" data-blogger-escaped-throws="" data-blogger-escaped-times="" data-blogger-escaped-to="" data-blogger-escaped-tring="" data-blogger-escaped-true.="" data-blogger-escaped-true="" data-blogger-escaped-two="" data-blogger-escaped-type="" data-blogger-escaped-unit="" data-blogger-escaped-university="" data-blogger-escaped-unnecessary="" data-blogger-escaped-usage="" data-blogger-escaped-use="" data-blogger-escaped-useful="" data-blogger-escaped-using="" data-blogger-escaped-usually="" data-blogger-escaped-valid:="" data-blogger-escaped-value="" data-blogger-escaped-values.="" data-blogger-escaped-values="" data-blogger-escaped-variable="" data-blogger-escaped-very="" data-blogger-escaped-void="" data-blogger-escaped-want="" data-blogger-escaped-when="" data-blogger-escaped-whereas="" data-blogger-escaped-which="" data-blogger-escaped-while="" data-blogger-escaped-will="" data-blogger-escaped-with.="" data-blogger-escaped-with="" data-blogger-escaped-words="" data-blogger-escaped-works.="" data-blogger-escaped-would="" data-blogger-escaped-you="" data-blogger-escaped-zero=""> '5');
System.out.println("\\n");
switch(choice) {
case '1':
System.out.println("The if:\\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
Java Programming Unit 3
Sikkim Manipal University Page No. 48
case '2':
System.out.println("The switch:\\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
Java Programming Unit 3
Sikkim Manipal University Page No. 49
}
}
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
The do-while:
do {
statement;
} while (condition);
In the program, the do-while loop is used to verify that the user has entered a valid choice. If not, then the user is reprompted. Since the menu must be displayed at least once, the do-while is the perfect loop to accomplish this.
A few other points about this example: Notice that characters are read from the keyboard by calling System.in.read( ). This is one of Java's console input functions. Although Java's console I/O methods won't be discussed in detail until System.in.read( ) is used here to obtain the user's choice. It reads characters from standard input (returned as integers, which is why the return value was cast to char). By default, standard input is line buffered, so you must press ENTER before any characters that you type will be sent to your program.
Java Programming Unit 3
Sikkim Manipal University Page No. 50
Java's console input is quite limited and awkward to work with. Further, most real-world Java programs and applets will be graphical and window-based. For these reasons, not much use of console input has been made in this book. However, it is useful in this context. One other point: Because System.in.read( ) is being used, the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors.
3.4.6 ‘Break’ statement
By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[ ]) {
for(int i=0; i<100 class="" data-blogger-escaped--="" data-blogger-escaped-.charat="" data-blogger-escaped-0="" data-blogger-escaped-1.="" data-blogger-escaped-10.="" data-blogger-escaped-10="" data-blogger-escaped-12.="" data-blogger-escaped-12="" data-blogger-escaped-14="" data-blogger-escaped-16-bit="" data-blogger-escaped-16="" data-blogger-escaped-1="" data-blogger-escaped-2.="" data-blogger-escaped-22="" data-blogger-escaped-2="" data-blogger-escaped-3.4.7="" data-blogger-escaped-3.5="" data-blogger-escaped-3="" data-blogger-escaped-4="" data-blogger-escaped-51="" data-blogger-escaped-52="" data-blogger-escaped-53="" data-blogger-escaped-54="" data-blogger-escaped-55="" data-blogger-escaped-56="" data-blogger-escaped-57="" data-blogger-escaped-58="" data-blogger-escaped-59="" data-blogger-escaped-5="" data-blogger-escaped-60="" data-blogger-escaped-61="" data-blogger-escaped-62="" data-blogger-escaped-63="" data-blogger-escaped-64="" data-blogger-escaped-65="" data-blogger-escaped-66="" data-blogger-escaped-67="" data-blogger-escaped-68="" data-blogger-escaped-69="" data-blogger-escaped-6="" data-blogger-escaped-70="" data-blogger-escaped-7="" data-blogger-escaped-8-bit="" data-blogger-escaped-8="" data-blogger-escaped-9.="" data-blogger-escaped-99="" data-blogger-escaped-9="" data-blogger-escaped-:="" data-blogger-escaped-a-z.="" data-blogger-escaped-a-z="" data-blogger-escaped-a="" data-blogger-escaped-abc="" data-blogger-escaped-abcdef="" data-blogger-escaped-above="" data-blogger-escaped-access="" data-blogger-escaped-achieve="" data-blogger-escaped-action.="" data-blogger-escaped-add="" data-blogger-escaped-added="" data-blogger-escaped-addition="" data-blogger-escaped-after="" data-blogger-escaped-age="" data-blogger-escaped-all="" data-blogger-escaped-allocated="" data-blogger-escaped-allow="" data-blogger-escaped-allows="" data-blogger-escaped-also="" data-blogger-escaped-altered="" data-blogger-escaped-alternative="" data-blogger-escaped-although="" data-blogger-escaped-an="" data-blogger-escaped-and="" data-blogger-escaped-another.="" data-blogger-escaped-another="" data-blogger-escaped-any="" data-blogger-escaped-applied="" data-blogger-escaped-approach="" data-blogger-escaped-appropriately="" data-blogger-escaped-are="" data-blogger-escaped-args="" data-blogger-escaped-around.="" data-blogger-escaped-around="" data-blogger-escaped-array.="" data-blogger-escaped-array="" data-blogger-escaped-arrays="" data-blogger-escaped-as="" data-blogger-escaped-ascii="" data-blogger-escaped-asciichars="" data-blogger-escaped-assessment="" data-blogger-escaped-assigns="" data-blogger-escaped-assure="" data-blogger-escaped-at="" data-blogger-escaped-automatic="" data-blogger-escaped-automatically.="" data-blogger-escaped-automatically="" data-blogger-escaped-available.="" data-blogger-escaped-available="" data-blogger-escaped-b:="" data-blogger-escaped-b="" data-blogger-escaped-be="" data-blogger-escaped-because="" data-blogger-escaped-been="" data-blogger-escaped-before.="" data-blogger-escaped-begin="" data-blogger-escaped-beginning="" data-blogger-escaped-begins="" data-blogger-escaped-being="" data-blogger-escaped-belonging="" data-blogger-escaped-bits="" data-blogger-escaped-bject="" data-blogger-escaped-body="" data-blogger-escaped-boolean="" data-blogger-escaped-both="" data-blogger-escaped-box="" data-blogger-escaped-break="" data-blogger-escaped-buf="" data-blogger-escaped-built-in="" data-blogger-escaped-but="" data-blogger-escaped-by="" data-blogger-escaped-bypassed.="" data-blogger-escaped-byte-to-character="" data-blogger-escaped-byte-to-string="" data-blogger-escaped-byte="" data-blogger-escaped-bytes.="" data-blogger-escaped-bytes="" data-blogger-escaped-c="" data-blogger-escaped-call="" data-blogger-escaped-called.="" data-blogger-escaped-called="" data-blogger-escaped-calling="" data-blogger-escaped-calls="" data-blogger-escaped-can="" data-blogger-escaped-cannot="" data-blogger-escaped-care="" data-blogger-escaped-careful="" data-blogger-escaped-case-sensitive.to="" data-blogger-escaped-case.="" data-blogger-escaped-case="" data-blogger-escaped-cases="" data-blogger-escaped-cause="" data-blogger-escaped-causes="" data-blogger-escaped-cde.="" data-blogger-escaped-cde="" data-blogger-escaped-certain="" data-blogger-escaped-ch.="" data-blogger-escaped-ch="abc" data-blogger-escaped-chain="" data-blogger-escaped-change="" data-blogger-escaped-changeable="" data-blogger-escaped-changed.="" data-blogger-escaped-changed="" data-blogger-escaped-changethe="" data-blogger-escaped-chapter.="" data-blogger-escaped-char="" data-blogger-escaped-character-to-byte="" data-blogger-escaped-character="" data-blogger-escaped-characters.="" data-blogger-escaped-characters="" data-blogger-escaped-charat="" data-blogger-escaped-chars="" data-blogger-escaped-check="" data-blogger-escaped-clarity.="" data-blogger-escaped-class.="" data-blogger-escaped-class:="" data-blogger-escaped-classes="" data-blogger-escaped-closely="" data-blogger-escaped-code="" data-blogger-escaped-collection="" data-blogger-escaped-common="" data-blogger-escaped-companion="" data-blogger-escaped-compare="" data-blogger-escaped-compared="" data-blogger-escaped-compares="" data-blogger-escaped-comparison="" data-blogger-escaped-compiler="" data-blogger-escaped-complement="" data-blogger-escaped-complete.="" data-blogger-escaped-complete="" data-blogger-escaped-comprise="" data-blogger-escaped-concat="" data-blogger-escaped-concatenate="" data-blogger-escaped-concatenated="" data-blogger-escaped-concatenates="" data-blogger-escaped-concatenation="" data-blogger-escaped-conditional="" data-blogger-escaped-consider="" data-blogger-escaped-considers="" data-blogger-escaped-construct="" data-blogger-escaped-constructed="" data-blogger-escaped-constructor.="" data-blogger-escaped-constructor:="" data-blogger-escaped-constructor="" data-blogger-escaped-constructors.="" data-blogger-escaped-constructors:="" data-blogger-escaped-constructors="" data-blogger-escaped-constructs="" data-blogger-escaped-contain="" data-blogger-escaped-contains.="" data-blogger-escaped-contains="" data-blogger-escaped-contents="" data-blogger-escaped-contiguous="" data-blogger-escaped-continue.="" data-blogger-escaped-continue="" data-blogger-escaped-continues="" data-blogger-escaped-control="" data-blogger-escaped-controls="" data-blogger-escaped-convenience="" data-blogger-escaped-convenient.="" data-blogger-escaped-conversion="" data-blogger-escaped-conversions="" data-blogger-escaped-convert="" data-blogger-escaped-converted="" data-blogger-escaped-converts="" data-blogger-escaped-copied="" data-blogger-escaped-create.="" data-blogger-escaped-create="" data-blogger-escaped-created.="" data-blogger-escaped-created="" data-blogger-escaped-creates="" data-blogger-escaped-creating="" data-blogger-escaped-creation="" data-blogger-escaped-d="" data-blogger-escaped-data.="" data-blogger-escaped-data="" data-blogger-escaped-declare="" data-blogger-escaped-declared="" data-blogger-escaped-declaring="" data-blogger-escaped-default="" data-blogger-escaped-defined="" data-blogger-escaped-demo="" data-blogger-escaped-demonstrate="" data-blogger-escaped-demonstrates="" data-blogger-escaped-depth="" data-blogger-escaped-describe="" data-blogger-escaped-describes="" data-blogger-escaped-designed="" data-blogger-escaped-desired="" data-blogger-escaped-determine="" data-blogger-escaped-determines="" data-blogger-escaped-difference="" data-blogger-escaped-differences="" data-blogger-escaped-different="" data-blogger-escaped-dimensions="" data-blogger-escaped-directly="" data-blogger-escaped-displays="" data-blogger-escaped-distinguished="" data-blogger-escaped-do-while="" data-blogger-escaped-do.="" data-blogger-escaped-do="" data-blogger-escaped-does="" data-blogger-escaped-done="" data-blogger-escaped-double="" data-blogger-escaped-during="" data-blogger-escaped-e="" data-blogger-escaped-each="" data-blogger-escaped-earlier="" data-blogger-escaped-early="" data-blogger-escaped-easier="" data-blogger-escaped-easiest="" data-blogger-escaped-easy="" data-blogger-escaped-effect="" data-blogger-escaped-efficiently="" data-blogger-escaped-element="" data-blogger-escaped-elements.="" data-blogger-escaped-elements="" data-blogger-escaped-employ="" data-blogger-escaped-empty="" data-blogger-escaped-enclosing="" data-blogger-escaped-encoding="" data-blogger-escaped-end.="" data-blogger-escaped-end="" data-blogger-escaped-enough="" data-blogger-escaped-entire="" data-blogger-escaped-environment.="" data-blogger-escaped-environment="" data-blogger-escaped-equal="" data-blogger-escaped-equality="" data-blogger-escaped-equals="" data-blogger-escaped-equalsdemo="" data-blogger-escaped-equalsignorecase="" data-blogger-escaped-equivalent="" data-blogger-escaped-even.="" data-blogger-escaped-even="" data-blogger-escaped-every="" data-blogger-escaped-examine="" data-blogger-escaped-examined="" data-blogger-escaped-example:="" data-blogger-escaped-example="" data-blogger-escaped-examples="" data-blogger-escaped-exception="" data-blogger-escaped-existing="" data-blogger-escaped-expected.="" data-blogger-escaped-expected="" data-blogger-escaped-explicit="" data-blogger-escaped-explicitly="" data-blogger-escaped-exporting="" data-blogger-escaped-expression.="" data-blogger-escaped-expression="" data-blogger-escaped-expressions.="" data-blogger-escaped-expressions="" data-blogger-escaped-extended="" data-blogger-escaped-extract="" data-blogger-escaped-extracted="" data-blogger-escaped-extraction="" data-blogger-escaped-f="" data-blogger-escaped-false="" data-blogger-escaped-features="" data-blogger-escaped-file="" data-blogger-escaped-final="" data-blogger-escaped-first.="" data-blogger-escaped-first="" data-blogger-escaped-fixed="" data-blogger-escaped-following:="" data-blogger-escaped-following="" data-blogger-escaped-follows:="" data-blogger-escaped-for="" data-blogger-escaped-force="" data-blogger-escaped-form:="" data-blogger-escaped-form="" data-blogger-escaped-format="" data-blogger-escaped-formats="" data-blogger-escaped-forms="" data-blogger-escaped-found="" data-blogger-escaped-four:="" data-blogger-escaped-four="" data-blogger-escaped-fragment="" data-blogger-escaped-frequently="" data-blogger-escaped-from="" data-blogger-escaped-full="" data-blogger-escaped-fully="" data-blogger-escaped-function="" data-blogger-escaped-functions="" data-blogger-escaped-general="" data-blogger-escaped-generates="" data-blogger-escaped-get="" data-blogger-escaped-getbytes="" data-blogger-escaped-getchars="" data-blogger-escaped-getcharsdemo="" data-blogger-escaped-given="" data-blogger-escaped-goes="" data-blogger-escaped-goto="" data-blogger-escaped-h="" data-blogger-escaped-handle="" data-blogger-escaped-handling="" data-blogger-escaped-has="" data-blogger-escaped-have="" data-blogger-escaped-height="" data-blogger-escaped-here.="" data-blogger-escaped-here:="" data-blogger-escaped-here="" data-blogger-escaped-hold="" data-blogger-escaped-how="" data-blogger-escaped-however.="" data-blogger-escaped-however="" data-blogger-escaped-human-readable="" data-blogger-escaped-i:="" data-blogger-escaped-i="5;i<=0;i--);" data-blogger-escaped-if="" data-blogger-escaped-ignores="" data-blogger-escaped-illustrates="" data-blogger-escaped-imensions="" data-blogger-escaped-immutable="" data-blogger-escaped-implement="" data-blogger-escaped-implementation="" data-blogger-escaped-implemented="" data-blogger-escaped-implementing="" data-blogger-escaped-implements="" data-blogger-escaped-important="" data-blogger-escaped-in="" data-blogger-escaped-include="" data-blogger-escaped-includes="" data-blogger-escaped-increase="" data-blogger-escaped-index.="" data-blogger-escaped-index="" data-blogger-escaped-indexed="" data-blogger-escaped-indexes="" data-blogger-escaped-individual="" data-blogger-escaped-initial="" data-blogger-escaped-initialize="" data-blogger-escaped-initialized="" data-blogger-escaped-initializer="" data-blogger-escaped-initializes="" data-blogger-escaped-instance="" data-blogger-escaped-instances="" data-blogger-escaped-instead="" data-blogger-escaped-int="" data-blogger-escaped-integer="" data-blogger-escaped-integrated="" data-blogger-escaped-interchange.="" data-blogger-escaped-intermediate="" data-blogger-escaped-internet="" data-blogger-escaped-into="" data-blogger-escaped-invoked="" data-blogger-escaped-invoking="" data-blogger-escaped-is="" data-blogger-escaped-it.="" data-blogger-escaped-it="" data-blogger-escaped-iteration.="" data-blogger-escaped-iteration="" data-blogger-escaped-its="" data-blogger-escaped-java.lang.="" data-blogger-escaped-java="" data-blogger-escaped-just="" data-blogger-escaped-label="" data-blogger-escaped-language.="" data-blogger-escaped-languages="" data-blogger-escaped-large="" data-blogger-escaped-last="" data-blogger-escaped-later="" data-blogger-escaped-left="" data-blogger-escaped-length="" data-blogger-escaped-let="" data-blogger-escaped-letters="" data-blogger-escaped-letting="" data-blogger-escaped-like="" data-blogger-escaped-line:="" data-blogger-escaped-line="" data-blogger-escaped-lines.="" data-blogger-escaped-literal.="" data-blogger-escaped-literal="" data-blogger-escaped-literals="" data-blogger-escaped-location.="" data-blogger-escaped-location="" data-blogger-escaped-locations="" data-blogger-escaped-long="" data-blogger-escaped-longstr="" data-blogger-escaped-look="" data-blogger-escaped-loop.="" data-blogger-escaped-loop="" data-blogger-escaped-loops="" data-blogger-escaped-main="" data-blogger-escaped-make="" data-blogger-escaped-makestring="" data-blogger-escaped-making="" data-blogger-escaped-manipal="" data-blogger-escaped-many="" data-blogger-escaped-may="" data-blogger-escaped-mean="" data-blogger-escaped-means="" data-blogger-escaped-memory.="" data-blogger-escaped-memory="" data-blogger-escaped-method.="" data-blogger-escaped-method="" data-blogger-escaped-methods="" data-blogger-escaped-might="" data-blogger-escaped-mix="" data-blogger-escaped-modifiable="" data-blogger-escaped-modifications.="" data-blogger-escaped-modified="" data-blogger-escaped-more="" data-blogger-escaped-most="" data-blogger-escaped-multiple="" data-blogger-escaped-multiplication="" data-blogger-escaped-must="" data-blogger-escaped-name.="" data-blogger-escaped-name="" data-blogger-escaped-need="" data-blogger-escaped-needed.="" data-blogger-escaped-needs="" data-blogger-escaped-neither="" data-blogger-escaped-new="" data-blogger-escaped-newline.="" data-blogger-escaped-no.="" data-blogger-escaped-no="" data-blogger-escaped-nonnegative="" data-blogger-escaped-not="" data-blogger-escaped-now="" data-blogger-escaped-number="" data-blogger-escaped-numbers.="" data-blogger-escaped-numbers="new" data-blogger-escaped-numchars="" data-blogger-escaped-object.="" data-blogger-escaped-object="" data-blogger-escaped-objects.="" data-blogger-escaped-objects="" data-blogger-escaped-obtain.="" data-blogger-escaped-obtain="" data-blogger-escaped-occupy="" data-blogger-escaped-of="" data-blogger-escaped-offset="" data-blogger-escaped-old.="" data-blogger-escaped-on="" data-blogger-escaped-once="" data-blogger-escaped-one.="" data-blogger-escaped-one="" data-blogger-escaped-ones.="" data-blogger-escaped-ontinue="" data-blogger-escaped-oop="" data-blogger-escaped-operand="" data-blogger-escaped-operation.="" data-blogger-escaped-operations.="" data-blogger-escaped-operations="" data-blogger-escaped-operator.="" data-blogger-escaped-operator="" data-blogger-escaped-operators="" data-blogger-escaped-optimizations="" data-blogger-escaped-or="" data-blogger-escaped-order="" data-blogger-escaped-original="" data-blogger-escaped-other="" data-blogger-escaped-otherwise.="" data-blogger-escaped-output:="" data-blogger-escaped-output="" data-blogger-escaped-overloaded="" data-blogger-escaped-override="" data-blogger-escaped-overriding="" data-blogger-escaped-own="" data-blogger-escaped-page="" data-blogger-escaped-parentheses="" data-blogger-escaped-part="" data-blogger-escaped-particular="" data-blogger-escaped-passed="" data-blogger-escaped-past="" data-blogger-escaped-perform="" data-blogger-escaped-performance="" data-blogger-escaped-performs="" data-blogger-escaped-pieces="" data-blogger-escaped-place="" data-blogger-escaped-platform.="" data-blogger-escaped-point:="" data-blogger-escaped-point="" data-blogger-escaped-portion="" data-blogger-escaped-possible="" data-blogger-escaped-practical="" data-blogger-escaped-precedence="" data-blogger-escaped-prevent="" data-blogger-escaped-prevents="" data-blogger-escaped-print="" data-blogger-escaped-printed="" data-blogger-escaped-printing="" data-blogger-escaped-println="" data-blogger-escaped-prints="" data-blogger-escaped-probably="" data-blogger-escaped-processing="" data-blogger-escaped-produced="" data-blogger-escaped-producing="" data-blogger-escaped-program:="" data-blogger-escaped-program="" data-blogger-escaped-programmer="" data-blogger-escaped-programming="" data-blogger-escaped-programs="" data-blogger-escaped-protocols="" data-blogger-escaped-provide="" data-blogger-escaped-provided="" data-blogger-escaped-provides="" data-blogger-escaped-public="" data-blogger-escaped-questions="" data-blogger-escaped-quoted="" data-blogger-escaped-rather="" data-blogger-escaped-receive="" data-blogger-escaped-refer="" data-blogger-escaped-reference="" data-blogger-escaped-referenced="" data-blogger-escaped-referred="" data-blogger-escaped-remainder="" data-blogger-escaped-represent="" data-blogger-escaped-representation.="" data-blogger-escaped-representation="" data-blogger-escaped-representations.fortunately="" data-blogger-escaped-represents="" data-blogger-escaped-restriction.="" data-blogger-escaped-result.="" data-blogger-escaped-result="" data-blogger-escaped-resulting="" data-blogger-escaped-results.="" data-blogger-escaped-return="" data-blogger-escaped-returns="" data-blogger-escaped-rule="" data-blogger-escaped-run="" data-blogger-escaped-running="" data-blogger-escaped-s.getchars="" data-blogger-escaped-s.length="" data-blogger-escaped-s1="" data-blogger-escaped-s2="" data-blogger-escaped-s3="Good-bye" data-blogger-escaped-s4="HELLO" data-blogger-escaped-s:="" data-blogger-escaped-s="This is a demo of the getChars method." data-blogger-escaped-same="" data-blogger-escaped-say="" data-blogger-escaped-search="" data-blogger-escaped-second="" data-blogger-escaped-see="" data-blogger-escaped-seem="" data-blogger-escaped-seldom="" data-blogger-escaped-self="" data-blogger-escaped-sequence="" data-blogger-escaped-series="" data-blogger-escaped-serious="" data-blogger-escaped-set.="" data-blogger-escaped-set="" data-blogger-escaped-several="" data-blogger-escaped-showed="" data-blogger-escaped-shown="" data-blogger-escaped-shows.="" data-blogger-escaped-sikkim="" data-blogger-escaped-simple="" data-blogger-escaped-simplest="" data-blogger-escaped-simply="" data-blogger-escaped-since="" data-blogger-escaped-single="" data-blogger-escaped-slightly="" data-blogger-escaped-smaller="" data-blogger-escaped-so="" data-blogger-escaped-some="" data-blogger-escaped-sometimes="" data-blogger-escaped-somewhat="" data-blogger-escaped-source="" data-blogger-escaped-sourceend="" data-blogger-escaped-sourcestart="" data-blogger-escaped-spaces="" data-blogger-escaped-special="" data-blogger-escaped-specified="" data-blogger-escaped-specifies="" data-blogger-escaped-specify="" data-blogger-escaped-start="" data-blogger-escaped-startindex="" data-blogger-escaped-statement:="" data-blogger-escaped-statement="" data-blogger-escaped-statements="" data-blogger-escaped-static="" data-blogger-escaped-still="" data-blogger-escaped-stop="" data-blogger-escaped-store="" data-blogger-escaped-stores="" data-blogger-escaped-str="" data-blogger-escaped-string.="" data-blogger-escaped-string="" data-blogger-escaped-stringbuffer="" data-blogger-escaped-strings.="" data-blogger-escaped-strings:="" data-blogger-escaped-strings="" data-blogger-escaped-strobj="" data-blogger-escaped-subclassed.="" data-blogger-escaped-subrange.="" data-blogger-escaped-subrange="" data-blogger-escaped-subscript="" data-blogger-escaped-subset="" data-blogger-escaped-substring.="" data-blogger-escaped-substring="" data-blogger-escaped-substringcons="" data-blogger-escaped-substrings="" data-blogger-escaped-such="" data-blogger-escaped-sufficient.="" data-blogger-escaped-support="" data-blogger-escaped-supports="" data-blogger-escaped-surprising="" data-blogger-escaped-syntax="" data-blogger-escaped-system.out.print="" data-blogger-escaped-system.out.println="" data-blogger-escaped-table="" data-blogger-escaped-take="" data-blogger-escaped-taken="" data-blogger-escaped-target.="" data-blogger-escaped-target="" data-blogger-escaped-targetstart.="" data-blogger-escaped-targetstart="" data-blogger-escaped-ten="" data-blogger-escaped-terminate="" data-blogger-escaped-text="" data-blogger-escaped-than="" data-blogger-escaped-that="" data-blogger-escaped-the="" data-blogger-escaped-their="" data-blogger-escaped-them.="" data-blogger-escaped-them="" data-blogger-escaped-then="" data-blogger-escaped-there="" data-blogger-escaped-these="" data-blogger-escaped-they="" data-blogger-escaped-this.="" data-blogger-escaped-this:="" data-blogger-escaped-this="" data-blogger-escaped-those="" data-blogger-escaped-though="" data-blogger-escaped-three="" data-blogger-escaped-through="" data-blogger-escaped-thus="" data-blogger-escaped-time.="" data-blogger-escaped-time="" data-blogger-escaped-to="" data-blogger-escaped-tochararray="" data-blogger-escaped-together="" data-blogger-escaped-too="" data-blogger-escaped-tostring="" data-blogger-escaped-tostringdemo="" data-blogger-escaped-transferred="" data-blogger-escaped-triangular="" data-blogger-escaped-tring="" data-blogger-escaped-true="" data-blogger-escaped-two="" data-blogger-escaped-type.="" data-blogger-escaped-type="" data-blogger-escaped-types="" data-blogger-escaped-typical="" data-blogger-escaped-unchangeable="" data-blogger-escaped-unchanged.="" data-blogger-escaped-unexpectedly="" data-blogger-escaped-unicode="" data-blogger-escaped-unit="" data-blogger-escaped-university="" data-blogger-escaped-unlike="" data-blogger-escaped-use.="" data-blogger-escaped-use="" data-blogger-escaped-used="" data-blogger-escaped-useful="" data-blogger-escaped-uses="" data-blogger-escaped-using="" data-blogger-escaped-v="" data-blogger-escaped-value="" data-blogger-escaped-valueof="" data-blogger-escaped-values.="" data-blogger-escaped-variable="" data-blogger-escaped-variablename="" data-blogger-escaped-variables.="" data-blogger-escaped-variables="" data-blogger-escaped-variety="" data-blogger-escaped-version="" data-blogger-escaped-versions="" data-blogger-escaped-very="" data-blogger-escaped-via="" data-blogger-escaped-void="" data-blogger-escaped-w="" data-blogger-escaped-want="" data-blogger-escaped-way="" data-blogger-escaped-ways="" data-blogger-escaped-we="" data-blogger-escaped-were="" data-blogger-escaped-what="" data-blogger-escaped-when="" data-blogger-escaped-whenever="" data-blogger-escaped-where="" data-blogger-escaped-which="" data-blogger-escaped-while="" data-blogger-escaped-whose="" data-blogger-escaped-why.="" data-blogger-escaped-width="" data-blogger-escaped-will="" data-blogger-escaped-with="" data-blogger-escaped-within="" data-blogger-escaped-without="" data-blogger-escaped-would="" data-blogger-escaped-wrap="" data-blogger-escaped-wrapped="" data-blogger-escaped-years="" data-blogger-escaped-you="" data-blogger-escaped-your="" data-blogger-escaped-zero.=""> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore case in such comparisons. Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) For both versions, startIndex specifies the index at which the region begins within the invoking String object. The String being compared is specified by str2. The index at which the comparison will start within str2 is specified by str2StartIndex. The
Java Programming Unit 3
Sikkim Manipal University Page No. 67
length of the substring being compared is passed in numChars. In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is significant.
startsWith( ) and endsWith( )
String defines two routines that are, more or less, specialized forms of regionMatches( ). The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string. They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is returned. For example,
"Foobar".endsWith("bar")
and "Foobar".startsWith("Foo")
are both true.
A second form of startsWith( ), shown here, lets you specify a starting point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the invoking string at which point the search will begin. For example,
"Foobar".startsWith("bar", 3)
returns true.
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares
Java Programming Unit 3
Sikkim Manipal University Page No. 68
two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[ ]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding
example:
Hello equals Hello -> true
Hello == Hello -> false
compareTo( )
Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose. It has this general form:
Java Programming Unit 3
Sikkim Manipal University Page No. 69
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here:
Searching Strings
The String class provides two methods that allow you to search a string for a specified character or substring:
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or –1 on failure.
To search for the first occurrence of a character, use int indexOf(int ch)
To search for the last occurrence of a character, use
int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the substring.
You can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Java Programming Unit 3
Sikkim Manipal University Page No. 70
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of Strings:
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}
Java Programming Unit 3
Sikkim Manipal University Page No. 71
Here is the output of this program:
Now is the time for all good men to come to the aid of their
country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String
Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.
substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending index of the substring:
String substring(int startIndex, int endIndex)
Java Programming Unit 3
Sikkim Manipal University Page No. 72
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
The following program uses substring( ) to replace all instances of one substring with
another within a string:
// Substring replacement.
class StringReplace {
public static void main(String args[ ]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
The output from this program is shown here:
This is a test. This is, too.
Java Programming Unit 3
Sikkim Manipal University Page No. 73
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.
concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example,
String s1 = "one";
String s2 = s1.concat("two");
puts the string "onetwo" into s2. It generates the same result as the following sequence:
String s1 = "one";
String s2 = s1 + "two";
replace( )
The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string "Hewwo" into s.
Java Programming Unit 3
Sikkim Manipal University Page No. 74
trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form:
String trim( )
Here is an example:
String s = " Hello World ".trim();
This puts the string "Hello World" into s.
The trim( ) method is quite useful when you process user commands. For example, the following program prompts the user for the name of a state and then displays that state's capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.
// Using trim() to process commands.
import java.io.*;
class UseTrim {
public static void main(String args[ ])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace
if(str.equals("Illinois"))
Java Programming Unit 3
Sikkim Manipal University Page No. 75
System.out.println("Capital is Springfield.");
else if(str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if(str.equals("California"))
System.out.println("Capital is Sacramento.");
else if(str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while(!str.equals("stop"));
}
}
Data Conversion Using valueOf( )
The valueOf( ) method converts data from its internal format into a human-readable form. It is a static method that is overloaded within String for all of Java's built-in types, so that each type can be converted properly into a string. valueOf( ) is also overloaded for type Object, so an object of any class type you create can also be used as an argument. (Recall that Object is a superclass for all classes.) Here are a few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
As we discussed earlier, valueOf( ) is called when a string representation of some other type of data is needed—for example, during concatenation operations. You can call this method directly with any data type and get a reasonable String representation. All of the simple types are converted to their common String representation. Any object that you pass to valueOf( )
Java Programming Unit 3
Sikkim Manipal University Page No. 76
will return the result of a call to the object's toString( ) method. In fact, you could just call toString( ) directly and get the same result. For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it is an array of some type. For arrays of char, however, a String object is created that contains the characters in the char array. There is a special version of valueOf( ) that allows you to specify a subset of a char array. It has this general form:
static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters, startIndex is the index into the array of characters at which the desired substring begins, and numChars specifies the length of the substring.
Changing the Case of Characters Within a String
The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected. Here are the general forms of these methods:
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that contains the uppercase or lowercase equivalent of the invoking String.
Here is an example that uses toLowerCase( ) and toUpperCase( ):
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[ ])
{
Java Programming Unit 3
Sikkim Manipal University Page No. 77
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
The output produced by the program is shown here:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
StrngBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings. As you know, String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and writeable character sequences.
StringBuffer may have characters and substrings inserted in the middle or appended to the end. StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. Java uses both classes heavily, but many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
Java Programming Unit 3
Sikkim Manipal University Page No. 78
The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.
length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following general forms:
int length( )
int capacity( )
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[ ]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
Java Programming Unit 3
Sikkim Manipal University Page No. 79
Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.
ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form:
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
setLength( )
To set the length of the buffer within a StringBuffer object, use setLength(). Its general form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative.
When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to shorten a StringBuffer.
Java Programming Unit 3
Sikkim Manipal University Page No. 80
charAt( ) and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ).
Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For setCharAt(), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.
The following example demonstrates charAt( ) and setCharAt( ):
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[ ]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
Here is the output generated by this program:
buffer before = Hello
charAt(1) before = e
Java Programming Unit 3
Sikkim Manipal University Page No. 81
buffer after = Hi
charAt(1) after = i
getChars( )
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. This means that the substring contains the characters from sourceStart through sourceEnd–1. The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart. Care must be taken to assure that the target array is large enough to hold the number of characters in the specified substring.
append( )
The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ). This allows subsequent calls to be chained together, as shown in the following example:
// Demonstrate append().
class appendDemo {
Java Programming Unit 3
Sikkim Manipal University Page No. 82
public static void main(String args[ ]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
The output of this example is shown here:
a = 42!
The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance. Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String. All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer? The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable. Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers. Actually, many programmers will never feel the need to use StringBuffer directly and will be able to express most operations in terms of the + operator on String variables.
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of
Java Programming Unit 3
Sikkim Manipal University Page No. 83
the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object.
The following sample program inserts "like" between "I" and "Java":
// Demonstrate insert().
class insertDemo {
public static void main(String args[ ]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
The output of this example is shown here:
I like Java!
reverse( )
You can reverse the characters within a StringBuffer object using reverse(), shown here:
StringBuffer reverse( )
This method returns the reversed object on which it was called. The following program demonstrates reverse( ):
// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
public static void main(String args[ ]) {
Java Programming Unit 3
Sikkim Manipal University Page No. 84
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Here is the output produced by the program:
abcdef
fedcba
delete( ) and deleteCharAt( )
Java 2 adds to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ). These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[ ]) {
Java Programming Unit 3
Sikkim Manipal University Page No. 85
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
replace( )
Another new method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus,the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.
The following program demonstrates replace( ):
// Demonstrate replace()
class replaceDemo {
public static void main(String args[ ]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
Java Programming Unit 3
Sikkim Manipal University Page No. 86
System.out.println("After replace: " + sb);
}
}
Here is the output:
After replace: This was a test.
Substring( )
Java 2 also adds the substring( ) method, which returns a portion of a StringBuffer. It has the following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
The first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. The second form returns the substring that starts at startIndex and runs through endIndex–1. These methods work just like those defined for String that were described earlier.
3.6 Summary
 Implementing Conditional Execution
You can control the flow of a program using the if construct. The if construct allows selective execution of statements depending on the value of the expressions associated with the if construct.
 Performing Repetitive Tasks Using Loop Construct
You can perform repetitive tasks by making use of the for construct.
 Storing Data in Arrays
An array represents a number of variables that occupy contiguous spaces in the memory. Each element in the array is distinguished by its index. All the elements in an array must be of the same data type.
Java Programming Unit 3
Sikkim Manipal University Page No. 87
3.7 Terminal Questions
1. Write Java program to print the address of the study center.
2. Write Java program to convert the Rupees to Dollars.
3. Write a Java program to compare whether your height is equal to your friends height.
4. Write a Java program to find the sum of 1+3+5+…. Fro 10 terms in the series.
5. Write a Java program to code the ApplicantCollection class, which stores and display the personal details of three applicants.
6. What are the different types of operator used in Java?
7. What do you understand by operator precedence?
8. What are the different types of control statements?
9. What do you mean by an array? Explain with an example?

No comments:

Post a Comment