Soda Chapter 9
Soda Chapter 9
Soda 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.
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
a collection of member variables of primitive and/or composite data types 'H member methods or
s is C S
•mitive and/or class types. Each method can either return a value of specified Hirn data type or no
P
p e, a class named Student with several instance variables and methods has n defined by a
0S bee
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)
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).
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.
•
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.
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
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
•
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.
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
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:
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
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;
•
•
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
* ____________ _____________ ____________
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;
}
}
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
}
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
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:
}
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
+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
vowels++;
}
if(Character.isLetter(ch)) {
letters++;
}
if(Character.isWhitespace(ch)) { spaces++;
}
}
int consonants = letters - vowels;
I!
+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
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
class.
Classes cannot be marked with the private access modifier. Marking a | private access modifier would
C ass m
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 {
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
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
System.out.println(“HRA :”hra);
System.out.println("Net pay :+net);
System.out.println (“PF deduction :+pf);
System.out.printlnf(“Gross pay :+gross);
•