UNIT-I A Java
UNIT-I A Java
UNIT-I 1
UNIT I
Introduction to Java: The key attributes of object oriented programming,
Simple program, The Java keywords, Identifiers, Data types and
operators, Program control statements, Arrays, Strings, String Handling
Introduction:
➢ JAVA is a programming language.
➢ Computer language innovation and development occurs for two fundamental reasons:
• To adapt to changing environments and uses
• To implement refinements and improvements in the art of programming
➢ Java is related to C++, which is a direct descendant of C. Much of the character of Java
is inherited from these two languages. From C, Java derives its syntax. Many of Java’s
object- oriented features were influenced by C++.
➢ Definition: Object-oriented programming (OOP) is a programming methodology that
helps organize complex programs through the use of inheritance, encapsulation, and
polymorphism.
➢ Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank,
and Mike Sheridan at Sun Microsystems, Inc. in 1991. This language was initially called
“Oak,” but was renamed “Java” in 1995.
➢ Java was not designed to replace C++. Java was designed to solve a certain set of
problems. C++ was designed to solve a different set of problems.
➢ Java contribution to internet:
Java programming had a profound effect on internet.
➢ Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the Internet
JAVA PROGRAMMING
and automatically executed by a Java-compatible web browser.
➢ Security
Every time you download a “normal” program, you are taking a risk, because the code you are
downloading might contain a virus, Trojan horse, or other harmful code.
In order for Java to enable applets to be downloaded and executed on the client computer
safely, it was necessary to prevent an applet from launching such an attack.
Java achieved this protection by confining an applet to the Java execution environment and not
allowing it access to other parts of the computer.
JAVA PROGRAMMING
UNIT-I 2
➢ Portability
Portability is a major aspect of the Internet because there are many different types of computers
and operating systems connected to it. Java programming provide portability
Byte code:
The output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM). In essence, the original JVM was designed as an
interpreter for bytecode.
functionality of a web browser, servlets dynamically extend the functionality of a web server.
➢ Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java. In fact, all Java programs are to at
least some extent object-oriented.
Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a program can be
conceptually organized around its code or around its data.
Some programs are written around “what is happening” and others are written around “who is
being affected.” These are the two paradigms that govern how a program is constructed.
The first way is called the process-oriented model. The process-oriented model can be
thought of as code acting on data. Procedural languages such as C employ this model
to considerable success.
Object-oriented programming organizes a program around its data (that is, objects) and a set of
well-defined interfaces to that data. An object oriented program can be characterized as data
controlling access to code.
JAVA PROGRAMMING
UNIT-I 3
Encapsulation
✓ Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse.
✓ In Java, the basis of encapsulation is the class.
✓ A class defines the structure and behavior (data and code) that will be shared by a set
of objects. Each object of a given class contains the structure and behavior defined by
the class. Objects are sometimes referred to as instances of a class.
✓ Thus, a class is a logical construct; an object has physical reality.
✓ The code and data that constitute a class are called members of the class. Specifically,
the data defined by the class are referred to as member variables or instance variables.
The code that operates on that data is referred to as member methods or just methods
✓ Each method or variable in a class may be marked private or public. The public interface
of a class represents everything that external users of the class need to know, or may
know. The private methods and data can only be accessed by code that is a member of
the class
Inheritance
✓ Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical classification.
✓ Inheritance interacts with encapsulation as well. If a given class encapsulates some
attributes, then any subclass will have the same attributes plus any that it adds as part
of its specialization
✓ A new subclass inherits all of the attributes of all of its ancestors.
Polymorphism
✓ Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions.
✓ More generally, the concept of polymorphism is often expressed by the phrase “one
interface, multiple methods.” This means that it is possible to design a generic interface
to a group of related activities. This helps reduce complexity by allowing the same
interface to be used to specify a general class of action.
JAVA PROGRAMMING
UNIT-I 4
class Example {
The name you give to a source file is very important. In Java, a source file is officially called a compilation
unit. It is a text file that contains (among other things) one or more class definitions. The Java compiler
requires that a source file use the .java filename extension
The name of the main class should match the name of the file that holds the program.
| javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of the program.
The output of javac is not code that can be directly executed.
To do so, pass the class name Example as a command-line argument, as shown here:
| java Example
JAVA PROGRAMMING
UNIT-I 5
/*
*/
This is a comment. The contents of a comment are ignored by the compiler. This is multiline
comment
class Example {
This line uses the keyword class to declare that a new class is being defined. Example is an identifier that
is the name of the class. The entire class definition, including all of its members, will be between the opening
curly brace ({) and the closing curly brace (}).
The next line in the program is the single-line comment, shown here:
// Your program begins with a call to main( ).
This line begins the main( ) method. All Java applications begin execution by calling main( ).
The public keyword is an access modifier, which allows the programmer to control the visibility of
class members. When a class member is preceded by public, then that member may be accessed
by code outside the class in which it is declared. main( ) must be declared as public, since it must
be called by code outside of its class when the program is started. The keyword static allows main(
) to be called without having to instantiate a particular instance of the class. This is necessary since
main( ) is called by the Java Virtual Machine before any objects are made. The keyword void simply
tells the compiler that main( ) does not return a value.
In main( ), there is only one parameter, String args[ ] declares a parameter named args, which is
an array of instances of the class String. Objects of type String store character strings. In this case,
args receives any command-line arguments present when the program is executed.
This line outputs the string “Java drives the Web.” followed by a new line on the screen. Output is
actually accomplished by the built-in println( ) method. In this case, println( ) displays the string
which is passed to it. The line begins with System.out. System is a predefined class that provides
access to the system, and out is the output stream that is connected to the console.
JAVA PROGRAMMING
UNIT-I 6
Example2:
/*
This demonstrates a variable.
Call this file Example2.java.
*/
class Example2 {
public static void main(String[ ] args) {
int var1; // this declares a variable
int var2; // this declares another variable
var1 = 1024; // this assigns 1024 to var1
System.out.println("var1 contains " + var1);
var2 = var1 / 2;
System.out.print("var2 contains var1 / 2: ");
System.out.println(var2);
}
}
O /P:
var1 contains 1024
var2 contains var1 / 2: 512
Example3:
/*
This program illustrates the differences between int and double.
Call this file Example3.java.
*/
Class Example3 {
public static void main(String[ ] args) {
int w; // this declares an int variable
double x; // this declares a floating-point variable
w = 10; // assign w the value 10
O/P
Original value of w: 10
Original value of x: 10.0
w after division: 2 x a
f ter division: 2.5
JAVA PROGRAMMING
UNIT-I 7
Example:
/*
Try This 1-1
This program converts gallons to liters.
Call this program GalToLit.java.
*/
class GalToLit {
public static void main(String[ ] args) {
double gallons; // holds the number of gallons
double liters; // holds conversion to liters
O/P:
10.0 gallons is 37.854 liters.
Identifiers
Identifiers are used to name things, such as classes, variables, and methods. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar- sign
characters. (The dollar-sign character is not intended for general use.) They must not begin with a number.
Java is case-sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are
GalToLit, Test, x, y2, maxLoad, my_var.
Invalid identifier names include these: 12x, not/ok.
JAVA PROGRAMMING
UNIT-I 8
JAVA PROGRAMMING
UNIT-I 9
• Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
• Characters This group includes char, which represents symbols in a character set, like
letters and numbers.
In Java char is a 16-bit type. The range of a char is 0 to 65,535. There are no negative chars.
JAVA PROGRAMMING
UNIT-I 10
• Boolean This group includes boolean, which is a special type for representing true/false
values.
// Demonstrate boolean
values. class BoolDemo {
public static void main(String[] args) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed."); b
= false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
O/P:
b is false b is
true
This is executed.
10 > 9 is true
Escape
Sequen Character
ce
\n newline
\t tab
\b backspace
\f form feed
\r return
\" " (double quote)
\' ' (single quote)
\\ \ (back slash)
character from the Unicode
\uDDDD
character set (DDDD is four hex
digits)
JAVA PROGRAMMING
UNIT-I 11
Operators:
An operator is a symbol that tells the compiler to perform a specific mathematical, logical, or other
manipulation. Java has four general classes of operators: arithmetic, bitwise, relational, and logical. Java
also defines some additional operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Operato Meaning
r
+ Addition(also unary plus)
- Subtraction(also unary
minus)
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
The operands of the arithmetic operators must be of a numeric type. We cannot use them on boolean
types, but we can use them on char types, since the char type in Java is, essentially, a subset of int.
When the division operator is applied to an integer type, there will be no fractional component attached to
the result. The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types.
// Demonstrate the % operator. class
ModDemo {
public static void main(String[ ] args) {
int iresult, irem;
double dresult, drem;
iresult = 10 / 3;
irem = 10 % 3;
dresult = 10.0 / 3.0;
drem = 10.0 % 3.0;
System.out.println("Result and remainder of 10 / 3: " + iresult + " " + irem);
System.out.println("Result and remainder of 10.0 / 3.0: " + dresult + " " + drem);
}
}
O/P:
Result and remainder of 10 / 3: 3 1
Result and remainder of 10.0 / 3.0: 3.3333333333333335 1.0
JAVA PROGRAMMING
UNIT-I 12
// Demonstrate ++.
class IncDec {
public static void main(String args[ ]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
The output of this program follows:
a=2
b=3
c=4
d=1
JAVA PROGRAMMING
UNIT-I 13
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate
on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and
!false == true. The following table shows the effect of each logical operation:
JAVA PROGRAMMING
UNIT-I 14
JAVA PROGRAMMING
UNIT-I 15
JAVA PROGRAMMING
UNIT-I 16
Assignment operators:
The assignment operator is the single equal
sign, =. It has this general form: var =
expression;
Here, the type of var must be compatible with the type of expression.
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
Java provides special operators that can be used to combine an arithmetic operation with an assignment.
a = a + 4; can rewrite as: a += 4;
There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form var = var op expression; can be rewritten as var op=
expression;
Operator Precedence
The following table shows the order of precedence for Java operators, from highest to lowest.
Operators in the same row are equal in precedence. In binary operations, the order of evaluation is
left to right (except for assignment, which evaluates right to left). Although they are technically
separators, the [ ], ( ), and . can also act like operators. In that capacity, they would have the highest
precedence.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them.
JAVA PROGRAMMING
UNIT-I 17
JAVA PROGRAMMING
UNIT-I 18
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then- else
statements. This operator is the ?.
The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
import java.util.Scanner;
public class Largest
{
public static void main(String[] args)
{
int a, b, c, d;
Scanner s = new Scanner(System.in);
System.out.println("Enter all three numbers:");
a = s.nextInt( );
b = s.nextInt( );
c = s.nextInt( );
d = a>b?(a>c?a:c):(b>c?b:c);
System.out.println("Largest of "+a+","+b+","+c+" is: "+d);
}
}
JAVA PROGRAMMING
UNIT-I 19
Control Statements
A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program. Java’s program control statements can be put
into the following categories: Selection, Iteration and Jump.
Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable. Iteration statements enable program execution
to repeat one or more statements (that is, iteration statements form loops). Jump statements allow
your program to execute in a nonlinear fashion.
if 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.
JAVA PROGRAMMING
UNIT-I 20
Nested ifs
A nested if is an if statement that is the target of another if or else. When you nest ifs, the main thing to
remember is that an else statement always refers to the nearest if statement that is within the same block
as the else and that is not already associated with an else.
JAVA PROGRAMMING
UNIT-I 21
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 default condition;
// Demonstrate an if-else-if ladder.
class Ladder {
public static void main(String[] args) {
int x;
for(x=0; x<6; x++) {
if(x==1)
System.out.println("x is one");
else if(x==2)
System.out.println("x is two");
else if(x==3)
System.out.println("x is three");
else if(x==4)
System.out.println("x is four");
else
System.out.println("x is not between 1 and 4");
}
}
}
O/P:
x is not between 1 and 4 x is
one
x is two x is
three x is four
x is not between 1 and 4
switch
The switch provides for a multi-way branch. It often provides a better alternative than a large series of if-
else-if statements.
Here is the general form of a switch statement:
JAVA PROGRAMMING
UNIT-I 22
The break statement is optional. If you omit the break, execution will continue on into the next
case.
Nested switch Statements
We can use a switch as part of the statement sequence of an outer switch. This is called a nested
switch. Since a switch statement defines its own block, no conflicts arise between the case
constants in the inner switch and those in the outer switch. For example, the following fragment is
perfectly valid:
switch(count) {
case 1:switch(target) { // nested switch
case 0: System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // …
JAVA PROGRAMMING
UNIT-I 23
In summary, there are three important features of the switch statement to note:
• The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match between
the value of the expression and one of its case constants.
• No two case constants in the same switch can have identical values. Of course, a switch
statement and an enclosing outer switch can have case constants in common.
• A switch statement is usually more efficient than a set of nested ifs.
Iteration Statements
Java’s iteration statements are for, while, and do-
while. while
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling
expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as the
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if only a single statement is being
repeated
// Demonstrate the while loop. class
WhileDemo {
public static void main(String[ ] args) {
char ch;
// print the alphabet using a while loop
ch = 'a';
while(ch <= 'z') {
System.out.print(ch);
ch++;
}
}
}
do-while
The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
The do-while loop is especially useful when you process a menu selection, because you will usually
want the body of a menu loop to execute at least once.
JAVA PROGRAMMING
UNIT-I 24
for loop
The general form of the traditional for
statement: for(initialization; condition;
iteration) {
// body
}
// Show square roots of 1 to 9.
class SqrRoot {
public static void main(String[ ] args) {
double num, sroot;
for(num = 1.0; num < 10.0; num++) {
sroot = Math.sqrt(num);
System.out.println("Square root of " + num +
" is " + sroot);
}
}
}
JAVA PROGRAMMING
UNIT-I 25
Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a
“civilized” form of goto.
Using break to Exit a Loop: 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.
// Using break to exit a loop.
class BreakDemo {
public static void main(String[ ] args) {
int num;
num = 100;
// loop while i-squared is less than
num for(int i=0; i < num; i++) {
if(i*i >= num) break; // terminate loop if i*i >= 100
System.out.print(i + " ");
}
System.out.println("Loop complete.");
}
}
When used inside a set of nested loops, the break statement will only break out of the innermost loop
Using break as a Form of Goto: The break statement can also be employed by itself to
provide a “civilized” form of the goto statement.
The general form of the labeled break statement is shown
here: break label;
JAVA PROGRAMMING
UNIT-I 26
Using continue
It is possible to force an early iteration of a loop, bypassing the loop’s normal control structure. This is
accomplished using continue. The continue statement forces the next iteration of the loop to take place,
skipping any code between itself and the conditional expression that controls the loop.
// Use continue.
class ContDemo {
public static void main(String[ ] args) {
int i;
// print even numbers between 0 and 100
for(i = 0; i<=100; i++) {
if((i%2) != 0) continue; // iterate
System.out.println(i);
}
}
}
As with the break statement, continue may specify a label to describe which enclosing loop to continue.
Here is an example program that uses continue to print a triangular multiplication table for 0 through 9:
// Using continue with a label.
class ContinueLabel {
public static void main(String args[ ]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println( );
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The continue statement in this example terminates the loop counting j and continues with the next
iteration of the loop counting i. Here is the output of this program:
return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method.
JAVA PROGRAMMING
UNIT-I 27
ARRAYS:
An array is a collection of variables of same type, referred to by a common name. Arrays of any type can
be created and may have one or more dimensions. A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables.
The general form to declare a one-dimensional array:
type[ ] array-name=new type[size];
Since arrays are implemented as objects, the creation of an array is a two-step process. First declare
an array reference variable. Second allocate memory for the array, assigning the reference to that
memory to the array. Thus arrays in java are dynamically allocated using new operator.
Eg : int[ ] sample=new int[10];
It is possible to break the above declaration.
int[ ] sample;
sample=new int[10];
JAVA PROGRAMMING
UNIT-I 28
JAVA PROGRAMMING
UNIT-I 29
Multidimensional Arrays:
Two-dimensional arrays:
A two dimensional array is a list of one-dimensional array. A two dimensional array can be thought of as
creating a table of data organized by row and column. An individual item of data is accessed by specifying
its row and column position.
To declare a two dimensional array, we must specify two dimensions.
int[ ] [ ] table=new int[10] [20];
O/P:
1 2 3 4
5 6 7 8
9 10 11 12
Irregular arrays:
When allocating memory for multi dimensional arrays we need to specify only the memory for the first
dimension. We can allocate the remaining dimensions separately.
// Manually allocate differing size second dimensions. class
Ragged {
public static void main(String[ ] args) {
int[ ][ ] riders = new int[7][ ];
riders[0] = new int[10];
riders[1] = new int[10];
riders[2] = new int[10];
riders[3] = new int[10];
riders[4] = new int[10];
riders[5] = new int[2];
riders[6] = new int[2];
int i, j;
JAVA PROGRAMMING
UNIT-I 30
// fabricate some
data for(i=0; i < 5;
i++) for(j=0; j < 10;
j++)
riders[i][j] = i + j + 10;
for(i=5; i < 7; i++) for(j=0;
j < 2; j++)
riders[i][j] = i + j + 10;
System.out.println("Riders per trip during the week:");
for(i=0; i < 5; i++) {
for(j=0; j < 10; j++)
System.out.print(riders[i][j] + " ");
System.out.println( );
}
System.out.println( );
System.out.println("Riders per trip on the weekend:");
for(i=5; i < 7; i++) {
for(j=0; j < 2; j++)
System.out.print(riders[i][j] + " ");
System.out.println( );
}
}
}
JAVA PROGRAMMING
UNIT-I 31
JAVA PROGRAMMING
UNIT-I 32
JAVA PROGRAMMING
UNIT-I 33
There is one important point to understand about the for-each style loop. Its iteration variable is “read-only”
as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying
array.
// The for-each loop is essentially read-only.
class NoChange {
public static void main(String[ ] args) {
int[ ] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println( );
}
}
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
JAVA PROGRAMMING
UNIT-I 34
O/P:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
O/P:
Enter a number to search 8
Value found!
JAVA PROGRAMMING
UNIT-I 35
STRINGS:
One of the most important data type in java is String. String defines and supports character
sting. In java strings are objects
Constructing strings:
String str= new String(“HELLO”);
This creates a String object called str that contains the character string “HELLO”.
A string can be constructed from another string
String str2= new String(str);
Another easy way to create a string is
String str=”Java strings are powerful”;
// Introduce String.
class StringDemo {
public static void main(String[ ] args) {
// declare strings in various ways
String str1 = new String("Java strings are objects.");
String str2 = "They are constructed various ways.";
String str3 = new String(str2);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
Operating on strings:
The String class contains several methods that operate on strings.
boolean Returns true if the invoking string contains the same character sequence
equals(str) as str
int length( ) Returns the number of characters in the string
char charAt(index) Returns the character at the index specified by index
int compareTo(str) Returns less than zero if the invoking string is less than str, greater than
zero if
the the invoking string is greater than str, and zero if the strings are equal
int indexOf(str) Searches the invoking string for the substring specified by str. Returns
the index
of the first match or -1 on failure
int lastIndexOf(str) Searches the invoking string for the substring specified by str. Returns
the index
of the last match or -1 on failure
JAVA PROGRAMMING
UNIT-I 36
JAVA PROGRAMMING
UNIT-I 37
Array of strings:
// Demonstrate String arrays. class
StringArrays {
public static void main(String[ ] args) {
String[] strs = { "This", "is", "a", "test." };
System.out.println("Original array: ");
for(String s : strs)
System.out.print(s + " ");
System.out.println("\n");
// change a string in the
array strs[1] = "was";
strs[3] = "test, too!";
System.out.println("Modified array: ");
for(String s : strs)
System.out.print(s + " ");
}
}
JAVA PROGRAMMING
UNIT-I 38
JAVA PROGRAMMING
UNIT-I 39
STRING HANDLING:
The String class is packaged in java.lang. Thus it is automatically available to all programs.
String objects can be constructed in a number of ways, making it easy to obtain a string when needed.
String Constructors:
// Demonstrate several String constructors.
class StringConsDemo {
public static void main(String[ ] args) {
char[ ] digits = new char[16];
// Create an array that contains the digits 0 through 9
// plus the hexadecimal values A through F.
for(int i=0; i < 16; i++) {
if(i < 10) digits[i] = (char) ('0'+i);
else digits[i] = (char) ('A' + i - 10);
}
// Create a string that contains all of the array.
String digitsStr = new String(digits);
System.out.println(digitsStr);
// Create a string the contains a portion of the array.
String nineToTwelve = new String(digits, 9, 4);
System.out.println(nineToTwelve);
// Construct a string from a string.
String digitsStr2 = new String(digitsStr);
System.out.println(digitsStr2);
// Now, create an empty string.
String empty = new String();
// This will display nothing:
System.out.println("Empty string: " + empty);
}
}
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to this rule
is the + operator, which concatenates two strings, producing a String object as the result.
String age = "9";
String s = "He is " + age + " years
old."; System.out.println (s);
This displays the string “He is 9 years old.”
JAVA PROGRAMMING
UNIT-I 40
One practical use of string concatenation is found when you are creating very long strings. Instead
of letting long strings wrap around within your source code, you can break them into smaller pieces,
using the + to concatenate them. Here is an example:
// Using concatenation to prevent long
lines. class ConCat {
public static void main(String args[ ]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}
}
Character Extraction
The String class provides a number of ways in which characters can be extracted from a String
object
charAt( )
To extract a single character from a String, you can refer directly to an individual character via the
charAt( ) method. It has this general form:
char charAt(int index)
// Demonstrate charAt( ) and length( ).
class CharAtAndLength {
public static void main(String[] args) {
String str = "Programming is both art and science.";
// Cycle through all characters in the string.
for(int i=0; i < str.length(); i++)
System.out.print(str.charAt(i) + " ");
System.out.println();
}
}
getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. It
has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
// getChars( )
class GetCharsDemo {
public static void main(String[] args) {
String str = "Programming is both art and science.";
int start = 15;
int end = 23;
char[ ] buf = new char[end - start];
str.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
JAVA PROGRAMMING
UNIT-I 41
String Comparison
The String class includes a number of methods that compare strings or substrings within strings.
class EqualityDemo {
public static void main(String[] args) {
String str1 = "table";
String str2 = "table";
String str3 = "chair";
String str4 = "TABLE";
if(str1.equals(str2))
System.out.println(str1 + " equals " + str2);
else
System.out.println(str1 + " does not equal " + str2);
if(str1.equals(str3))
System.out.println(str1 + " equals " + str3);
else
System.out.println(str1 + " does not equal " + str3);
if(str1.equals(str4))
System.out.println(str1 + " equals " + str4);
else
System.out.println(str1 + " does not equal " + str4);
if(str1.equalsIgnoreCase(str4))
System.out.println("Ignoring case differences, " + str1 +" equals " + str4);
else
System.out.println(str1 + " does not equal " + str4);
}
}
O/P:
table equals table
table does not equal chair
table does not equal TABLE
Ignoring case differences, table equals TABLE
JAVA PROGRAMMING
UNIT-I 42
equals( ) Versus = =
It is important to understand that the equals( ) method and the == operator perform two different operations.
The equals( ) method compares the characters inside a String object. The == operator compares two object
references to see whether they refer to the same instance.
// 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
regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific region in
another string. Here are the general forms for two methods:
boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int
numChars) boolean regionMatches(boolean
ignoreCase,
int startIndex, String str2,
int str2StartIndex, int numChars)
// Demonstrate
RegionMatches. class
CompareRegions {
public static void main(String[] args) {
String str1 = "Standing at river's edge.";
String str2 = "Running at river's edge.";
if(str1.regionMatches(9, str2, 8, 12))
System.out.println("Regions match.");
if(!str1.regionMatches(0, str2, 0, 12))
System.out.println("Regions do not match.");
}
}
O/P:
Regions match. Regions do
not match.
JAVA PROGRAMMING
UNIT-I 43
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)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point
replace( )
The replace( ) method has two forms. The first 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');
JAVA PROGRAMMING
UNIT-I 44
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( )
Eg: String str=” gamma “;
After str=str.trim( );
Str will contain only the string”gamma”