Chapter 11
Chapter 11
Chapter 11
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:
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.
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.
example:
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
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);
#
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
-
/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 ( ));
}
}
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()
-
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 ("Same Thing ?" + (s1 == s2));
s2 = new String (s1) ;
S
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:
-
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
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
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
}
}
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 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));
+
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
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
>••< — —^
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\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
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
}
}
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 {
*
double balance;
•V
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
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().
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
•
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("\n");
len = s.length();
-
if(ch!="){ System.out.print(ch);
len = len + 1;
*
if(ch=="){
...
Syrtem.oiii,pri i(“/n’)
n
}
}
}
}
++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 ".
-
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 :
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));
String n =reader.readeline();
Char x =n.replace(x,”9”);
c.replacestring();