Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 11

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Chapter 11

Using Library Classes


We have seen how user defined classes can be created and used for solving different
real life problems. Every program needs input/output operations. For input/output
operations, Java takes help of library classes. Java provides many built-in library
classes for the support of operation involving Input/ Output, String handling etc.
Let us study the concept of I/O Streams, Strings, Java Library Classes and other related
things in terms of Java Programming.
SIMPLE INPUT /OUTPUT IN JAVA
Input is any information that is needed by your program to complete its execution. There are many forms that
program input may take. Some program use graphical components like a pop-up dialog box to accept and
return the character string that is typed by the user. You are certainly familiar with programs that are controlled
simply by clicking the mouse in a specific area of are of the screen. Still other programs, like word processing
programs, get some of their input from a file that is stored on the computer’s floppy or hard disk drive . some
program like web browsers, get their data from a network connection, while others get datafromdevices like
scanners digital cameras and microphones. The possibilities are limited only computer scientists imagination.
Standard I/O Streams
produce output on the computer screen. Java provides the following three stands
streams All the programming languages provide support for standard I/O where user's program can take input from
keyboard and then:
Stream Types - Java I/O
Standard Input: This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used as standard output stream and represented as System. out.
Standard Error: This is used to output the error data produced by the user's program and usually a
computer screen is used as standard error stream and represented as System.err.

Abstract Classes

Input Stream
Byte Based

Output Stream

Streams
Reader
••

Writer
Character
Based

CONSOLE INPUT
to get information from the user. In many cases, the user is prompted to enter input* user prompt is a line of text that is
output to the user that explains what information the user should in next We can prompt the user by displaying information in
a dialog box, a program frame or even the cons window. All programs that require the user to input information while the
program is running, must pro the user for the information in any manner When a program is waiting for input at the console,
there is sometimes a blinking cursor in the conso^ window indicates that the user should type some information. But, this is
not always the case. The us only know what information to type, if the program describes that information in the form of
Console input is any input that is entered in the console window instead of typing it into a field or dialog box. For example,
when the redline ( ) method is called, the program waits for the user to enter information. Whatever the user types is
returned to the program in the form of a String object. There are many ways a user prompt t• of several Java I/O classes
is required to successfully receive input that is typed by the user. The java You need to learn about three of
them tioned below. All the classes are in the java.io package.
 « Java.io.InputStream is used to store information about the connection between an input device and
the computer or program.
 Java.io.InputStreamReader is used to translate data bytes received from Input Stream objects into a
stream of characters.
 java.io.BufferedReader is used to buffer(store) the input received from an InputStreamReader object
This is done to improve efficiency
.
steps for console based user input:

1.Use the System. in object to create an InputStreamReader object.


2. Use the InputStreamReader object to create a Buffered Reader object.
-

3. Display a prompt to the user for the desired data.


4. Use the Buffered Reader object to read a line of text from the user.
Do something interesting with the input received from the user.

integer input
If the user types in "1234", that will be returned as a String object by the redline method of Buffered Reader.
You will need to parse (convert) the String object into an int value if you wish to store it in an int variable or
data member.

1. Get a String of characters that is in an integer format. For example-"1234". String input = stdin.readLine
();
2. Use the Integer class to parse the string of characters into an integer.
int number = Integer.parselnt (input); // converts a String into an int value.
The Integer class contains conversion methods for changing String data into int values and vice versa.
Wrapper classes have class methods for parsing and are also used when you need to store a primitive value
asan object.
In the above case, we need to convert a String object into an int value. The parselnt method of the Integer
class performs this action.

Using Buffered Character Streams

Following method is widely used for Java console read/write operations. It is possible to wrap standard io
streams in any type of buffered streams. But generally the data read and written to console is character data.
We prefer buffered character streams to read and write data. Following are the two classes which we will use
for console read/write operations.

•> Buffered Reader


•> Buffered Writer
Both of these streams are character based buffered streams. System. out uses java.io.PrintStream which
internally uses Buffered Writer. So we do not wrap System. out with any other class. Consider following

example:

Public class Test {


Public static void main(String args[ ]) throws IoException {
Buffered Reader reader = new Buffered Reader (new InputStreamReaderCSystem.i'n));
String line * reader. readLine( );
System,out.pr/ntfn(line);
}
}
InputStreamReader is a new class that we have used in above example. Generally System is a. FilelnputStream
object. FilelnputStream is a byte stream. So we need a bridge to convert bytes to characters and cha^^ bytes
InputStreamReader acts as this bridge.
InputStreamReader converts bytes into characters and characters into bytes.

II Use a Buffered Reader to read characters from the console,


import java.io.*;
class BRRead {
public static void main(String args[ ]) throws lOException {
char c;
BufferedReader br = new Buffered Reader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
II read characters
do{
c = (char) br.read();
System, out. println(c);
}
while(c != 'q');
}
}
What if the user types letters instead of digits ?
The parselnt method declares that it may throw a NumberFormatException. If the user types any string of
characters that cannot be parsed into an int value, a NumberFormatException will be thrown and the
program will crash. But, there is something that you as the programmer can do to keep your program away
from crashing. You can catch the NumberFormatException from crashing the program.
An OutputStreamWriter is a bridge to convert from character streams to byte streams: Characters written to
it are encoded into bytes using a specified charset. The charset that it uses may be specified by name or may
be given explicitly or the platform's default charset may be accepted. Each invocation of a wr/te( ) method
causes the encoding converter to be invoked on the given character(s). The resulting bytes are
accumulated in a buffer before being written to the underlying output stream. The sizeof this buffer may be
specified, but by default it is large enough for most purposes. Note that the characters passed to the write( )
methods are not buffered.
efficiency, consider wrapping an OutputStreamWriter within a Buffered Writer frequent converter invocations.
For example:
Writer out = new BufferedWriter (new OutputStreamWriter (System. out));
WHATJSlASTRING?
String is series of characters. Strings are constant and their values cannot be
a

Stringhang String handling and manipulation is a common and an important activity in Java programs. String is
ed

a sequence of characters.
in Java, String is a class and not a primitive data type.
In Java, Strings are implemented using two classes; String and String Buffer. String is a class, therefore, it
starts with an uppercase letter whereas all primitive data
types start with lowercase letter.
String may & declared as follows :
e

String String Name;


NoUSt
String Name = new String("Hello ); n

The value of string cannot be changed after


its creation. A string is declared by the keyword
String.
The java.lang package contains two string classes:
(i) String (ii) StringBuffer
String class is used when strings cannot change.
StringBuffer is used when there is a need of manipulation on the contents of string.
Characteristics of String
(i) String is a series of characters.
(ii) It is not terminated by null in Java.
(iii) String can be delimited using double quotes.
(iv) String is terminated using a semicolon.
(v) String objects can be shared.
(vi) The keyword string starts with capital 'S\
The Java platform provides the String class to create and manipulate strings.
The principal operations on a String Buffer are the append( ) and insert( ) methods, which are overloaded so as
to accept data of any type. Each method effectively converts a given characters to a string and then appends or
inserts the characters ofthat string to the string buffer. The append ( ) method always adds these characters at
the end of the buffer whereas the insert( ) method adds the characters at aspecified point.
siraiicn
public class Appendlnsert {
public void main() {
StringBuffer a = new String Buffer();
a.insert(0, "Computer Applications");
System.out.println(a);

StringBuffer b = new StringBufferfComputer Applications");


System.out.println(b);
StringBuffer c = new StringBuffer(20);
c.insert(0, "Computer Applications");
1

Output of the Program


Computer Applications
Computer Applications
-

Creating a String
Strings are mainly created from string literals. When the compiler reads a series characters enclosed in double 1

quotes, it immediately creates a String object whose value .s that wh.ch appears between the
For example –
"Good Morning"
The most direct way to create a string is to write: String school = "St Thomas";
In this case, "St Thomas" is a string literal i.e. a series of characters enclosed in double quotes. Whenever,
encounters a string literal in the program, the compiler creates a String object with its value-in this case, St

Thomas.
As with any other object, you can create String objects by using the new keyword and a constructor.
\•-
*

When the compiler encounters the above string literal, it creates a string whose value is Good Morning.
To create an empty String, use of default constructor is required. String str = new String( );
It will create an instance of String with no characters in it.
To create a String, which is initialized by array of characters, the following constructor can be used :
String(char charsf ])
For example -
char str[ ] = {V, *o\ W, 'p' 'iT, T, 'e', V}; String s = new String(str);
#

The above constructor initializes the string with "computer".



••

Methods used in String Operations


Access or methods : length{), char At(i), get Bytes(), get Chars(istart,iend,gtarget[ ], itargstart), toCharArray(),
value Of(g,iradix), substring(iStart [,iEndlndex)]) [returns up to but not includingiEndlndex]
Modifier methods: to Lowercase(), to Uppercase(), trim(), concat(g), replace(cWhich, replacement).
Boolean test methods : content Equals(g), ends With( ), equals( ), equalsIgnoreCase( ), matches( ),
region Matches(), starts With().
Integer test methods : compare To() [returns 0 if object equals parameter, -1 if object is before parameter in
sort order +1 if otherwise] index of () [returns position of first occurrence of substring in the string, -1 ifnot found]
lastlndex0f() [ returns position of last occurrence of substring in the string, -1 if not found], length (
String Length
. a string a series of characters and its length is the number of characters it -fains- To obtain
the length of a string, length() method is used.
Int length()
'lllsufration
n

public class String Length {


public void main() {
char str[ ] = {'c', 'o', W, 'p', ' r'};
u

String a = new String(str); System.out.print("Length of the String = ");


System.out.println (a. Length());
}
}
Output of the Program
Length of the String = 8
^
StringBuffer Class in Java
The StringBuffer class is included in java.lang library class and is mostly used when we have to
make a lot of modifications to Strings of characters. We know that String class does not support
string mutability. If we use String class, we have to face problems of memory wastage and
memory overflow. Objects of String Buffer class can be modified a number of times. You do not
need a reference to the object to assign. Simply use the method on the object and change will
reflect on the object. The String Buffer class modifies strings over and over again. The main use
of String Buffer class is in File I/O where large stream of data keeps on coming with constantly
changing values. By using this class, the loss of memory never happens.
.
Constructors of StringBuffer class
String Buffer (): it creates a String Buffer with initial capacity of 16characters.
String Buffer (String s)• it creates String Buffer which contains same number of ' characters as
in the String argument.
String Buffer (String s);it creates String Buffer with specified number of
String Buffer (int length) ;characters.
^CONCATENATION OF STRINGS AND OPERTOR
The + operator is used to concatenate two strings in Java. String in Java
String s = “ter”;
System .outsprinting (“compu" +s + "Applications");
You can also use the operator to append the non-string values.
+

public void main() {


String str = "I am Poonam Mehta. " +
"I read in 0 P J Senior Model School, " +
"Fatimabad, Haryana";
System, out.println(str);
}
}

Output of the Program


I am Poonam Mehta. I read in 0 P J Senior Model School, Fatimabad, Haryana
• w»

Extracting Characters from Strings


String class provides various ways to extract characters from String object. String indexes begin at
Zero. The characters which comprise a string within a string object cannot be indexed.

charAt()
The charAt( ) method returns the character at a specified index An index has the range from 0 to
total length minus 1.
char charAt(int position)
In the above example, position is the index of the character which you want to extract
char a;
a = "ritiprateek".charAt(3)
In the above example, the value "t" will be assigned to "a".
get chars()
The getChars( ) method returns more than one character at a time.
getChars(int stringstart, int stringend, char target ], int targetStart)
In the above usage, stringstart specifies the index of beginning of the substring. Whereas stringend
specifies the index at the end of that substring. Therefore, the substring contains the total characters
as stringstart
through stringend-1.
(lustration
-

public class ExtractChar {


-

public void main( ) {


String str = "I am Poonam Mehta. " +
"I read in 0 P j Senior Model School, - + "Fatehabad, Haryana";
•.

/nt beginning = 5;
intend = 17;
char al ] = new char fend - beginning];
str.getChars(beginning, end, a, 0);
System.out.println(a);
}
}
outputofthe Program
poonam Mehta
get bytes () method stores characters in an array of bytes. The get Bytes method
^verts result into a new array. This method is an alternative of get Chars() method.
the string into bytes according to specified character encoding and stores
Byte[ ] get Bytes()

dffuslrafj
on
public class Byte Char {
public void main() {
String str = "I am Poonam Mehta." +
"I read in 0 P J Senior Model School," +
"Fatimabad, Haryana";
int beginning = 5;
int end = 17;
char a[ ] = new char [end - beginning];
byte b[ ] = new byte[20];
str.getChars(beginning, end, a, 0);
str.getBytes(5, 17, b, 0);
System.out.println("The get Bytes characters are = " +b);
Output of the Program
The get Bytes characters are = [B@l9a029e
toCharArray()
the toCharArray() method is used to convert all characters of a string object into
character array.
char[ ] = toCharArray()

iSjJusfraiion
jf public class ArrayChar { *
public void main() {
String str =
"I am Poonam Mehta." + ..
, read in 0 P 3 Senior Model School,
"Fatimabad, Haryana";
int beginning = 5; int end = 17;
char a[ ] = new char [end - beginning]; byte b[ ] = new byte[20];
str.getChars(beginning, end, a, 0); str.getBytes(5, 17, b, 0);
System.out.printlnfThe get Bytes characters are = " +b); String strl = "Malhotra &
Amphora";
System.out.println (strl.toCharArray ( ));
}
}

Output of the Program


Malhotra & Malhotra
startsWith()
The startsWith( ) method is used to check whether the invoking string starts with the
same sequence ol characters as the substring passed as an argument to the method.
The signature of the method is given below:
public boolean starts With(String prefix)
There is also an overloaded version of starts With() method with the following
signature : public Boolean starts With(String prefix, int start index)
In both signatures of the method given above, the prefix denotes the substring to be
matched within the
invoking string However in the second version, the start index denotes the starting index
into the invoking
string at which the search operation will commence. waning inaex into we
endsWith()
The endsWith( ) method is used to check whether the invoking string ends with same
sequence of characters as the substring passed as an argument the method. The
signature of the method is given below.
public Boolean ends With(String prefix)
The String class defines two methods that facilitate in searching a particular character or sequence
of characters in a string. They are as follows:
IndexOf ()
the indexOf() method searches for the first occurrence of a character or a substring the invoking
string. If a match is found, then the method returns the index at'"hich the character or the
substring first appears. Otherwise, it returns -1. The jndexOf() method has the following
signatures :
public int indexOf(int ch)
public int indexOf(int ch, int start index)
public int indexOf(String str)
public int indexOf(String str, int start index)
lastlndexOf()
fhelastIndexOf( ) method searches for the last occurrence of a character or a substring in the
invoking string. If a match is found, then the method returns the index at which the character or
the substring last appears. Otherwise, it returns -1.
The Iastlndex0f( ) method has the following signatures : public int Iastlndex0f(int ch)
public int Iastlndex0f(int ch, int start index) public int lastlndex0f(String str)
public int lastIndexOf(String str, int start index)
r

illustration
public class LastlndexOfCh {
public static void main(String args[ ]) {
String s = "Honesty is the Best Policy";
System.out.println(s);
System.out.println ("lastIndexOf(b) ->" +s.lastlndex0f(98));
System.out.println("lastIndexOf(b) ->" +s.lastIndexOf('b'));
}
}
* STRING MODIFICATION
String objects are immutable. Whenever you want to modify a string, you have to copy it into a
String Buffer or have to use any one of the following methods to do so.
Substring()
The substring() method returns a new string which is a substring of the string.
The substring() can be used in two different formats which are mentioned below-
sWng substring(int startindex)
The startindex specifies the index at which a substring will begin. The above format returns a
copy of the substring which begins at start index and runs to the end of
e invoking string.
th
••

.(,!

String substringfint
startlndex, int endlndex)
f

format specifies the beginning and endlndexthe, ncI poimTh
e e st

returned in this manner contains all the characters from the starting Index, upto the endmg index( endlnn 9 index not
included).
c(/fusfrafiofl
public class ModiString { public void main() {
String str = "Computer Applications"; System.out.println(str.substring(2));
}
Output of the Program
CO
The concat() method concatenates the specified string to the end of the given string

String concat(String str)
-.

tSllustration
/
public class StringConc { public void main() {
String strl = "Computer Applications ";
String str2 = strl.concat("For Class 10th 1CSE ");
System.out.println(str2);
}
Output of the Program
Computer Applications For Class 10th 1CSE
trim
The trim() method trims(removes) white spaces from both the ends of a string.
String trim()
-

public class StringTrim {


-

public void main() {


/
String strl = Computer Applications
-
11

System.out.println(strl.trim( ));
}
}
Changing Case of String
Method to LowerCase() converts all the characters from lowercase to uppercase to lowercase and
the methodconverts all the characters of string from uppercase to lowercase and the method
c(llus(raficn- j
public class StringCase {
public void main() {
String strl = "Computer Applications ";
System.out.println (strl.toUpperCase ( ));
}
}
Output of the Program
COMPUTER APPLICATIONS
public class StringCasel {
public void main() {
String strl = "MY NAME IS RITIK MALHOTRA";

System.out.println (strl.toLowerCase ());


}
}
Output of the Program
my name is ritik malhotra
Some other modifications on Strings
replace()
The method replace() replaces all occurrences of one character in the specified string with another
character.
General Syntax-
String replace(char original, char replacement)
In the above syntax, the word original specifies the character to be replaced by the word
replacement.
String str = "Today.Two".replace(T, 2');
,

The result of the above program segment will be :


2oday 2wo
insert()
The insert() method Inserts one string into another. It calls String.valueOf() to obtain the string
representation of the value it is called with.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch) String Buffer insert(int index, Object obj)
The index in the above forms specifies the index where the string will be inserted Into the
specified object.
I;
f i/us/ration
class Ever62 {
public void main( ) {
String Buffer str = new StringBufferf'I am solving problems.");
str.insert (5, "learning Java and");
System.out.println(str);
}
}
Output of the Program
I am learning Java and solving problems
3!j
reverse

The reverse() method is used to reverse a string.


String Buffer reverse( )
illustration
class Ever {
public void main() {
StringBuffer str = new StringBuffer("PRATIEK MALHOTRA");
System.out.println("Original String=" +str);
str.reverse () ;
System.out.println("Reversed String =" +str);
-

}
}

Output of the Program


5,
Original String = PRATIEK MALHOTRA

Reversed String = ARTOHLAM KEITARP


Comparing Two Strings
We can compare two string using==operator. For comparing two strings, equals( ) method of
String class is used.
Consider the following illustrations :
illustration-
class CompareStrings {
public void main( ) {
String s1, s2;
S1=”VIKAS”
s2 = s1;
0

;
System.out.println ("Same Thing ?" + (s1 == s2));
s2 = new String (s1) ;
S

System.out.printlnfSame Thing ?" + (si == s2)V


System.out.println("Same Result ?" +sl.equals(s2));
utput of the Program
Same Thing ? true
Same Thing ? false
Same Result ? true
^Illustration- J
Write a program using compareTof) method in a simple array, arranging the days of week
in dictionary order.
class compareTo {
static String s[] = {"Sunday", "Monday", "Tuesday", "Wednesday", 'Thursday", "Friday",
"Saturday"}; public static void main(String args[]) {
for (inti = 0; i < s.length; {
for (int j = i + 1; j < s.length; j++) { if(s[j].compareTo(s[i] < 0) {
String temp;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
System.out.prlntln(s[i]);
}
}
}
Output of the Program
Friday
Monday
Saturday
Sunday
Thursday

Tuesday
Wednesday
Checking Whether Two Strings are Equal
To determine whether two strings contain same characters(number of characters), equals method is
used
Consider the following program segment:
String exam = "Tenth ;
String paper = 'Tenth";
if(exam. equals(paper))
The above segment will give true result since both the strings are equal.
Ignoring the Case in Two Equal Strings
If you want to ignore the case of two strings, equalsIgnoreCase method is used.
Consider the following program segment :
String exam = "TENTH";
String standard = "tenth";
if(exam. EqualsIgnoreCase(standard))
The result of the above segment will be true.
Removing Leading and Trailing White Space from a String
Sometimes need arises to remove leading and trailing white space characters (like blank spaces, tabs etc) from
a string. The trim() method is used for removing such spaces.
Consider the following program segment:
-

String abc = " Tenth class ";


abc = abc.trim();
System.out.println("Class is =" +abc);
In the above segment, leading and trailing spaces of the abc object will be removed.
DETERMINING WHETHER A CHARACTER IS A SPACE
While working on the characters in Java program, sometimes need arises to determine whether a
character is a space. In Character objects, isSpace method is used to check this condition.
Consider the following program segment:

Character chr = new Character(' ');


if(chr.isSpace( ))
System.out.println ("The Character is a Space");
How to convert a character to a numeric value?

The character.digit method is used to convert a character to a numeric value


Consider the following program segment:
What is the meaning of white space ?
int n;
Character four = new Character^ ); = Character.digit(four);
1 n

MATHEMATICAL CALCULATIONS USING STRINGS


String class allows the inclusion of the Math class, which is defined in the Java. A function in
Java can be used as per the following format:
Math. Function-name();
for Example:
double a,b;
a = Math.pow(b,3);
Here in the above format, the cube of b gets assigned to the variable a
Some of the commonly used mathematical functions in Java have been mentioned below :
(i) sin()
It returns the sine of the given angle in radians. The value of given angle is of double type.
Syntax
Math.sin(a);
(ii) cos()
It returns the cosine of the given angle in radians. The value of given angle is of double type.
Syntax
Math.cos(a);
(iii) tan()
It returns the tangent of the angle in radians. The value of given angle is of double type.
Syntax
Math.tan(a);
(iv) pow()

This function compute a to the power of b, where a and Z?are of double type.
Syntax
Math.pow(a,b);
(v) exp()
This returns the exponent of e to the power of a, where a is of double type.
Syntax
Math.exp(a);
(vi) log()
This function computes the log of a given value, where the value is of double type
Syntax
Math.log();
(vif) Kjrt()
' ° „, th» variable a, where the value of a is of double type.
qrt trA

If. returns the square root of trie vanawe ,


Syntax Math,sqrt(a);
(viiij wilf )
"etls the smallest whole number greater than or equal to the variable a, where the va, Ue of

of double type.
Syntax
Math,cefl(a);
(ix) floor( ) . .
e

It returns the largest whole number less than or equal to a, where the value of a ,s of double type.
Syntax
Math.floor(a);
(x) abs()
It returns the absolute value of the variable a, where value of a is of type int, long, double or float.
Syntax
Math.abs(a);
(xi) max()
It returns the maximum of the two given variables a and A
where the value of a and b can be int, long, float or double types.
Syntax
Math,ma/(a, b);
fxii) min( )
Jt returns the minimum of the two given variables a and b, where a and b can be int, long, float or double
types.
Syntax
Math.rnin(a, b);
(xiii) randomf)

-™ S

' Ue

° »• •** «* time, you ri


d

u the Random class when you need to generate random numbers.


Method

Function
Argument Type
Result Type
randorn( )
Returns a pseudo-random
None
double
greater than or equal to 0.0
and less than 1.0
r

class Random {
public void rnumber() {
System.ouLprinUn(-Random Number between 0 and 1 is =• , „. System-
+HaUl Pncfe(n

outprintlnCP^ndom Number between 1 and 100 =« +I +

System-outprintinCRandom Character =- arXl28 * Katfuwfcn* )))•


+(dl

}
}
Output of the Program
Random Number between 0 and 1 is =0.4892840479088907
' Random Number between 1 and 100 =122
I ^^o^O^^^x =S
(xiv) rint()
The rin« ) method is used to calculate the nearest integer to the argument
Its argument type is double and return type is also double.

tlUuziraiicn
9

class Rint {
public void rint() {
double x = 20.224;
System.out.println("Value= " +Math.rint(x));
}
}
Output of the Program
r- \

Value=20.0
ON MATH FUNCTIONS/ 5

Use of pow() function.


Public class Power {
i

public void main() {


double x = 2, y = 3;
System.outprint("Value of x power y
= +Math.pow(x,y));
M

Output of the Program


Valueof x power y=8.0

Use of sqrt() function.


public class Square Root {
public void main( ) {
double x = 56.25;
System.out.print("Value of Squareroot of x =" +Math.sqrt(x));
}
}
Output of the Program
Value ofSquareroot of x = 7.5
o(l/iisfra(ion- •$
Use of max() function, public class Maximum {
public void main() {
double x = 56.25;
double y = 55.12;
System.out.print("Maximum Value of the Given Numbers =" +Math.max(x,y));
}
}
Output of the Program
Maximum Value of the Given Numbers =56.25
^(lustration-^
/
use of min( ) function.
public class Minimum { public void main() {
double x = 56.25; double y = 55.12;
System.out.print("Minimum Value of the Given Numbers =" +Math.min(x,y));
}
}
Output of the Program
Minimum Value of the Given Numbers =55.12

Use of floorAbs
class FloorAbs {
public
public void maln() {
double x e 56.25;
}

}
Output of the Program
Floor Value of the Given Number =56.0
Absolute Value of the Given Number =56.25
illustration- j
r Use of ceil() function
public class Celing {
public void main( ) {
double x = 56.75;
System.outprintlnfCeiling Value of the Given Number +Math.ceil(x));
}
}
Output of the Program
£2
Ceiling Value of the Given Number =57.0

illustration^}
Use of exp( ) function
public class Exp {
public void main( ) {
double x = 25;
System.out.prinU"Bcponential Value of the Oven Number Math.exp(x));
+

out tput of ihe Program


f'O' y

Exponential Value of the Given Number -7.20M89933738588E10


The Complete Reference Java 2
It constructs a new String by converting the specified
of bytes. **,
ub

String(byte[ ] bytes) int offset, int length)


It constructs a new String by converting the specified
of bytes. *Ubarr

String(byte[ J bytes)
t
It constructs a new String by converting the specified suba bytes using the specified character
encoding.
String(byte[ ] bytes, Int offset,
int length, String enc)
It constructs a new String by converting the specified arra
bytes using the specified character encoding.
String(byte[ ] bytes, String enc)
y of
It allocates a new String that represents the sequence characters currently contained in the
character array argum^
String(char[ ] value)
It initializes a newly created String object so that it represent the same sequence of characters
as the argument.
String(String value)
It allocates a new string that contains the sequence of character currently contained in the string
buffer argument.
String(StringBuffer buffer)
It returns the character at the specified index.
char charAt(\nt index)
Compares String to another Object.
compareTo(Object)
It concatenates the specified string to the end of this string.
String concat(String str)
It returns a String that is equivalent to the specified character.
Static String ValueOf(Object) boolean equals(Object anObject)
boolean equalsIgnoreCase (String
It compares a string to the specified object.
Compares this String to another String, ignoring case, considerations.
anotherString)
It converts the String into bytes according to the platform's default character encoding, storing
the result into a new byte array.
byte [ ] getBytes( )
It returns a hashcode for this string.
int hashCode()
It returns a canonical representation for the string object.
String intern()
int LastIndexOf(String str, intfromlndex)
It returns the index within this string of the last occurrence of the specified substring.
intlength()
It returns the length of this string.
String replace(char oldChar, char newChar)
It returns a new string obtained from replacing all occurrences of oldChar in this string with
newChar.
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
char[ ] toCharArray()
It converts this string to a new character array.
String toLowerCase()
It converts all the characters in this String to lowercase.
String toString()
This object (which is already a string) is itself returned.
String toUpperCase()
It converts all the characters in this String to uppercase using the rules of the default locale,
which is returned by
Locale.getDefault.
String trim()
It removes white space from both ends of this string.
static String valueOf(char[ ] data)
It returns the string representation of the char array argument.
static String valueOf(char[ ] data)
It returns the string representation of a specific subarray of* char array argument.
..if
grouping IS called a package. A package Is a name that stands for a set of related classes.
for example :
(i) java.io is a package which contains several classes for Java file streams,
(ii) java.lang contains several classes for math functions and Strings.
To use a package in the program, the same has to be imported in that prog
ram.
The java.lang package is available to the
program by default.
for example :
import java.io.*;
import java.lang.*;
etc
Some other packages
java.util
It provides language utility classes like vectors, hash tables, date, etc
java.out
It provides a set of related classes for implementing GUI. This package includes classes for windows, menus,
lists, buttons etc
java.net
It provides a set of classes for networking of computers.
java.applet
It provides classes for creating and implementing applets.
Creating Packages (Package Declaration)
We can create our own package. A package is declared by using the keyword package followed by the
package name.
Package statement is the first executable statement in the program.
For example:
package my Package; // package declaration
public class my Class // class definition
{
// body of class
In the above program segment, it is seen that after package declaration, class is defined. The class myClass
becomes a part of this package. The listing will be
by the file name as myClass.java and it will be located in a directory /.ft
mypacfcage* When you compile the program, Java will create a ,class fife and store it fn the I
directory, It is not possible to remove a package without renaming \M directory m which ^ cjr ;
t rrnyPa agp

stored. * & |s

Java also supports, package hierarchy. 1


You can specify multiple name, In a package statement separated by dots, I
For example : I
package my Package, nev/Pad cage; I
Using this approach, you can group related classes into a package and then group related packages
bigger package, * I
How to Access a Package ?
As alread/ mentioned, a package can be imported (accessed) using Import statement.
The import statement Is used to locate a list of packages of a particular class.
General Syntax —
import packagel [.packaged] [.package3].classname;
In the above synta/, packagel is the top package. package2 resides in packagel and so on their After

names, classname is specified.


The statement must end with a semicolon(;).
It must be noted that Import statement should be mentioned before class definition in a program file.
Multiple import statements are also alloy/ed in the programs.
For example:
import my Package newPackage.Class A;
St T

Here all the members of Class A can be accessed using the class name without using name of
package.
Package can be imported in the following manner-
import packagename.*;
In the above illustration, the program file (source file) is saved by the name myClass.java and is
saved in the subdirectory your Package.
The myCiass.class will be saved in the same subdirectory I.e. your package.
Jlluzlraiion
>••< — —^

public class ClassMine {


protected int i = 5;
public void dispdata() {
System.outprintln( Class Mine");
M

System.out.println("i is=" +|);


}
}
• - 5

Both the source file and package reside in the subdirectory abcPackage.
JAVA CLASSPATH
However,package solve many problems but they cause some difficultieswhen you complie
and run java programs. This is due to the reason that specific location that the java complier
considers as the root of any package hierarchy is controlled by
Consider the following package specification :
package MyWork;
in order to find MyWork, the program is executed from a directory immediately
path to MyWork for
M^—

execution of program. From that it can be known that either the program can be executed from
a directory above the package (MyWork) or using CUSSPATH may also be known that either he
program can be executed from a director above the package (mywork) or using CLASSPATh
which is set to include the path of the package (MyWork).
A sample program on a simple package
Class Bank { String name;
Double balance; Bank(String n, double a) {
name = n; balance = a;
}
void showdata() {
if (balance > 0) {
System.out.prmtln("Name = " +name);
System.out.println("Balance = " +balance);
}
}
>
class BankBalance {
public static void main(String argsf. ]) {
Bank current [] = new Bank (2);
currents = new Bank ("A", 1000.00);
current [1] = new Bank ("B", 2000.00);
for (int i = 0; i<2; f++)
current [i].showdata();
}

}
Output of the Program
Name = A
Balance = 1000.0
Name = B

Balance = 2000.0
The above program file BankBalance.java can be called and put In the directory called testpack
file. Ensure BankBalance.class files also exists in the directory testpack. The class can be executed ° *ft java
C ln

TestPack.BankBalance
While executing the above command, you have to be in the directories above Test Pack or to set e
to your CUSSPATH. Bank Balance becomes the part of package Test Pack. It cannot be itself
typing java Bank Balance. Bank Balance must be qualified with its package name.
merit
by
executed
You can follow the following steps to create working directories for package execution.
)
C:\>CD JDK1.3 (Assuming that JDK1.3 directory is already there)

C:\JDK1.3>MD TestPack (Creating a directory to save Java Package Files)

C:\JDK1.3>CD TestPack Changing current directory)

C:\JDK1.3\TestPack>javac BankBalance (if you are compiling the program in JDK1.3 at DOSPrompt)
C:\JDK1.3\TestPack>CD..
Make the necessary change in autoexec.bat file at C prompt.
SET PATH = C:\JDK1.3\TestPack
After that execute the program as below :
C:\JDK1.3>javacTestPack.bankbalance
Package Access Protection
Java provides various level of controls of protection to gain control over visibility of variable and methods within
classes, subclasses and packages. Both classes and packages are the means of encapsulation and for
containing the name, scope of variable and methods. Packages act as containers for classes and subordinate
packages. Classes act as container for data and code.
Due to their interplay between a class and a package, there are four categories of visibility of class members.
- subclasses in the same package
- non-subclasses in the same package
- subclasses in different packages
- classes that are neither in the same package nor subclasses
The access specifiers private, public and protected provide various ways to provide many levels of access required by
these categories.
Class Member Access private public
Same class
Same package subclass no yes yes
Same package non-subclass No yes yes

Different package subclass no yes yes

Different package class no no yes

It is obvtous from the above table that anything declared public can be accessed frpm anywhere but
the things declared private,,
importing Packages
java includes the important statement to ring some or all packages. After importing a package, a class can be
direcly referred to by only using its name. the important statement is very convenient tot he programmer and he is
not required to write complete java program.
The general from of the import statement is as follows:
import Packagelf.package2].(classname | *) }

The import statement immediately appears following the packge2 statement and before any class
definition.
In the above form, packagel is top level packge2 is the name of subordinate package inside the outer
package separated by a dot(.)
an

All the standard Java classes are stored in a package called java. All the basic javafunctions are stored
in the package which exists in java package called java. Lang compiler implicitly java lang . the
following line is added at the top of the java program
Import java ,.lang.*;
If any class exists in two different packages with the same name and you import it with
*form, the compilr remains silent. In such a case, you have to use one of the classes.
You have to explicitly name the class specifying its package.
import java.utif.*;
class SampleDate extends Date {
………..
}
The above example without the import statement would be as follows - class SampleDate extends
java.util.Datef) {
••

}
When a package is imported, items within the package that is declared public, are only available to non-
subclasses in importing program code.
Package testpack; class Bankl {
String name; double balance;
Bankl(String n, double a) { name = n;
balance = a;


««.*

}


void showdataf) {
r

if(balance>0) {
System.out.println ("Name = +name);I
M

System.out.println("Balance = " +ba\ance);


}
}
V

For example, If you want that the class Bankl of the package test pack, already given
»n the previous program, to be available for general use outside testpack, you have to declare it as
public by mentioning
package testpack;
After giving the above declaration, the class Bankl, its constructor and showdata( ) method become
They can be used by non-subclass program code outside the package too.
The Bankl class in the above illustration has become public. Its constructor and showdata() method
also become public. They can be accessed by any type of code from outside the testpack package.
In the example given below, the class Balances imports testpack and makes use of the bank class.
class Balances {
public void main( ) {
//bank class is public
//use Bank class and call its constructor Bank current = new Bankf'A", 1000.00);
current.showdata( );
-

}
The complete combined program using the above sequence has been given below
- //public class for declaring a package,
class Bankl {
*

//class Bankl, its constructor is public, //method showdata is also public


String name;

double balance;
•V

Bankl(String n, double a) { name = n;


balance = a;
>
void showdata() {
imbalance > 0) {
-
-

System.out.println("Name =" +name);


System.out.println("Balance = " +balance);
}
}
Balances {
public void mato() {
//Bankl class is public
//use Bankl class and call its contractor.
Bankl current « new Bankl ("A", 1000.00);
current.showdata();
}
INTRODUCTION TO INTERFACES
A group of method declarations to provide basic functionality to classes to share common behaviour or
needs is called an interface.This allows Java classes to deal with multiple class hierarchy. Declaration of
interface introduces a new reference type whose members are constants and abstract methods.
An interface can be declared to act as a direct extension to one or more interfaces.Interfaces are almost
similar to classes but they lack instance variables and do not using the implementshave anybody for their
methods declaration. By using an interface, we can specify what a class should do but not how it should
do.It is necessary that a class must create the complete set of methods defined by the interface.
Defining an Interface
An interface is defined much like a class. The general form of an interface has been given below :
access interfacename {
return-type method_namel(parameter list);
Return-type method jiame2(parameterjist);
type flnal-variablel * value;
type final-variable2 • value;
//
return-type method_nameN(parameterJlst)
type final-variable • value;
}
In the above syntax, the access is either public or not at all used. When no access specifier, in such a
case, the default access results. In this case, interface is only available to the other members of the
package in which it is declared. When the access specifier is declared public, it can be used by any other
program code. The name Is the name of the interface and can be any valid identifier. The
methods which are declared have not body(ies). The methods end with a semicolon after the parameter
list. As mentioned earlier, there can be no default implementation of any method specified within an
interface because they are essentially abstract methods. The class which includes an interface must
implement all the methods.
Implementing Interfaces
A class can implement an interface by using the keyword implements in the code. It stout be'm^* class can only
extend one other class but ft can implement as many interfaces ft wants to Inclde.
A class can Implement multiple interfaces according to the following validity :
—Interface extends interface
Hp
—class extends class
—class Implements Interface
Once the Interface Is defined, one or more classes can implement the same. To implement an faterfeo^
Implements clause Is used in a class definition and then the methods are created defined by the mtsrfe* *
:

The general form of implements clause Is shown below ;


access class classmate[extends super class]
[Implements interface^ Interface...]]
// class-body
}
In the above syntax, access is either publicly declared or not at all. In case a class implements more ftanog
interface, the interfaces are separated by comma.
When a class implements two interfaces that declare the same method, in such a case the same method be
used by the members of either interface.
WM.

The methods that implement an interface should be declared public and the type signature of the implementi
methods should also match with the type signature specified in the interface definition.
-

illsiraiion
class employee implements Back { //implements the Back's interface
public void call it(int value) {
-It

System.out.println ("cal lit will be called with " -f-value);


}
}
In the above illustration, class implements the Back interface.
The callit( ) method is declared using the public access specifier since it is a must to declare the method to be
public when you implement an interface method.
Sfe*

Look at the following example :


*

class employee implements Back {


//implements the Back's interface
'it 1

public void callit(int value) {


System.out.println("callit will be called with " +value)" }
void nonIntface() {
System.out.println("Classes implementing Interfaced "define other members also");
}
}
e above example, the class employee implements callit() method and adds the method
In th

nonIntface().
• JAVA LANGUAGE PACKAGES
The java.lang package is automatically imported into every Java Program. This package provides a
number of classes, interfaces, classes for errors etc.
The java.lang package includes the following classes:
class Boolean
class Byte
class Character
class Class
class Class Loader
class Compiler
class Loader
class Double
class Float
class Integer
class Long
class Object
class Thread
class Runtime
class Short
J
class String
class Math
class Number
class Runtime
class Void
class Throwable
Java
class RuntimeException class AbstractMethodError etc.
Interfaces included in java.lang package :
Interface Runnable Interface Comparable Interface Cloneable
Simple Type Wrappers
Primitive data types are not used as objects in Java. These types include numbers, booleans and
characters. Some Java classes and methods need primitive data typesto be objects. Simple types
like int and char are used in Java but already mentioned, these are not the part of object hierarchy.
They are passed by value to the methodsand not directly by reference. Java also provides
enumerated classes, which dealonly with objects to store a simple type in one of these classes.
There is a need to in Java, you have toWhile writing programswrap the simple type in a class. These
classes wrap(encapsulate) the simple types within a class. These are also commonly known as type
wrappers.The following is a list of primitive data types that java.lang package supports : make the
program as such that it might ask forvalue as input from the input device.The Byte, Short, Integer and Long
classes provide
parseByte(), parselntQ and parseLong()
methods. You have already seen some
; programs written in this book, have made the
use of parselnt() and parseLong() methods.
Wrapper Classes
Double
Character
Byte Integer
Boolean
Short
Long
Float
Number
The class Number is an abstract class and it is a superclass of classes like Byte, Double, Float
Integer, Long and Short. It is implemented by the classes that wrap
the numeric data types. The Number class constructor is written as Number().

These data types are :


short
long
int
byte
float double
The Number class returns the value of the object in different number formats.
For example, doubleValue() returns the value as a double, longValue() returns the value as
long
so
Double and Float
Double and Float are wrapper for floating point values of type double and float.
•'

The constructors for the Float wrapper are :


Float(double num)
Float(float num)
Float(String str) throws NumberFormatException
The Double class wraps a value of primitive type double in an object. Float objects can be
constructed v, float or double.
Byte
The Byte class is a wrapper for byte integer type.
The constructor for Byte class is shown below :
Byte(byte num)
Byte(String str) throws NumberFormatException
It is visible, these objects can be created from numeric values or from strings that contain valid whole
number(s).
Short
The Short class is a wrapper for short integer type.
The constructor for Short class is shown below : Short(short num)
Short(String str) throws NumberFormatException
It is visible, these objects can be created from numeric values or from strings that contain valid whole
number(s).

Integer
The Integer class is a wrapper for integer type.
The constructor for Integer class is shown below :
Integer(int num)
Integer(String str) throws NumberFormatException
in valid whole
numbed strings that conta
Long
The Long class is a wrapper for long integer type.
The constructor for Long class is shown below :

Long(long num)
Long(String str) throws NumberFormatException
It is visible, these objects can be created from numeric valuesor from strings that contain
validwhole following program will show the use of parselnt{
)Use ofparseInt() method.
//Converting a decimal number into binary.

••

import java.io.*;
class Parselnt {
public static void main(String args[ ]) throws IOException { Parselnt numb = new Parselnt();
//to read bytes and translate them into characters according to specified character string.
InputStreamReader reader = new InputStreamReader (System.in);
//to create buffering character input stream //to use default sized input buffer.
Buffered Reader input = new Buffered Reader(reader); System.out.printlnfEnter Number
=");
String number = input.readLine(); //using parselnt
int n = Integer.parselnt(number); System.out.printlnfBinary Value of the Number =");
numb. binary(n);
•-

}
void binary(int n) {
int m[ ] = new lnt[10];



int j;
for(j = 8;j>=l;h-) { m[j] = n % 2;
n = n / 2;
••

>
for(j = l;j<= 8;j++) System.out pnntln(+m[j]
);
i•

}
•f

}
Output of the Program
Enter Number = 12
Binary Value of the Number = 0 0 0 0 1 1 0 0
Character Type
Character is a simple wrapper around a char. The constructor for Character is mentioned
below.
Character(char chr)
The Character class wraps the value of primitive type char in an object. In the above syntax
the character that will be wrapped by the Character object being created.
To obtain the char value from Character object, the char Value() method is called
char charValue()
illustration
class Charact {
public static void main(String args[ ]) { char chr[ ] = {'A', 'b', 'C, '5'};
for(int i = 0; i < chr.length; i++) { if(Character.isLetter(chr[i])) {
System.out.println(chr[i] + " is a Letter");
}
if(Character.isDigit(chr[i])) { System.out.println(chr[i] + " is a Digit");
}
if(Character.isUpperCase(chr[i])) {
System.out.println (chr[i] + " is an Uppercase Letter");
}
if(Character.isLowerCase(chr[i])) {
System.out.println (chr[i] + " is a Lowercase Letter");
}
}
Output of the Program
A is a Letter
A is an Uppercase Letter
b is a Letter
b is a Lowercase Letter
C is a Letter

C is an Uppercase Letter lit


The System Class
The system class contains a collection of static methods and variables. The standard input , output
and error output of java runtime are available in the in, out and err variables.
ClassMethod
objects of type Class objects are automatically created when classes are loaded. A Class object
cannot bo ?! lared explicitly. You can obtain a class by calling the getClass( ) method defined by the
object. Primitivedata types in Java ; boolean, byte, char, short, int, long, float, double and the
keyword void are represented class objects.There is no public constructor for the class Class.
by

Objects for class are automatically constructed and called by Java.


Look at the following segment:
void printClassName(Object ob) {
System.out.println('The class of object" -fob + "is "+ob.getClass( ).getName());
}
In the above segment, Class object has been used to print the class name of the object.
Class Loader Method
The ClassLoader is an abstract class, which defines how classes are loaded. Applications
implement subclasses of ClassLoader.
The method defineClass( ) converts an array of bytes into an instance of class Class. The methods
and constructs of objects created by the class loader may reference other classes. The ClassLoader
allows to loadclasses in some different way other than the normally loaded class by Java run-time
system. For example, an application can create a network class loader to download class files from
server.
Math Class Method
The Math class consists all the floating-point functions, which are used for various mathematical
calculations.
Method Definitions by Math Class Methods
Description
Method
It returns the sine of the angle specified by arg in radians.
static double sin(double arg)
It returns the cosine of the angle specified by arg in radians.
static double cos(double arg)
It returns the tangent of the angle specified by arg in radians.
static double tan(double arg)
It returns the angle whose sine is specified by arg.
static double asin(double arg)
It returns the angle whose cosine is specified by arg.
static double acos(double arg)
It returns the angle whose tangent is specified by arg.
static double atan(double arg)
It returns the square root of arg.
static double sqrt(double arg)
It returns the absolute value of arg.
static double abs(double arg)
It returns the absolute value of arg.
static long abs(long arg)
It returns the absolute value of arg.
static float abs(float arg)
It returns the maximum value of x and y.
static double max(double x, double y)
It returns the maximum value of x and y.
static long max(long x, long y)
It returns the maximum value of x and y.
static float max(float x, float y)
It returns the minimum value of x and y.
static double min(double x, double y)
It returns the minimum value of x and y.
static long min(long x, long y)
It returns the minimum value of x and y.
static float min(float x, float y)
present in even position of this number. ^ (*e /?
a s c a

a
program which accepts a word from keyboard and displays the characters present in
even position of this number.
1.
answer.
class Even Position {
public void even(String s){
S=S+
II II-

int i, len;
int x = 0;

System.out.print ("You have entered the string= +s); M

System.out.print("\n");
len = s.length();
-

System.out.print ("Characers at Even Position ");


for(i = 0; i < len;
if((i - 1) % 2 == 0) System.out.print(s.charAt(i));
System.out.print ("");
m
Write a program to input a sentence and print the number of characters found in eachword of the given
sentence.
class LongestWord {
public void WordSize(String str) { char ch;
str = str + " "; int len = 0;
int x = str.length( );
System.out.print ("Enter the sentence::" +str); System.out.print("\n");
for(int i = 0; i < x ; i++){
ch = str.charAt(i);
2.
B-swer.
-



if(ch!="){ System.out.print(ch);
len = len + 1;
*

if(ch=="){
...

System.out.println(" : The Size is " +len + " characters");


len = 0;

Syrtem.oiii,pri i(“/n’)
n

}
}
}
}

. Wrffr .i 'program In Java to enter a


mm tin and and present in t/w sentence. Class Wordcounl {
out keyheard .nut count the number of
MS
public void count (String text) { Int andcount w 0;
Int Ihccount - 0; Int Index a -1;
String ondstr « "and";

lndex«texUndexOf(andstr); whlle(lndex >= 0) {


++andcount;
Index += andstr.length();
Index = text.lndexOf(andstr,lndex);
}
String thestr = "the"; index=text.indexOf(thestr);
whlle(lndex > = 0){
++thecount;
Index += thestr.length();
Index = text.indexOf(thestr, Index);
}
System.out.prlntln("Number of 'and* =" +and count); System.out.prlntln("Number of 'the' ="
+thecount);
4. Consider the following statement :
"January 26 is celebrated as the Republic Day of India ".
Write a program to change 26 to 15, January to August, Republic to Independence and finally
print "August 15 Is celebrated as the Independence Day of India ".
-

'•^Answer, public class Republic { public void main() {


String s - "January 26 is celebrated as the Republic Day of India";
int positionl = s.indexOffJanuary 26");
int len = s.length();
int lenl = "January 26".length();
String str = s.substring(lenl + 1, len);
String si = "August 15 " +str; int Ien2 = sl.length();
int position2 = sl.indexOff'Republic "); int Ien3 = "Republic".length();
String s2 = si.substring^, position2);
String s3 = sl.substring(position2 + Ien3 + 1, Ien2);
System.out.println("Final String=" +s2 + " Independence " +s3);
}
}
5. Write a program in Java to enter a String and displays the first alphabet of each
Council Indian Secondary Certificate Examination
Sample Input : Sample Output :CISCE
Answer, class ShortForm {
public void main(String a) { int x, y;
char b;
System.out.printlnfYou have entered the string=" +a); x = a.length();
char c = Character.toUpperCase(anchoret(0)); System.out.print(c+ ".");
for(y = 0; y < x; y++) { b=a.charAt(y);
if(b == '')
System.out.print (Character.toUpperCase(a.charAt(y + 1)) + ".");
}
}
}
6. Write a program to accept three strings from the keyboard and arrange them in the
order of their lengths. Answer, import java.io.*;
public class Arrange Strings {
public static void main(String args[ ]) throws IOException {
String si, s2, s3;int II, 12, 13;
DatalnputStream d = new DatalnputStream (System.in);
System.out.printlnfEnter three strings");
S1 = d.readl_ine( );
s2 = d.readLine( );
s3 = d.read!_ine( );
System.out.println("You entered "+sl+", "+s2+" and "+s3)- II = sl.length();
12 = s2.!ength(); 13 = s3.length();
if(!l <BQU 12 <= 13) {
System.outprtntln(sl +if(ll <=!3 &8t!3< = 12) {
+

System.out.print!n(sl + +S2);
}
if(!2 <= II &&I1 < = 13) {
System.out.println(s2 + , + si + “,” + s3);
}
if(l2 < = 13 13 < = II) {* S3 4 "/ 4 si)
;
System.out.println(s2 +
If «

}
if(!3 < = II && II < = 12) {
System.out.printIn(s3 + •r si +"/ + s2);
i

}
if(l3 < = 12 && 12 < = II) {
System.out.println(s3 +
+ s2 + V + si);
}
}
Write a program to accept a sentence and print only the first letter of eac± word the sentence in
capital letters separated by a full stop.
Example :
INPUT SENTENCE : "This is a cat" OUTPUT : T.I.A.C.
Answer, class ShortForm {
public void main(String a) { intx/y;
• char b;
System.out.println("You have entered the string
+a);
x = a.length();
char c = Character.toUpperCase(a.charAt(0)); System.out.print(c+ ".");
for(y = 0; y < x; y++) { b=a.charAt(y);
if(b == '')
System.out.print(Character.toUpperCase(a.charAt(y+l))+ ".");
}
}
}
| Design a class to overload a function Joystring( ) as follows ;
(I) void Joystrlng(Strlng s, char chl, char ch2) with one string and two char
that replaces the character argument chl with the character argument dS* 9um string s and points the new
ar

string. in th ^tj
2 e

Example:
Input value of s - "TECHNALAGY"
chl = 'A', chl - 'O'
Output : "TECHNOLOGY"
(//) void Joystring(String s) with one string argument that prints the position of th
and the iast space of the given String s. st ^
e f,r

Example : First Index : 5


Last Index : 36
(III) void Joystring(String si, String s2) with two string arguments that combines strings with a space between
them and prints the resuitant string. h
he

Example :
Input value of si = "COMMON WEALTH"
s2 = "GAMES"
Output : "COMMON WEALTH GAMES"
wer. class Overloading {
void Joystring(String s, char chl, char ch2) {
System.out.println("Entered String is :");
System.out.println(s);
System.out.println("New String is :");
System.out.println(s.replace(chl ch2));
f

}
void Joystring(String s) {
System.out.print("Entered String is :");
System.out.println(s);
System.out.printlnC'Char 'First Space' at first occurence: "+s.indexOf(''));
System.out.println("Char last Space" at Last occurence: "+s.lastIndexOf(''));
}
void Joystring(String si, String s2) {
String S3 = ""; //creating a blank space
String s4 = sl.concat(s3); //adding a blank space to first String. String s5 = s4.concat(s2);
System.out.pr/ntln("String concat using String concat method • " + s5V >
>
CANDID ICSE COMPUTER APPLICATIONS- ' 0

Write a program that encodes a word into Piglatin. To translate word into a Piglatin word,
convert the word into uppercase and then place the first vowel of the original
word as the start of the new word alongwith the remaining alphabets. The alphabets present
before the vowel being shifted towards the end followed by "A Y".
Sample input (1): London, Sample output(l): ONDONLAY
Sample input (2): Olympics, Sample output(2): OLYMPICSAY (From ICSE Exams)
Answer, import java.io.'
class PigLatin {
public static void main( )throws IOException {
Buffered Reader in = new Buffered Reader(new InputStreamReader(System.in));
System.out.print("Enter the String: ");
String s = in.readLine(), n="";
String strUpper = s.toUpperCase(); System.out.printlnfOriginal String:" +s);
System.out.printlnfString changed to upper case:"+ strUpper); char ch;
boolean b = false;
for(short i = 0; i < s.length(); i++) { ch = strllpper.charAt(i);
(ch == W || ch == »E' II ch == T || ch == '0' ||ch == V || ch == 'a' || ch == 'e' || ch == T || ch == V || ch
if

=='u')
b = true;
if(b == true) n+=ch;
}
for(short i=0; i<strUpper.length(); { ch=s.charAt(i);
if(ch == W || ch == 'E* ||ch == T || ch == '0' || ch == || ch == 'a' || ch == 'e' ch == Y || ch == 'o' || ch ==
V)
break;
n += ch; }
n += "AY";
System.out.printfWord in PigLatin: "+n);
}
}
Write a program in Java to read a string from console and replace all occurrences of the
sixth character of the string by the digit 9.
Gteswer. import java.io.*;
class Character Digit {
void replace String() throws IOException {
Busffered Reader reader = new Buffered Reader(new InputStreamReader (System. in));

System .out.prinitin (“string is ::’);

String n =reader.readeline();

Char x =n.replace(x,”9”);

System.out.print(“the output string is =”+chr);

Public static void main(string args[])throuws IOException {

Character Digit c = new character digit();

c.replacestring();

You might also like