Soda Chapter 9

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

Chapter 9

Java provides various in-built data types. These in-built data tyres are called
primitive data types. There are S primitive data types -
byte, short int, long, float, double, char and boolean. You can create your own
data types in Java programs by using primitive
data types. The 6ata types that are based on primitive data types are called
Composite data types. Since these data types are created
by the user according to his own convenience, these data types are also called
user-defined data types. Since these data types are
created through Classes, let us see in details as to how classes form the basis for
creating user-defined data types.

Class as composite data type


A class is a good example of composite data tyepe.
Let us have a look on the following program segment-
What is an object ?
class Compdatatype {
int a;
double b;
bytec; float d;
char e;
public void Havedata() {
___________
__________
}
public void Output() {
__________
_______
}
}
in the above segment, you will see that primitive data types have been used viz
int a;
double b;
byte c;
float d;
chare;
After the class is declared, you can declare the variables of the class as follows-
Compdatatype obj = new Compdatatype( );
Variables of a class are also its objects.
Therefore, a class is a composite data type.

* CLASS AS USER-DEFINED DATA TYPE

A Java programmer can create software objects by taking help of either user- defined application
specific classes or pre-defined library classes.
Therefore, Javaprogram involves class definitions and creating objects out of them for
computational interactions
.
A class can be regarded as a user defined data type template to produce as many desired objects as
required. A class can make use of both instance and function
variables of simple data types like int, float, double, boolean, char etc.

At times, a programmer may need to represent a simple data type as an object of its Java-defined
wrapper class. Such wrapping of a simple data type helps in utilizing
the methods available with the wrapper classes.
0vides wrapper class or each simple data type. Such type wrapper classes in defined in the
JaVa

java.lang package, which automatically gets included with , lava program you write. Subsequent
re

examples will make this wrapper conception


ore clea n

a collection of member variables of primitive and/or composite data types 'H member methods or
s is C S

functions capable of accepting argument(s) of different

•mitive and/or class types. Each method can either return a value of specified Hirn data type or no
P

output value as indicated by void.

A programmer can easily


M ndle objects created out of such a composite class structure by specifying the lass-name as a
user-defined data type. That is why, a class can also be regarded as
an augmentation of permissible data types.

p e, a class named Student with several instance variables and methods has n defined by a
0S bee

programmer in a Java program. She/He can create several

student objects simply by using the statements as shown below :

Student si = new Student ();

Student s2 = new Student ();

Student sn = new Student ();

Thus Student acts as a special composite data type referring to the class structure — Student.
Difference between Primitive and User-Defined Data Type
Primitive Data Type User-Defined Data
(i) Sizes of primitive data types are (i) Sizes of user-defined data types
fixed. are variable
(ii) These data types remain .(ii) These data types remain available
available in all parts of the according to programs.
programs. (iii) These data types are created by the
(Hi) These are built-in data types in user according to the program(s).
Java language.
(iii)

Composite data type


The data types that are based on primitive data types are called composite data
types
Primitive data types

int short byte long float boolea


double chart
n

There are 8 primitive data types in java. You can use any of the above data
types or you can create your own data types. Any data type you want to create
would be created using primitive data types.
* WRAPPER CLASSES FOR THE PRIMITIVE DATA TYPES

In fact,java provides so-called wrapper classes for the primitive data types. Each primitive data type has an associated
class that typically has the same name as the data type, but starts with a capital letter (except for int and char, where the
name of he wapper class is different).

Primitive data type Corresponding wrapper class

Byte Byte
Short Short
Int Interger
Long Long
Float Float
Double Double
Char Character
boolean boolean
HOW TO CREATE NEW OBJECTS ?

When we have to write Java programs, we have to define a set of classes. Classes are templates which
create objects. The objects are self-contained elements.
To create a new object, the new operator is used with the name of the class for which you want to create an
instance followed by parentheses.
For example:
String name = new String();
In the above example, the parentheses are empty. In this usage, the most simple object is created.
However, these parentheses can contain arguments also.
For example :
String str = new String(4,2);
The number and type of the arguments within the parentheses with new are
defined by the class itself by constructor.
The keyword newis frequently used in array handling and string modifications.
Getting Values : We can get value of an instance variable by using dot (.) operator.
By using dot notation, an instance or class variable name has two parts.
General form
Object reference.variablename;
For example: Rectangle, perimeter;
§ above example, one is reference to an object or reference to an object or class on the left side of
the dot and second is reference to the variable called perimeter. This form is also called an
expressin and
lM nd is reference to the variable on the right sideof
sec0

this example, we have an object assigned to variable called perimeter. This form sides of the
dots are also called expres from left 9 egressions are evaluated
t0 r, hL

Changing Values : The process of assigning value to a varfchi to apply an assignment operator to
the right side of
Rectangle. Perimeter = 12.0;
This example assigns the value of 12.0 to the perimeter of a rectanale
Class Variables -yie

Class variables are those variables which arre defined and storeeed in the class itself. Their
values are applicable to the class and all the instance of that class.
Each new instance of the class can get a new copy of the those instance variable that is without
by the class. Each instance can change the value of the those instance variables without affecting
any another any other instances.
Class variables can be defined by the keyword static before the variable itself.
Look at the following program segment:

class Employee {
static String empname = "Narinder Shastri",'
String name;
int age;
}
In the above program segment, instances of the class Employee have their own value for names
and age. The class variable empname has only one value for all
the family members i.e., Narinder Shastri. If you change the value of empname, all instances of
Employee are affected.
For accessing the class variables, you have to use the dot notation with instance variables.

Class variables are also known by the name


static variables.
Static Variables
While writing Java programs, we have frequently used a keyword static.
For example:
Public static void main(String argsf ]) {
Here the keyword static Is a modifier.
The modifier Is used to create class methods and variables.
'-—w

Look at the following program in which static modifier has been used.
public class QrclePerlm {
public static float pi = 3.141459265F;
return pi * radius * 2;
What Is a variablo ?
}
}
The keyword static refers to the fixed state. If a class has a static variable,
And every object of that class has the fixed value for that variable.
each
Look at the following program segment:
Class Measurement {
Static String measure = "Cms.";
Double length;
}
In the above program segment, Instances of the class have their own value for length but the class
variable measure has only one value for all lengths i.e. Cms.
This value is static for all objects, but in case you change the value for measure, all objects of
Measurement are affected.
Operation on Objects
Let us have a look on operations on objects through the following program segment :
class Operation { //Data Attributes
int km, mt, cm; //methods (behaviour)
void printdata() {
System.out.println(+km+"-"+mt+"-"+cm);
}
void measure(int k, int m, int c) {
km = k;
mt = m;
cm = c;
}
In the above segment, complete definition for the class Operation has been given. The Operation
class has three variables of int type namely km, mt and cm. Setting
measure means setting values for these data. A method measure( ) has been used for doing this
measure. Another method printdata() has been used to print the
values of all these variables.
Let us understand the action of these methods.
Let uus understand the action of these methods.
The body of a method is the part beginning from brace ({)upto the ending or bramce (})
the printdata()method has to do nothing tween the br ces. It doesgenerate any new object
^ the keyword void precedes its name in its header. The printdata() metho println() e59

methodI .n -ts body. h method measure( ) requires three values for km, mt and cm. These
T e

lues can be supplied bdeclaring three mt variables in its header. These variable are
parameters. These arameters are also called dummy parameters since you can use any
name in place of k, m and c while
m/oking this method. The header could be like the following also-
void measure(int, int, int)
This process is also called signature of the method. Let us have a look on the invoking of
this method in the
following program :
class Temp {
public void main() {
Operation m = new Operation( );
m.measure(15 10 12);/ /

m.printdata();
}
}
In the above program, the main method in the Temp class declares m as a measure
object and creates the same by using the new keyword. The message is passed to m in
the next line to measure the data as
The message is then passed to print the measure. The output of the program will be as
under:
15-10-12
Let us have another idea after modifying the Temp class, class Temp {
public void main() {
Operation m = new Operation();
Operation ml = new Operation(); m.measure(15,10,12);
ml = m; m.printdata();
ml.printdata();
}
1

After the above program is Compiled and run, the following will be the output of the
program :
15-10-12 15-10-12
In the above program, we have defined another object ml of class Operation. Instead of
setting measure for it by using measure() method, the ml Operation has been copied on
to it. After the print of the output, you
will see that both the measurements are alike.
Creating and using objects
As you know, a class provides the blueprint for objects; you create an object from a class.

Point originOne = new Point(23, 94);


Rectangle rectl = new Rectangle(originOne, 100, 200);
Rectangle rect2 = new Rectangle(50, 100);
The first line creates an object of the Point class and the second and third lines each create an object of ^
Rectangle class.
Each of these statements has three parts:
1. Declaration : The code set in are all variable declarations that associate a variable name with
an object type.
2. Instantiation : The new keyword is a Java operator that creates the o je .
, . tn T\ constructor, which initializes thp no,
3. Initialization : The new operator is followed by a call to a const uie new
object.
Declaring a Variable to Refer to an Object
A variable can be declared in the following manner:
type name) ...... . ...
This notifies the compiler that you will use name to refer to data wnose iyy
this declaration also reserves the proper amount of memory for the vanaoie.whose type is type. With a
primitive variable
You can also declare a reference variable on its own line. For example:
Point one; „ ....
If you declare one like this, its value will be undetermined until an object is actually created and ass.gned to t
Simp* desiring a re e en e variable does not create an object. For that, you need to use the ^ operator,
as in the next section. You must assign an object to one before you use ,t m your code. Otherw.se,
you will get a compiler error.
A variable in this state, which currently references no object, can be illustrated as follows (the variable name
one, plus a reference pointing to nothing):
one

Instantiating an Object
Instantiation means allocating space for a new object. The new operator in Java instantiates a class by
allocating memory for a new object.
The name of the constructor provides name of the class to instantiate. The new operator returns a reference
to the object which it has created.
It should be noted that there is a difference between instantiating an object and declaring an object.
Declaration does not create any new object. It only declares a variable.
For Example :
Object x;
It does not create any object. The reference is empty until it is assigned and this empty reference is called
null reference.
On the other hand, instantiation creates a new object.
Object x = new Object( );
In the above statement, an object is being created The name of the constructor provides the name
of the class to instantite.
//pmgmm to find current date and time
import java.util*;
class DateFind {
public void main() {
Date dt = new Date( )•
System.out.printlnf'The Date is=" +dt);
}
}
In the above program the statement Date dt = new Date();
How can you create objects ?
creates the Date object dt and initializes it with the system date
The output of the above program will be similar to the following :
The Date is = Tue Jul 06 28 22:40:12 EST 2015
Initializing an Object
An object can be initialized by passing initial values as constructor's arguments
Observe the following code for the Point class: arguments.
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor
in the Point class takes two integer arguments, as declared by the code (int a, int b). The following
statement provides 30 and 80 as values for those arguments:
Point one = new Point(30, 80);
The result of executing this statement can be illustrated in the following figure:
A point object
One

X
3
o
y
One 8

Using Objects
A typical Java program creates many objects, which as you know, interact by invoking
methods. . have created an object, you probably want to use it for something. You may
0nce

need to use the value of ^ 0f

its variables, change one of its variables or call one of its methods to perform an action.
Once an object has completed the work for which it was created, its resources are recycled for
use by other
objects.
Here's a small program, called CreateObjectDemo, that creates three objects: one Point
object a Rectangle objects.
public class ObjectCreation {
public static void main(String args[ ]) {
// Declare and create a point object and two rectangle objects

Point originOne = new Point(23, 94);


Rectangle rectl = new Rectangle(originOne, 100, 200);
-

Rectangle rect2 = new Rectangle(50, 100);

// display rectl's width, height and area


System.out.printlnfWidth of rectl: " + rectl.width);
System.out.printlnfHeight of rectl: " + rectl. height);
System.outprintlnfArea of rectl:" + rectl.findArea( ));

// set rect2's position


rect2. origin = originOne;

rect2's position
// display
System.out.println("X Position of rect2: " + rect2.origin.x);
System.out.println("Y Position of rect2: " + rect2.origin.y);
// move rect2 and display its new position
rect2.move(40, 72);
System.out.println("X Position of rect2: " + rect2.origin.x);
System.out.println("Y Position of rect2: " + rect2.origin.y);
*

}
}
This program creates, manipulates and displays information about various objects.

Referencing an Object's Variables


Object variables are accessed by their name. You must use a name that is unambiguous.
You may use a simple name for a variable within its own class. For example, we can add a
statement within the rectangle class that prints the width and height
System.out.printin(“width and height are:”+++width+”,+height);
In this case, width and height are simple names.
Code that is outside object’s class must use an object referne of expression, followed by
the dot.() operator, followed by a simple variable name, as in:
Object reference.variablename
For example, the code in the object creation class is outside the code for the
rectangle class. So to refer to the origin, width and height fields within the
rectangle named rect1, the object creation class must use the name
rect1,orgin,return.width and rect1.height,respectively. The program uses two of
these names to display the wifth and the height of rect1.
System.out.printin(“width of rect1:”+rect11.width);

System.out.printin(“height of rect1:”+rect11.height);

Attempting to use the simple names width and height from the code in the object creaction class doesn’t
make sense- those fields exist only within an object-and results in a computer error latre, the program uses s
m.lar code to display information about rectl Objects of the same type have their o n copy of the same
W

instance fields. Thus, each Rectangle object has fields named origin, width and height.
When you access an instance field through an object reference, you reference that particular object's field.
two objects rectl and rect2 in the ObjectCreation program have different origin, width and height fields.
To access a field, you can use a named reference to an object, as in the previous examples or you can use
any expression that returns an object reference. Recall that the new operator returns a reference to an
object. So
you could use the value returned from new to access a new object's fields:
te

int height = new Rectangle( ).height;


This statement creates a new Rectangle object and immediately gets its height. In essence, the statement
calculates the default height of a Rectangle. Note that after this statement has been executed, the program
no longer has a reference to the created Rectangle, because the program never stored the reference
anywhere.
The object is unreferenced and its resources are free to be recycled by the Java Virtual Machine.
Calling an Object's Methods
You also use an object reference to invoke an object's method. You append the method's simple name to the
object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any
arguments to the method. If the method does not require any arguments, use empty parentheses.
objectReference.methodName (argumentList);
or
objectReference.methodName();
The Rectangle class has two methods: findArea() to compute the rectangle's area and move() to change the
rectangle's origin. Here's the ObjectCreation code that invokes these two methods:

System.out.println("Area of rectl: • + rectl.findArea());


•••

rect2.move(40, 72);
The first statement invokes rectl's findArea() method and displays the results. The second line moves rect2
because the move() method assigns new values to the object's origin.x and origin.y.
As with instance fields objectReference must be a reference to an object. You can use a variable name, but
you also can use any expression that returns an object reference. The new operator returns an object
reference, so you can use the value returned from new to invoke a new object's methods:

new Rectangle(100, 50).findArea()


The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle ob,.
shown, you can use the dot notation to invoke the new Rectangle's findAreaf()method to compute
th * e

the new rectangle. Some methods, such as findArea(), return a value. For methods that return a
01

value, you can use the method invocation in expressions. You can assign the return value to a
variable, use£toi mate decision or control loop. This code assigns the value returned by findArea()
to the variable areaOfRectangle:
int areaOfRectangle = new Rectangle(l00, 50).find Area();
Remember, invoking a method on a particular object Is the same as sending a message to that
object. , case, the object that find Area() is invoked on is the rectangle returned by the
h h

constructor.
Example :
In this example, we are creating two objects of Student class and initializing the value to these
objects invoking the insertRecord method on it. Here, we are displaying the state (data) of the
by

objects by Invoking &,displaylnformation method.


class Student {
Int rollno;
String name;
void insertRecord(int r, String n) { //method
rollno = r;
name = n;
}
void displaylnformationf) { //method
System.out.println(rollno + "" + name);
}
public static void main(String args []) {
Student2 si = new Student2();
Student2 s2 = new Student2();

sl.insertRecord(205, "Parth");
s2.insertRecord(101, "Deepak");

sl.displayInformation();
s2.display!nformation();
}
}
Output of the Program
205 Parth
101 Deepak

As you see in the above figure, object gets the memory in Heap area and reference variable refers
to the object allocated in the Heap memory area. Here, si and s2 both are reference variables that
refer to the
objects allocated in memory.
Another Example: How to create an object of the class and call the member methods i
By now you must have an idea that new operator is used to create an object of a class.
Let us have a look on the following example :
class Library {
int id; //data member (also instance variable)
String title; //data member(also instance variable)
public static void main(String args[]) {
Library si = new Library(); //creating an object of Library
System.out.println(sl.id);
System.out.println (sl.title);
}
}
In the above program, variables used just after the name of the class are its data members or also
called instance variables. The statement
Library si = new Library();
is creating a new object si of the class Library.
Let us study the following program which will give the complete calling methods in the
program.
of creating object and
import java.io.*;
Just after the name of class, data members
have been declared with appropriate
data types
class Library { Just after the name of
i
int acc_num; class, data members
i have been declared
String title; with appropriate data
String author;
int days;
double fine;

public void input() throws IOException {


BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Accession Number:");
acc_num = Integer.parseInt(reader.readLine());
System.out.printlnf'Enter Title:"); title = reader. readLine( );
System.out.println("Enter Author:");
author = reader.readl_ine();
}

public void compute() throws IOException {


System.out.printlnf'Enter the number of days (late days)");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
days = Integer.parselnt(reader.readl_ine());
fine = days * 2;
System.out.println("Fine is Rs.=" +fine);
}
public void display() {
System.out.println("Accession Number" + "\t" + "Title"+ "\t" + "Author");
System.out.println(acc_num + "\t" +title +"\t" + author);
}

public static void main (String args []) throws IOException {


Library lib = new Library();
lib.input();

lib.compute();
lib.display();
}
}

to above program defines a class called Library With the following description: Instance
variables/data members:
Int acc -num - stores the accession number of the book
String title - stores the title of the book
String author - stores the name of the author
Member Methods:
void input() - to input and store the accession number, title and author
void compute( ) - to accept the number of days late, calculate and display the fine charged
at the rate of X 2 per day
void display() - to display the details in following format:
Accession Number Title Author
* ____________ _____________ ____________

USING LIBRARY METHODS


To work on various data input operations, Java has a rich library of methods. We are explaining
only those methods which have been covered in the syllabus.
Integer.parselnt Method
Returns an int value specified by the string parameter.
Usage:
Integer.parseInt(String s);
where s is a string expression.
It returns the int value specified by s.

illusfralion
class IntParse {
public void IntParse( ) {
int i = Integer.parselnt("555");
System.out.print("The int value is:" +1);
}
}
Output of the Program
The int value is: 555
Long.parseLong Method
Returns a long value specified by the string parameter.
Usage:
Long.parseLong(String s);
Where s is a string expression.
It returns the long value specified by s.
(lustration
class Long Parse {
public void Long Parse() {
long i = Long.parseLong("-123456");
System.out.print (The long value is : " +i;);
}
}
Output of the Program
" The long value is : -123456
Float.parseFloat Method
Returns a float value specified by the string parameter.
Usage:
Float.parseFloat(Str/ng s);
where s is a string expression.
It returns the float value specified by s.
illustration
class FloatParse {
public void FloatParse() {
float i = Float.parseFloat("-1.23F");
System.out.print("The float value is : " +0;
}
}

Output of the Program


The float value is : -1.23F
Integer.valueOf Method
This method returns the Integer object represented by a string parameter.
Usage:
Integer.valueOf (String s);
Where s is the string to be parsed.
It returns the Integer object represented by s.
illustrration
class IntValue {
public void IntValue() {
String s = new String("-128");
int i = Integer.valueOf(s);
System.out.print('The int value is :" +j);
}
}
Output of the Program
The int value is : -128

double.valueOf Method
This method returns the Double object whose float value is represented by specified string
parameter.
Usage:
Double.valueOf (String s);
where s is the string that represents the double value.
It returns the Double object whose float value is represented by s.
Illustration
Class Double Value {
Public void Double Value() {
Double i = Double.valueOf("2.34 );
M

System.out.printfThe Double value is :" +i);


}
}
Output of the Program
;The Double value is : 2.34
Float.valueOf Method
This method returns the Float object whose float value is represented by a specified string
parameter.
Usage:
Float.valueOf (String s);
Where s is the string that represents the float value.
It returns the Float object whose float value is represented by s.
illustration
Class Float Value {
Public void Float Value() {
Float i = Float.valueOf ("3.12");
System.out.print ("The Float value is :" +i);

}
Output of the Program
The Float value is : 3.12
Long.valueOf Method
This method returns the Long object represented by a string parameter.
Usage:
Long.valueOf(String s);
where s is the string to be parsed.
It returns the Long object represented by s.

illiistraiion
ciass LongValue {
public void LongValue() {
String s = new Str/ngf-256"); Long i = Long.valueOf(s);
System.out.print("The Long value is : " +1);
}
}
Output of the Program
The Long value is: -256

Character.isLowerCase Method
This method checks whether a specified char is a lowercase letter or not

Usage:
Character.isLowerCasefchar ch);
where ch is the char to be checked.
It returns true if the char is a lowercase letter, false otherwise.
Illustration
public class Is Lowercase {
public static void Is Lowercase() {
char cl =M;
char c2 = 'm';

boolean bl = Character.isLowerCase(cl);
boolean b2 = Character.isLowerCase(c2);
if (bl == true) {
System.out.println (cl + " is lowercase.");
}
else {
System.out.println (cl + • is not lowercase.");
}
if (b2 == true) {
System.out.println (c2 + " is lowercase.");

}
else{
a

System.out.println(c2 -•-" is not lowercase.");


}
}
}
Output of the Program
M is not lowercase,
m is lowercase.
Character.isUpperCase Method
This method checks whether a specified char is an uppercase letter or not.
Usage:
Character.isUpperCase (char ch); where ch is the char to be checked.
It returns true if the char is an uppercase letter, false otherwise.
Illustration:
public class Is Uppercase {

public static void Is Uppercase() {


char cl = 'a';
char c2 = 'A';
boolean bl = Character.isUpperCase(cl);
boolean b2 = Character.isUpperCase(c2);
if(bl == true){
System.out.println(cl + " is uppercase.");
}
-

else {
System.out.println(cl + " is not uppercase.");

}
if(b2 == true) {
System.out.println(c2 + " is uppercase.");
} else{
System.out.println(c2 + " is not uppercase.");
}

}
}
Output of the Program
a is not uppercase.
A is uppercase.
Character.isDigit Method
This method checks whether a specified char is a digit or not
Usage :
Character.isDigit (char ch);
where ch is the char to be checked.
It returns true if the char is a digit, false otherwise.
Illustration
pubiic class IsDigit {
public void IsDigitf) {

char cl = 'D';
char c2 = '9';
boolean bl = Character. isDigit(cl);
boolean b2 = Character. isDigit(c2);
jf(bl == true) {
System.out.println(cl + " is a digit.");
}
else {
System.out.println(cl + " is not a digit.");
}
|f(b2 == true) {
System.out.println(c2 + " is a digit.");

else {
System.out.println(c2 + " is not a digit.");
}
}
Output of the Program
D is not a digit.
9 is a digit.
Character.isLetter Method
This method checks whether a specified char is a letter or not. Usage:

Character.isLetter(char ch);
Usage:
Where ch is the char to be checked.
It returns true if the char is a letter, false otherwise.
Illustration:

public class IsLettor {


public void Isl_etter() {
charcl=’T;
char c2 ='';
boolean bl • Charactcr.lsLetter(cl);
boolean b2 = Character.lsLetter(c2);
if(bl == true) {
System.out.prlntln(cl + " is a letter.");
•»-'•.
else {
System.out.println( +d + - | not a letter.");
S

}
If(b2 == true) {
System.out.println(c2 + " is a letter.");
}
else {
System.out.printlnf ''" +c2 + " is not a letter.");
}
}
}
Output of the Program
T is a letter.
" is not a letter.
Character.isLetterOrDigit Method
This method checks whether a specified char is a letter or digit. ;
Usage:
where ch is the char to be checked.
It returns true if the char is a letter, false otherwise.
Illustration:
public class IsLettor {
public void Isl_etter() {
charc=T;
char c2= ‘ '';
boolean bl • Charactcr.lsLetter(cl);
boolean b2 = Character.lsLetter(c2);
if(bl == true) {
System.out.prlntln (cl + " is a letter.");
•»-'•.

else {
System.out.println ( +d + - | not a letter.");
S

}
If(b2 == true) {
System.out.println (c2 + " is a letter.");
}
else {
System.out.printlnf ''" +c2 + " is not a letter.");
}
}
}
Output of the Program
T is a letter.
" is not a letter.
Character.isLetterOrDigit Method
This method checks whether a specified char is a letter or digit.
Usage:
Character.isLetterOrDigit (char ch);
Where ch is the char to be checked.
It returns true if the char is a letter or digit, false otherwise
Illustration:
Public class IsLetterOrDigit {
Public void IsLetterOrDigit() {
char cl = 'C;
••"
char c2 = ';
1
boolean bl = Character.isLetterOrDigit(cl);
boolean b2 = Character.isLetterOrDigit(c2);
if(bl == true) {
System.out.println(cl + " is a letter/digit.");
}
else {
System.out.print/n(+cl + " is not a letter/digit");
}
if(b2 == true) {
System.out.print/n(c2 + " is a letter/digit.");
>
else {
System.out.prtntfn(+c2 + " is not a letter/digit.");
ma
>
>
>
Output of the Program
C is a letter/digit
9 is not a letter/digit
-

Character.isWhitespace Method
This method checks whether a specified char is a white space.
Usage :
Character j"sWhitespace(char ch);
where ch is the char to be checked.
It returns true if the char is white space, false otherwise.
Illustration:
public class IsWhite {
public void IsWhite() {
char cl =’ T;
char c2 =’ '';
boolean bl = Character.isletter(cl);
boolean bl = Character.is letter(c2);
if(bl == true)
System.out.pr/ntln(c1 + ”is a letter.");
Else{
System.out.print/n(" '" + cl + “ is not a letter.");
if(b2 == true)
System.out.println( + 2 + + • w e space.");
C fs a hit

Else {
System.out.println("+ c2 + “is not a letter.”");
}
}
}
Output of the Program
T is not a white space.
“ is a white space.
character.toLowerCase() Method
This method is used to convert a character to its lowercase.
The character to be converted is passed as an argument and the method returns either the
original character , if it is uppercase, the lowercase equivalent. This enables you to deal with all
or

the characters in the string as


if they were lowercase.
Illustration
public class CharToLowerCase {
void count() {
String text = "I am studying in ICSE 10th class";
int spaces = 0, vowels = 0, letters = 0;
int textLength = text.length(); // Get string length
for(int i = 0; i < textLength; i++) {
char ch = Character.toLowerCase(text.charAt(i));
if(ch == 'a' || ch == 'e' || ch == T || ch == 'o* || ch ==’u;) {
vowels++;
}
if(Character.isLetter(ch)) {
letters++;
}
if(Character.isWhitespace(ch)) {
spaces++;
}
}
int consonants=letters-vowels;
System.out.println("The text contains vowels:+V+ consonants: +consonants+ \n"+ spaces:
H n n w

+spaces);
}
Output of the Program
The text contains vowels: 8
consonants: 16
.

spaces: 6
The method returns the character at index position i as a value of type char and you can convert this to
lowercase by using the method toLowerCase() in the class Character.
Character.toUpperCase()
This method is used to convert a character to its uppercase equivalent.
The character to be converted is passed as an argument and the method returns either the original character
or if it is lowercase, the uppercase equivalent. This enables you to deal with all the characters in the string
as

if they were uppercase.


Illustraaaion:
public class CharToUpperCase {
void count() {
String text = "I am a student of ICSE 10th class";
int spaces = 0, vowels = 0, letters = 0;
int textLength = textlength(); // Get string length
for(int i = 0; i < textLength; \++) {
char ch = Character.toUpperCase(text.charAt(i));
if( == 'A' || ch == 'E' \\ch== T \\ch== 'O' || ch == 'LT) {
ch

vowels++;
}
if(Character.isLetter(ch)) {
letters++;
}
if(Character.isWhitespace(ch)) { spaces++;
}
}
int consonants = letters - vowels;
I!

System.out.println("The text contains vowels: +vowels+ \n"+"consonants: +consonants+"\n"+ spaces:


,, ,, ,, ,,

+spaces);
}
Output of the Program
The text contains vowels: 9
consonants:15
spaces: 7
The method returns the character at index position i as a value of type char and you can convert this to
uppercase by using the method toUpperCase() in the class Character.
The isUpperCase( ) method determines whether the specified char value is uppercase The toUpperCase( )
method creates a new copy of a string after converting all the lowercase letters in the invoking string to
uppercase.
'Hi*' •

member Methods
*M member methods ore the methods which am Hnfi
class.
" '" a class that act on the data members in the
],K h

Illustration:
class dmensure {
// Access specifier
public float kilometre; // Data member
public float metre; // Data member
public float centimetre; // Data member
void display() // Class method
{
In the above illustration, the dmeasure class uses a member method display().
Access specifiers for classes or interfaces in Java
Access specifiers are used to control the visibility of members like classes, variable and methods.
There are three access specifiers: public, private and protected. In addition to these three access
specifiers, if there is
no specifier with a class, the class is said to have default specifier. This means that the class
member has default access.
The access specifiers are listed according to their restrictiveness order.
•» private
•> default (when no access specifier is specified)
protected
•* public
But the classes and interfaces themselves can have only two access specifiers.
•» Public
•> default (when no access specifier is specified)
For example, the following class declaration is also valid though no access specifier is stated.
class Student { V
j
In such cases, the default restrictions (also known as the package restrictions) are applied. Now,
we will see what effect these specifiers have on classes, methods and variables. Before moving
further, there is another thing to be noted. A simple program file can contain more than one class
but only one of them should be
declared as public. If more than one class is declared in the same program file, both of them will
be considered as different classes. Or in other words, one class is not said to be contained within
the other class.
* ACCESS SPECIFIERS FOR CLASSES
When a class is declared as public, it is accessible to other classes defined in the same package
as well as those defined in other packages. This is the most commonly used specifier for classes.
A class cannot be
declared as private. If no access specifier is stated, the default access restrictions will be applied.
The class will be accessible to other classes in the same package but will be inaccessible to
classes outside the package.
CANDID ICSE COMPUTER APPLICATIONS-10
When we say that a class is Inaccessible, It simply means that we cannot Cr object of that class or declare a
variable of that class type. The protected*** *
specifier too cannot be applied to a class.
private Access Specifier
If a method or variable is marked as private (has the private access ^ assigned to it), then only code inside
the same class can access the variable^
the method. Code inside subclasses cannot access the variable or method, JJ code from any external
nor

class.
Classes cannot be marked with the private access modifier. Marking a | private access modifier would
C ass m

mean that no other class could access it, which J ME

that you could not really use the class at all. Therefore the private access modifier* not allowed for classes.
Example of private Access Specifier :
class ParentClass {
private int a = 10;
public void showValue( ) {
System.out.printlnf'a value "+ a);
}
private void test( ) {
System.out.printlnfThis is my example");
}
}
public class acessspecifier {
ParentClass accessSpecifier = new ParentClass( );
AccessSpecifier. Test( ); // Private method cannot be used
accessSpecifier.a = 5; // Private variable cannot be used
accessSpecifier.showValue (); // runs properly
default (package) Access Specifier
If you declare any variable /function as
private access specifier so you can use it within
the Java class itself, not from outside the class,
package and others.
The default Java access modifier is declared by not writing any access modifier at all. The default access
modifier means that code inside the class itself as well as
code inside classes in the same package as this class, can access the class, field, constructor or method which the
default access modifier is assigned to. Therefore,
the default access modifier is also sometimes referred to as the package access
modifier.
Subclasses cannot access methods and member variables (fields) in the superclass, if these methods and
fields are marked with the default access modifier, unless the
subclass is located in the same package as the superclass
Example of default/package Access Specifier:
Public class Distance {
foog length = 0;
}
pubic dass DistanceReader {
Distance dist = Distance{ );
pubfc long readDistance {

return dist.length;
}
}
if there is
no specifier with a class, the class is said to have default specifier. This means that the class
member has default access.
The access specifiers are listed according to their restrictiveness order.
•» private
•> default (when no access specifier is specified)
protected
•* public
But the classes and interfaces themselves can have only two access specifiers.
•» Public
•> default (when no access specifier is specified)
For example, the following class declaration is also valid though no access specifier is stated.
class Student { V
j
In such cases, the default restrictions (also known as the package restrictions) are applied. Now,
we will see what effect these specifiers have on classes, methods and variables. Before moving
further, there is another thing to be noted. A simple program file can contain more than one class
but only one of them should be
declared as public. If more than one class is declared in the same program file, both of them will
be considered as different classes. Or in other words, one class is not said to be contained within
the other class.
* ACCESS SPECIFIERS FOR CLASSES
When a class is declared as public, it is accessible to other classes defined in the same package
as well as those defined in other packages. This is the most commonly used specifier for classes.
A class cannot be
declared as private. If no access specifier is stated, the default access restrictions will be applied.
The class will be accessible to other classes in the same package but will be inaccessible to
classes outside the package.
When we say that a class is Inaccessible, It simply means that we cannot object of that class or declare a
Cr

variable of that class type. The protected*** *


specifier too cannot be applied to a class.
private Access Specifier
If a method or variable is marked as private (has the private access ^ assigned to it), then only code inside
the same class can access the variable^
the method. Code inside subclasses cannot access the variable or method, JJ code from any external
nor

class.
Classes cannot be marked with the private access modifier. Marking a | private access modifier would
C ass m

mean that no other class could access it, which J ME

that you could not really use the class at all. Therefore the private access modifier* not allowed for classes.
Example of private Access Specifier :
class ParentClass {
private int a = 10;
public void showValue( ) {
System.out.printlnf'a value "+ a);
}
private void test( ) {
System.out.printlnfThis is my example");
public class AccessSpecifier {

public static void main(String args[ ]) {


ParentClass accessSpecifier = new ParentClass( );
accessSpecifier.test( ); // Private method cannot be used
accessSpecifier.a = 5; // Private variable cannot be used
accessSpecifier.showValue(); // runs properly
default (package) Access Specifier
If you declare any variable /function as
private access specifier so you can use it within
the Java class itself, not from outside the class,
package and others.
The default Java access modifier is declared by not writing any access modifier at all. The default access
modifier means that code inside the class itself as well as
code inside classes in the same package as this class, can access the class, field, constructor or method which the
default access modifier is assigned to. Therefore,
the default access modifier is also sometimes referred to as the package access
modifier.
Subclasses cannot access methods and member variables (fields) in the superclass, if these methods and
fields are marked with the default access modifier, unless the
subclass is located in the same package as the superclass
Example of default/package Access Specifier:
pafr'ic dass Distance {
long length = 0;
}
pubic dass DistanceReader {
Distance dist = Distance{ );
pubfc long readDistance {

return dist.length;
}
}
Tte length field in the Distance doss has no access modifier, which means that it i:
implicitly assigned the default access modifier. Therefore, the DistanceReaderdass can
read the length
object provided that DistanceReader and Distance are located in the same Java package.
public Access Specified
The Java access modifier public means that all code can access the class, field,
constructor or method, reca-dSess of ?/here the accessing code is located. The
accessing code can be in a different class and different
package.
If you declare any variable /function as public access spedfier so you can used it from
anywhere.
Example of public Access Specifier:
dass ParentQass { public void test() {
System.oiitprintin(This is my example");
}
}
public dass AccessSpedfier {
public static void main(String args[ ]) { ParentQass acsp = new ParentClass();
acsp.testf);
}
>
protected Access Specifier
The protected members can be accessed from any class of same package and from the
sub class of other packages.
Use protected to allow access from classes that extend from the declaring class.
Protected methods and fields can only be accessed within the same class to which the
methods and fields belong, within its subclasses and within classes of the same
package, but not from anywhere else. You use the
protected access level when it is appropriate for a class's subclasses to have access to
the method or field, but not for unrelated classes.

house

Bed room (private access)

Hall (protected and default


access
Reception (default and
procted access)

Door step (public acess).


Example of protected Access Specifier :
class ParentClass {
protected Int a = 10;
public void showValuef) {
System.out.prlntlnf'a value "+ a);
}
Protected void test() {
System.out.printlnfThis is my example");
}
}
class childClass extends ParentClass {
}
public class AccessSpecifier {
public static void main(String argsfj) {
child Class accessSpecifier = new child Class();
AccessSpecifier. Show\/alue(); // run properly
AccessSpecifier. Test(); // run properly
accessSpecifier.a = 5; // run properly
}
}
Summary of Access Specifiers

M
clclass subclass package everywher
Private Allowed Not Nnot allowed
Not
Protected Allowed allowed Not allowed
Public Allowed Not allowed Not
package allowed allowed Not allowed
Not allowed Not
allowed Not allowed
Not allowed Not
allowed allowed
ORE PROGRAMS RELATED TO THIS CHAPTE
1. 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
Import java.io.*;
class Pig Latin {
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( ); String n=" ";
String strUpper = s.toUpper€ase( );
System.out.println("Original String: "+s);
System.out.println("String changed to upper case: "+ strUpper); char ch;
boolean b = false;
for(short i=0; i < s.length(); i++) { ch=strl)pper.charAt(i);
if(ch==’a’||ch==’e’||ch==’I’|ch==’u’||ch==’a’||ch’e’||ch==’I’ch==’0’||==’u’)
b = true;

if(b == true)
n += ch;
java.io.*;
}
for(short i=0; i < strUpper.length( ); i++) {
ch=s.charAt(i);
if(ch==’a’||ch==’e’||ch==’I’||ch==’o’||ch==’u’||ch==’a’||ch==’e’||ch==’I’||ch==’o’||ch==’u’)
break;
n+=ch;
}
n += "AY";
System.out.print("Word in Piglatin: "+n);
}
}
2. Define a class named Fruit Juice with the following description:
Instance variables/data members:
int product code - stores the product code number
String flavor - stores the flavor of the juice (E.g. orange, apple etc.)
String pacjype - stores the type of packaging (E.g. tera pack, PET bottle etc.)
int pack size - stores package size (E.g. 200 ml, 400 ml etc.)
int product price - stores the price of the product
Member methods:
(i) FruirJuice( ) - Default constructor to initialize integer data members to 0 and ingdata members
i

(fi) void mput() - To input and store the product code, flavour, pack type, pack size product price.
an

(iii) void discount() - To reduce the product price by 10.


(iv) void display() - To display the product code, flavour, pack type, pack size and d price.
pr0 Uct

Answer. class FruiUuice {


private int product code; private String flavor;
private String pacjype; private int pack size;
private int product price;
void Fruit Juice( ) { product code=0;
flavor = " "; pac.type = "";
pack size = 0; product price = 0;
}
Void input(int pc, String f, String pt, int ps, int pp) { product_code = pc;
Flavor = f; pac_type = pt;
Pack size = ps; product price = pp;
System.out.println ("Product Code = " +product code); System.out.println("Flavor = " +flavor);
System.out.println ("Pack Type = " +pac_type); System.out.println("Pack Size = " +pack size);
System.out.println ("Product Price = " +product price);
}
void discount() {
product price = product price - 10;
System.out.println ("Discounted Price = " +product price);
}
void display() {
system.out.printin(“produce code=”+produce-code);
system.out.printin(“flavor=”+flavor);
system.out.printin(“pack ty[e=”+key-type);
system.out.printin(“pack size=”+pack-size);
system.out.printin (“produce price=”+produce-price);
}
}
3. write a class with name employee and basic as its data member, to find the gross pay
of an employed for the following allowances and deduction. Use meaningful variables.
Dearness Allowance = 25% Basic Pay
of the

House Rent Allowance = 15% f Basic Pay


0

Provident Fund = 8.33% of Basic Pay


Net Pay = Basic Pay Dearness Allowance +House Rent Allowance
+ +=

Gross Pay = Net Pay - Provident Fund


Answer.
import java.util.*;
class employee {
.
// data members
String name;
Double basic;
// constructor
Public employee (String name, double basic) {
this.name = name;
this.basic = basic;
}
// compute and display the gross pay public void compute Gross ( ) {
double da = 0.25 * this.basic;
double hra = 0.15 * this.basic;
double pf = .0833 * this.basic;
double net = this.basic + da + hra;
double gross = net - pf; System.out.println("Dearness allowance+ da);

System.out.println(“HRA :”hra);
System.out.println("Net pay :+net);
System.out.println (“PF deduction :+pf);
System.out.printlnf(“Gross pay :+gross);

// entry point main method


public static void main(Strlng args[]) {
// ask user to enter the details of an employee

-•

Scanner sc =new scanner (system. in);


System.out.printin (“enter name:”);
String n =sc.nextline ();
System.out.printin (“enter basic; “);
Double b =sc.nextdouble ();
String temp =sc.nextline (); // for the trailing newline

// create the object


Employee e=new employee (n,b);
e.computergross ();
}
}
Let lis revise
 Oop means object oriented programming
 A class is a collection of objects.
 A class is used define aggregate data type
 A class can contain data member and member methods both
 The number oof a class can be data members, constructor and method and
member methods
 Instantiation means allocation oof space for a new object
 Declaration of object does not create a new object
 Declaration only declares variables.

You might also like