access specifiers

14
Unit-2 Prof. P. M . Pandya Access Specifiers : Access specifiers for member of a package: For the classes and interfaces that are a part of a package, they are only two access specifiers available. A particular class or an interface can have either a public access specifier or a default access specifier. When any member of a package has a default access specifier (no access specifier defined), then such a member is known and accessible only within its package. The default access specifier is also known as package level access. When any number of a package has a public access specifier, then such a member is known anywhere, i.e. it is usable outside the package. Most of the time the classes and interface which we create have to be allowed to be used from outside the package, and so they are normally declared to be public. Access specifier Within package Outside package Def `ault Accessible Not Accessible Public Accessible Accessible Access Specifiers for member of a class: For the member of a class there are four access specifiers. A member of a class can be declared to be private, default, protected and public. Access specifier Within class Within package sub-classes outside package Non-sub class outside package private Accessible Not Accessible Not Accessible Not Accessible default Accessible Accessible Not Accessible Not Accessible protected Accessible Accessible Not Accessible but inherited Not ccessible public Accessible Accessible Accessible Accessible

Upload: shamik

Post on 10-Dec-2015

245 views

Category:

Documents


0 download

DESCRIPTION

Access Specifiers

TRANSCRIPT

Page 1: Access Specifiers

Unit-2

Prof. P. M . Pandya

Access Specifiers :

Access specifiers for member of a package:

For the classes and interfaces that are a part of a package, they are

only two access specifiers available.

A particular class or an interface can have either a public access

specifier or a default access specifier.

When any member of a package has a default access specifier (no

access specifier defined), then such a member is known and accessible

only within its package.

The default access specifier is also known as package level access.

When any number of a package has a public access specifier, then

such a member is known anywhere, i.e. it is usable outside the

package.

Most of the time the classes and interface which we create have to be

allowed to be used from outside the package, and so they are normally

declared to be public.

Access specifier Within package Outside package

Def

`ault Accessible Not Accessible

Public Accessible Accessible

Access Specifiers for member of a class:

For the member of a class there are four access specifiers. A

member of a class can be declared to be private, default, protected

and public.

Access

specifier

Within

class

Within

package

sub-classes

outside

package

Non-sub

class outside

package

private Accessible Not

Accessible

Not Accessible Not

Accessible

default Accessible Accessible Not Accessible Not

Accessible

protected Accessible Accessible Not Accessible

but inherited

Not ccessible

public Accessible Accessible Accessible Accessible

Page 2: Access Specifiers

Unit-2

Prof. P. M . Pandya

Access Specifiers for overriding methods:

When a sub-class overrides a method from the super-class, then what

access specifier is allowed for the overriding method depends on the

access specifier of the method being overridden.

The rule here is that the overriding method is not allowed to have a weaker access

specifier compared to the method being overridden

Commonly used classes from the java.lang package

Core java language, classes and interface String, StringBuffer,

StringBuilder, Math, System, Comparable etc.

String class:

Constructors:

String() creates an empty string with a value “”.

String(String s) creates a copy of specified string object s.

String(char[] c) creates a string from the characters in character array.

Example:

Char[] c1={„h‟,‟e‟,‟l‟,‟l‟,‟o‟};

String s=new String(c1);

System.out.println(s);

String class methods:

String concat(String s) : In java, you can use this method to concatenate two strings in a

single string.

If s1=”MCA” s2=”SEM 3” then

If s1.concat(s2) then it is not right.

If s3=s1.concat(s2) then s3=MCASEM3 It is right.

int length() : The length of the string is the number of characters that it contains. To

obtain this value, you can use length() method.

char charAt(int i) : This method is used to extract a single character from a string.

If String s=”Raj kamal” then if

char c=s.charAt(2) returns j.

int compareTo(String s) : This method is used to compare two strings. It returns 0,

positive or negative value.

If s1=”MCA” and s2=”MBA” then

If int i=s1.compareTo(s2); then it returns 1.

If s1=”MCA” and s2=”Mca” then

If int i=s1.compareTo(s2) then it returns -32.

int compareToIgnoreCase(String s) : This method is used to compare two strings

whether it is in capital or small.

If s1=”MCA” and s2=”MBA” then

Page 3: Access Specifiers

Unit-2

Prof. P. M . Pandya

If int i=s1.compareTo(s2); then it returns 1.

If s1=”MCA” and s2=”Mca” then

If int i=s1.compareTo(s2) then it returns 0.

boolean equals(String s) : This method is used to compare two strings. It returns true if

both strings are equal. It returns false, if both strings are different.

boolean equalsIgnoreCase(String s) :This method is used to compare two string

whether it is in any case (i.e. in capital or small).

boolean startsWith(String s) : This method returns true, if the string is starting with the

string specified in parameter.

If s1=”MBAMCA” and if

boolean b=s1.startsWith(“MB”) then it returns true.

boolean b=s1.startsWith(“MA”) then it returns false.

boolean endsWith(String s) : This method returns true, if the string is ending with the

string specified in parameter.

If s1=”MBAMCA” and if

boolean b=s1.endsWith(“MB”) then it returns false.

boolean b=s1.startsWith(“CA”) then it returns true.

int indexOf(String s) : This method returns the starting index value from the string

compared with staring given in parameter string.

If s1=”MBAMCA”

int i=s1.indexOf(“B”) then it returns 1.

int i=s1.indexOf(“AM”) then it returns 2.

int lastIndexOf(String s) : This method returns the starting index value from the string

compared with ending given in parameter string.

If s1=”MBAMCAMBA”

int i=s1.lastIndexOf(“B”) then it returns 7.

int i=s1.lastIndexOf(“AM”) then it returns 5.

String replace(String old, String new) : This method is used to replace two strings.

If s1=”MBAMCAMBA”

String s2=s1.replace(“AM”,”MA”); then it returns MBMACMABA

String substring(int i) : This method is used to divide a whole string in a substring.

If s1=”MBAMCAMBA”

String s2=s1.substring(3); then it returns MCAMBA

String substring(int i1, int i2) : This method is also used for divide a whole string in to

substring between two index values where i1 is inclusive and i2 is exclusive.

If s1=”MBAMCAMBA”

String s2=s1.substring(3,6); then it returns MCA

String toLowerCase() : This method is used to convert the whole string in lowercase.

String toUpperCase() :This method is used to convert the whole string in uppercase.

String trim() : This method is used to remove the space from the left and right side.

Page 4: Access Specifiers

Unit-2

Prof. P. M . Pandya

void getChars(int srcbegin, int srcend,char[] dest, int destbegin) : This method is

used to convert a string in the character array.

String s1=”This is MCA College”;

char[] c1=new char[20];

s1.getChars(2,8,c1,0);

for(int i=0;i<c1.length;i++)

{

System.out.println(c1[i]);

}

Char[] toCharArray() : This method is also used to convert a string in the character

array.

String s2="Pooja";

char c[]=s2.toCharArray();

for(int i=0;i<c.length;i++)

{

System.out.println(c[i]);

}`

StringBuffer class: The instances of String Buffer hold the sequence of characters in some internal array of characters.

StringBuilder class is introduced from Java 5 onwards. It has exactly same methods as are available in

StringBuffer class but its methods are faster compared to StringBuffer.

Constructors:

StringBuffer() : This constructs an empty StringBuffer.

Page 5: Access Specifiers

Unit-2

Prof. P. M . Pandya

StringBuffer(int size) : This constructs an empty StringBuffer with the initial capacity.

StringBuffer(String s) : This constructs a StringBuffer that initially contains a String.

The default constructor contains 16 characters. The second constructor takes int value that

explicitly sets the size of buffer. The third constructor contains String argument that sets the

initial contents of StringBuffer object.

StringBuffer class Methods:

int length() : This method returns the length of the StringBuffer.

int capacity() : This method returns the capacity of the StringBuffer. A StringBuffer has a

capacity which is equal to its longest string.

char charAt(int index) : This method returns the character from the StringBuffer.

void setLength(int len) : This method is used to set the length of the StringBuffer.

void setCharAt(int p,char c) : Thie method sets the character at position defined in p.

void getChars(int srcstart, int srcend, char c[], int deststart) : This method extracts more

than one character from the StringBuffer.

String substring(int startindex) :

String substring(int startindex, int endindex)

Appending characters in StringBuffer

StringBuffer append(String s) : This method appends the String at the end of existing

StringBuffer.

StringBuffer append(int i)

StringBuffer append(char c)

StringBuffer append(long l)

StringBuffer append(double d)

StringBuffer append(char[] ch)

StringBuffer append(boolean b)

StringBuffer append(char[] ch, int start, int length)

Example:

StringBuffer sbuf=new StringBuffer();

Sbuf.append(“Bhavin”);

Sbuf.append(2);

Page 6: Access Specifiers

Unit-2

Prof. P. M . Pandya

Inserting characters in StringBuffer

StringBuffer insert(int pos, String str) : This method inserts the String in position defined

in the pos.

StringBuffer insert(int pos, char[] ch)

StringBuffer insert(int pos, char c)

StringBuffer insert(int pos, int i)

StringBuffer insert(int pos, long l)

StringBuffer insert(int pos, double d)

StringBuffer insert(int pos, boolean b)

Deleting characters in StringBuffer

StringBuffer delete(int start, int end) : This method is used to delete more than one character from

the StringBuffer. Where start in inclusive and end is exclusive.

StringBuffer deleteCharAt(int pos) : This method is used to delete individual character from the

StringBuffer.

Replace and reverse String:

StringBuffer replace(int start, int end, String s) : This method is used to replace a string with other

string in StringBuffer.

StringBuffer reverse() : This method is used to reverse the string available in StringBuffer.

StringBuilder class:

StringBuilder objects are like String objects, except that they can be modified. Internally,

these objects are treated like variable-length arrays that contain a sequence of characters.

The StringBuilder class, like the String class, has a length() method that returns the

length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have

been allocated. The capacity, which is returned by the capacity() method, is always greater

than or equal to the length (usually greater than) and will automatically expand as necessary.

Page 7: Access Specifiers

Unit-2

Prof. P. M . Pandya

StringBuilder Constructors

Constructor Description

StringBuilder() Creates an empty string builder with a

capacity of 16 (16 empty elements).

StringBuilder(CharSequence cs)

Constructs a string builder containing the

same characters as the specified

CharSequence, plus an extra 16 empty

elements trailing the CharSequence.

StringBuilder(int initCapacity) Creates an empty string builder with the

specified initial capacity.

StringBuilder(String s) Creates a string builder whose value is

initialized by the specified string, plus an extra

16 empty elements trailing the string.

--For example, the following code // creates empty builder, capacity 16

StringBuilder sb = new StringBuilder();

// adds 9 character string at beginning

sb.append("Greetings");

will produce a string builder with a length of 9 and a capacity of 16:

The StringBuilder class has some methods related to length and capacity that the

String class does not have:

Various StringBuilder Methods

Method Description

StringBuilder append(boolean b)

StringBuilder append(char c)

StringBuilder append(char[] str)

StringBuilder append(char[] str, int

offset, int len)

StringBuilder append(double d)

StringBuilder append(float f)

StringBuilder append(int i)

StringBuilder append(long lng)

StringBuilder append(Object obj)

StringBuilder append(String s)

Appends the argument to this string builder.

The data is converted to a string before the

append operation takes place.

Page 8: Access Specifiers

Unit-2

Prof. P. M . Pandya

StringBuilder delete(int start, int

end)

StringBuilder deleteCharAt(int index)

The first method deletes the subsequence from

start to end-1 (inclusive) in the

StringBuilder's char sequence. The second

method deletes the character located at index.

StringBuilder insert(int offset,

boolean b)

StringBuilder insert(int offset, char

c)

StringBuilder insert(int offset,

char[] str)

StringBuilder insert(int index, char[]

str, int offset, int len)

StringBuilder insert(int offset,

double d)

StringBuilder insert(int offset, float

f)

StringBuilder insert(int offset, int

i)

StringBuilder insert(int offset, long

lng)

StringBuilder insert(int offset,

Object obj)

StringBuilder insert(int offset,

String s)

Inserts the second argument into the string

builder. The first integer argument indicates

the index before which the data is to be

inserted. The data is converted to a string

before the insert operation takes place.

StringBuilder replace(int start, int

end, String s)

void setCharAt(int index, char c)

Replaces the specified character(s) in this

string builder.

StringBuilder reverse() Reverses the sequence of characters in this

string builder.

String toString() Returns a string that contains the character

sequence in the builder.

System class :

System class defines several attributes related to runtime environment. It has a static

variable out that contains a reference to a PrintStream object.

The print() and println() method of the object display string arguments on the output. The

static variable err also holds a reference to a PrintStream object.

This is the standard error stream. The static variable in contains a reference to an

InputStream object. PrintStream and InputStream are classes that provide I/O support.

Another static method of the System class is exit(). It terminates the current application.

Syntax :

void exit(int code);

Page 9: Access Specifiers

Unit-2

Prof. P. M . Pandya

where code is the exit code. A zero value indicates normal termination. Other values can

be used to report some problems.

The static method currentTimeMillis() returns the number of milliseconds between the

current time and midnight, January 1, 1970.

Syntax :

long currentTimeMillis();

The static method arraycopy() copies the elements from a source array to a destination array.

Syntax :

void arraycopy(Object source, int srcindex, Object destination, int destindex, int s);

where source is the array from which s elements are read starting from srcindex. The elements

should be written to destination starting at destindex.

Example :

class arraycopy1

{

public static void main(String args[])

{

int arr1[]={1,2,3,4,5,6,7,8,9};

int arr2[]={0,0,0,0,0,0,0,0,0};

System.arraycopy(arr1,2,arr2,2,4);

System.out.println(arr2[3]);

}

}

Pass by value: When we use primitive types as parameter then it is pass by value.

Actual parameter expressions that are passed to a method are evaluated and a

value is derived.

Then this value is stored in a location and then it becomes the formal parameter

to the invoked method. This mechanism is called pass by value and Java uses it. class a

{

void calc(int i,int j)

{

i=i+2;

j=j+2;

System.out.println(i);

System.out.println(j);

}

}

class passval

{

public static void main(String args[])

{

a a1=new a();

int i=4,j=3;

Page 10: Access Specifiers

Unit-2

Prof. P. M . Pandya

a1.calc(i,j);

System.out.println(i);

System.out.println(j);

}

}

pass by reference

When we use the reference type as parameter in a method, then it becomes pass

by reference.

The reference type refer to an object show when we use the reference data type

as a parameter a copy of the reference value is made available to the invoke

method.

In pass by reference, the formal parameter is just an alias to the actual

parameter. It refers to the actual argument.

Any changes done to the formal argument will reflect in actual argument and

vice versa.

class abc

{

int i;

abc()

{

i=4;

}

void calc(abc a1)

{

a1.i=a1.i+4;

System.out.println(i);

}

void disp()

{

System.out.println(i);

}

}

class passref

{

public static void main(String args[])

{

abc a1=new abc();

a1.calc(a1);

System.out.println(a1.i);

a1.disp();

}

}

Wrapper class

Wrapper are classes that provide object version of the fundamental data types.

Page 11: Access Specifiers

Unit-2

Prof. P. M . Pandya

Type wrapping are important because many java classes and method operate on

object rather than the fundamental data types.

So, by creating object version of the simple data types, it is possible to add

useful methods

To each other. Like

toString(), equals() & compareTo()

These methods are applicable to all the wrappers data types.

Below points indicates where the wrapper class is to be used.

1. Types of Wrapper class

2. Converting primitive data types into object type using constructor.

Syntax

Integer i=new Integer(value);

Float f=new Float(value);

Or

v.addElements(new Integer(value));

3. Converting object to primitive data types using Value() method.

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char

int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String

Page 12: Access Specifiers

Unit-2

Prof. P. M . Pandya

Method Purpose

byteValue() returns the value of this Integer as a byte

doubleValue() returns the value of this Integer as an double

floatValue() returns the value of this Integer as a float

intValue() returns the value of this Integer as an int

shortValue() returns the value of this Integer as a short

longValue() returns the value of this Integer as a long

4. Converting numbers to string using toString() method

Method Purpose

toString(i) returns a new String object representing the integer i

Ex= Integer.toString()

5. Converting string into numeric object.

Syntax:

Short s=new Short ();

S1=Short.valueOf(s);

6. Converting numeric string into primitive type using parse() method

Method Purpose

parseInt(s) returns a signed decimal integer value equivalent to string s

parseShort(s) returns a signed decimal Short value equivalent to string s

E.g- Short s=Short.parseShort(“123”);

System.out.pritnln(s);

7. All the data type of wrapper class include following two constant data

member

a. MIN_VALUE

b. MAX_VALUE

8. Character class of wrapper include

isLowerCase()

isUpperCase()

isDigit()

E.g Class wcha

{

Public static void main(String a[])

Page 13: Access Specifiers

Unit-2

Prof. P. M . Pandya

{

Character c1=new Characte(„m‟);

char c2=‟H‟;

System.out.pritnln(c1.charValue());

System.out.pritnln(c2);

System.out.pritnln(Characte.isLowerCase(c2));

System.out.pritnln(Characte.isUpperCase(c1));

System.out.pritnln(Characte.isDigit(c2));

}

}

Explain Math class

The Math class contains several method for mathematical calculations.

It is declared as final so you cant extend it.

Static variable :

Math.PI

Math.E

Rounding functions :

i. static double abs(double d) : Returns the absolute value of d.

ii. static int abs(int i) : Returns the absolute value of i.

iii. static long abs(long l) : Returns the absolute value of l.

iv. static int min(int a, int b) : Returns the minimum of a and b.

v. static long min(long a, long b)

vi. static double min(double a, double b)

vii. static int max(int a, int b) : Returns the maximum of a and b.

viii. static long max(long a, long b)

ix. static double max(double a, double b)

x. static double ceil(double d) : Returns the smallest whole number greater than or equal to d.

xi. static double floor(double d) : Returns the largest whole number less than or equal to d.

xii. static long round(double d) : Returns the d rounded up to the nearest long.

Exponential Functions :

i. static double pow(double d1, double d2) : Returns d2 raised to the d1.

ii. static double exp(double d) : Returns e to the d.

iii. static double log(double d) : Returns the natural logarithms of d.

iv. static double sqrt(double d) : Returns the square root of d.

Trancedental functions :

i. static double sin(double d) : Returns the sin of the angle specified by d in radians.

ii. static double cos(double d) : Returns the cosine of the angle specified by d in radians.

iii. static double tan(double d) : Returns the tangent of the angle specified by d in radians.

iv. static double toRadians(double d) : This method converts degrees to radians.

v. static double toDegrees(double d) : This method converts radians to degrees.

Page 14: Access Specifiers

Unit-2

Prof. P. M . Pandya

Pseudorandom Number Generator :

i. static double random() : This method returns a random number greater than or equal to 0.0

and less than 1.0 where the value is selected randomly from the range.

E.g

double x=3.6;

System.out.println(Math.rint(x));

System.out.println(Math.round(x)); System.out.println(Math.ceil(x)); System.out.println(Math.PI);