• No results found

Package and Interfaces and String Handling

In document java notes (Page 33-40)

Q1. What are packages ?

Ans Package is a mechanism for organizing a group of related files in the same directory.

In a computer system, we organize files into different directories according to their functionality, usability and category.Some of the existing packages in Java are::

java.lang - bundles the fundamental classes

java.io - classes for input , output functions are bundled in this package Naming convention (Rules) for using the packages

Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.

The directory name must be same as the name of package that is created using

"package" keyword in the source file.

Before running a program, the class path must be picked up till the main directory (or package) that is used in the program.

If we are not including any package in our java source file then the source file automatically goes to the default package.

In general, we start a package name begins with the order from top to bottom level.

In case of the internet domain, the name of the domain is treated in reverse (prefix) order.

Q2. Explain access modifiers ?

Ans Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

1) Default 2) Public 3) Private

For free study notes log on: www.gurukpo.com 4) Protected

Default Access Modifier - No keyword:

Default access modifier means we do not explicitly declare an access modifier for a class, field, method etc.

A variable or method declared without any access control modifier is available to any other class in the same package. The default modifier cannot be used for methods, fields in an interface.

Example:

Variables and methods can be declared without any modifiers, as in the following examples:

String version = "1.5.1";

boolean processOrder() {

return true;

}

Private Access Modifier

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

Example:

The following class uses private access control:

public class Logger { private String format;

public String getFormat() { return this.format;

}

public void setFormat(String format) { this.format = format;

} }

For free study notes log on: www.gurukpo.com Public Access Modifier

A class, method, constructor, interface etc declared public can be accessed from any other class.

Example:

The following function uses public access control:

public static void main(String[] arguments) {

// ...

}

Protected Access Modifier

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Example:

The following parent class uses protected access control, to allow its child class override openSpeaker() method:

class AudioPlayer {

protected boolean openSpeaker(Speaker sp) { // implementation details

} }

class StreamingAudioPlayer {

boolean openSpeaker(Speaker sp) { // implementation details

} }

Here if we define openSpeaker() method as private then it would not be accessible from any other class other than AudioPlayer. If we define it as public then it would become accessible to all the outside world. But our intension is to expose this method to its subclass only, thats why we used protected modifier.

For free study notes log on: www.gurukpo.com Q4. Define interfaces and how do you implement interfaces ?

Ans An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object.

An interface contains behaviors that a class implements.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Syntax:

import java.lang.*;

//Any number of import statements public interface NameOfInterface {

//Any number of final, static fields

//Any number of abstract method declarations\

}

Interfaces have the following properties:

An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.

Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */

interface Animal { public void eat();

public void travel();

}

For free study notes log on: www.gurukpo.com Implementing Interfaces:

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */

public class MammalInt implements Animal{

public void eat(){

System.out.println("Mammal eats");

}

public void travel(){

System.out.println("Mammal travels");

}

public int noOfLegs(){

return 0;

}

public static void main(String args[]){

MammalInt m = new MammalInt();

m.eat();

m.travel();

} }

This would produce following result:

Mammal eats Mammal travels

Q5. Explain string ?

Ans Strings, which are widely used, are a sequence of characters. In the Java programming language, strings are objects.

Creating Strings:

For free study notes log on: www.gurukpo.com The most direct way to create a string is to write:

String greeting = "Hello world!";

The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

public class StringDemo{

public static void main(String args[]){

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

String helloString = new String(helloArray);

System.out.println( helloString );

} }

This would produce following result:

hello

Q6. Explain string operations in java ? Ans

1 char charAt(int index)

Returns the character at the specified index.

2 int compareTo(Object o)

Compares this String to another Object.

3 int compareTo(String anotherString) Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)

Concatenates the specified string to the end of this string.

6

boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.

7 static String copyValueOf(char[] data)

Returns a String that represents the character sequence in the array specified.

For free study notes log on: www.gurukpo.com 8 static String copyValueOf(char[] data, int offset, int count)

Returns a String that represents the character sequence in the array specified.

9 boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

10 boolean equals(Object anObject)

Compares this string to the specified object.

11 boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

12

byte getBytes()

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

byte[] getBytes(String charsetName

Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

int lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

int length()

Returns the length of this string.

String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.

boolean startsWith(String prefix, int toffset)

Tests if this string starts with the specified prefix beginning a specified index.

For free study notes log on: www.gurukpo.com

Unit - IV

In document java notes (Page 33-40)

Related documents