The String and StringBuffer classes

This Topic illustrates different features of String and StringBuffer classes: modifying a StringBuffer, creating Strings and StringBuffers,converting one type of string to another and using of accessor methods to get information about a String or StringBuffer.

The two String Classes

Java programming environment provides two classes which stores and manipulates character data suich as String, for immutable strings (which should not be modified), and StringBuffer for mutable strings (which needs to be modified).

class ReverseString
{
public static String reverseIt(String source)
{
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);

for (i = (len – 1); i >= 0; i–)
{
dest.append(source.charAt(i));
}
return dest.toString();
}
}

 

The String class is provided for the constant strings; you can use Strings when you don’t want its value to be changed. Let us consider for example, if you pass the string data into the method, and you don’t want to modify the string by the method in any way, you can use “String”. Typically, Strings are used to pass character data to methods and return character data from the methods. method reverseIt() takes an String argument and returns back a String value.

A StringBuffer class is used for non-constant string. When we know that value of the character data will do change we use StringBuffers. Typically StringBuffers are used for constructing the character data like that of reverseIt() method.



 

Creating Strings and StringBuffers classes

The reverseIt method in the above example creates a StringBuffer called “dest” whose initial length is equal to that of source. StringBuffer dest declares to the compiler that dest will be used to refer to an object whose type is of String, the new operator will allocate memory for the new object, and StringBuffer() will initialize the object. When we create any object in a Java program, we always do use the same three steps: declaration, instantiation, initialization.



 

The Accessor Methods

Methods which are used to obtain information about the object are known as accessor methods. The method reverseIt() uses two String’s accessor methods to get the information about a source string.

First, reverseIt() uses String’s length()
accessor method to obtain the length of the String source.
int len = source.length();

Second, reverseIt() uses the charAt()
accessor which returns the character at the position specified in the parameter.
source.charAt(i)

 



 

Modifying a StringBuffer

To add characters to dest reverseIt() method uses StringBuffer’s append() method. In addition to append() method, StringBuffer also provides methods to insert characters into buffer or modify the character at a specific location within buffer, among others.

dest.append(source.charAt(i));

 

append() is the only StringBuffer’s methods which allows you to append data to end of the StringBuffer. There are different append() methods which appends data of various types, like boolean, float, int, and even Object, to the end of the StringBuffer. The data is first converted into string before the append could takes place.



 

Converting the Objects to Strings

toString() Method
Sometimes it becomes necessary to convert an object into String because you may need to pass it to a method that accepts only String values. consider for example, System.out.println() will not accept StringBuffer, so there is need to convert a StringBuffer to String before you could print it. The reverseIt() method in the above example uses StringBuffer’s toString() method to converte StringBuffer into String object before returning the String.

return dest.toString();

 

many of the classes in java.lang supports toString() including all the “type wrapper” classes such as Integer, Boolean,Character and others. Even the base Object class has toString() method which converts an Object to String. When we write a subclass of an Object, we can override the method toString() to perform the more specific conversion for the subclass.

valueOf() Method
for convenience, the String class do provides the static method “valueOf()” which we can use to convert variables of different types to the String. For example, to print the value of the pi

System.out.println(String.valueOf(Math.PI));

 

 

Leave a Comment

JAVA objects,classes,and Interface

Here you will learn how to create and destroy the objects, how to create class and subclass a classes, how to write the methods, and even how to create and use the interfaces. This chapter covers everything from how to protect an object from other objects and overriding methods, to create template classes using the abstract classes and methods and patriarch of the Java object hierarchy–java.lang.Object class.

Life Cycle of the Object

an object is a module that has both state and behaviour. An object’s state is contained within the member variables and the behaviour is implemented by its methods. The Java programs that you write will create many different objects by the template, these templates are known as classes. The objects created interact with each other by sending messages. As a result of messag, method is invocated which will perform some action or it may also modify the state of object which is receiving the message. By these interaction of the objects, your Java code can implement a graphical user interface, run animations, or can also send and receive information over network. Once the object completes the work it was created for, it is destroyed and all the resources assigned to it are recycled for use, by some other objects.



 

Creating the Classes

A class is a template which can be used to create many objects. The class implementation comprises of two components: class declaration and class body.

classDeclaration
{
. . .
classBody
. . .
}

 



 

Class Declaration

The class declaration, declares the name of a class along with some other attributes like class’s superclass, and whether the class is final, public, or abstract. The class declaration should contain the class keyword and the name of the class that you are defining. Therefore the minimum class declaration will look like this:

class NameOfClass
{
. . .
}

 



 

Class Body

Class body follows the class declaration and is always embedded within curly braces { and } as shown in the example above. Class body contains declarations for variables which are members of the class, methods declarations and implemenatations of the class. We will now discuss two special methods that you can declare within a class body: The Constructors and finalize() Method.



 

Constructors

These are some of the rules on constructors:

  • private constructors()- keyword used “private”, no one can instantiate the class as object. But can still expose public static methods, and these methods can construct object and return it, but no one else can do this.
  • package constructors() – None of them outside your package can construct an instance of your class. This is useful when you want to have classes in your package which can do new yourClass() and don’t want to let anyone else to do this.
  • protected constructors() – keyword used “protected” only the subclasses of your class can make use of this package.
  • public constructors() – keyword used “public” the generic constructor will use these.

 



 

Declaring the Member Variables

An object do maintains its state by the variables defined within that class. These variables are known as the member variables. While declaring the member variables for the class, you can specify a host of different “attributes” about those variables: its name, its type, access permission assigned to it, and so on.
Member variable declaration looks like this:

[accessSpecifier] [static] [final] [transient] [volatile] type variableName
The items in the square brackets are optional. The words inside the bracket are to be replaced by names. or keywords.

 

Words specified inside the bracket defines the following aspects of variables:

  • accessSpecifier defines that which all other classes do have access to tahat variable
  • static indicates the variable declared is class member variable as opposed to instance member variables.
  • final indicates the variable is constant.
  • transient variables are not part of object’s persistent state.
  • volatile means the variable is modified asynchronously.


 

Writing a Method

In Java we define methods within the body of a class for which it implements the behaviour. We usually declare methods after its variables in the class body although not required. Similar to the class implementation, a method implementation also consists of two parts: method declaration and method body.

methodDeclaration
{
. . .
methodBody
. . .
}

 



 

Method Declaration

At the minimum, the method declaration component has a return type which indicates the data type of value returned by the method, and name of the method.

returnType methodName()
{
. . .
}

 

Cosider for example, the following code declares a simple method named isEmpty() within the Stack class that returns boolean value (either true or false).

class Stack
{
. . .
boolean isEmpty()
{
. . .
}
}

 

The method declaration shown in the example above is very basic. Methods do have many other attributes like access control, arguments and so on. This section will cover these topics.



 

The Method Body

In the method body all the action of a method takes place, the method body do contains all legal Java instructions that implements the method. For example, here is a Stack class with the implementation for isEmpty() method.

class Stack
{
static final int STACK_EMPTY = -1;
Object stackelements[];
int topelement = STACK_EMPTY;
. . .
boolean isEmpty()
{
if (topelement == STACK_EMPTY)
return true;
else
return false;
}
}

 

Within method body, you can do use “this” to refer the current object.



 

What is Subclasses, Superclasses, and Inheritance?

As other object-oriented programming languages in Java, one class can be derived from other class. For example, suppose you hav a class named MouseEvent that represents the event when user presses the mouse button in the GUI window environment. Later, while developing application, you realize that you need a class to represent event when user press a key on the keyboard. You can write the KeyboardEvent class from scratch, but since MouseEvent and the KeyboardEvent classes share some states and behaviours like which mouse button or key was pressed,the time that the event occurred, and so on, we can go for duplicating the MouseEvent class rather than re-inventing the wheel, You can take advantages of subclassing and inheritance..and so you create a class Event from which both MouseEvent and KeyboardEvent can be derive

Event is now a superclass of both MouseEvent and KeyboardEvent classes. MouseEvent and KeyboardEvent are now called subclasses of class Event. Event do contains all the states and behaviour which are common to both mouse events and keyboard events. Subclasses, MouseEvent and KeyboardEvent, inherit the state and behaviour from the superclass. Consider for example, MouseEvent and KeyboardEvent both inherits the time stamp attribute from super class Event.



 

How to Create a Subclass

You do declare that a class is subclass of another class in the Class Declaration. Suppose that you wanted to create a subclass called “ImaginaryNumber” of the “Number class”. (where the Number class is a part of java.lang package and is base class for Floats, Integers and other numbers.).You can now write:

class ImaginaryNumber extends Number
{
. . .
}

 

This line declares ImaginaryNumber as a subclass of Number class



 

Write a Final Class

Java allows us to declare our class as final; that is, the class declared as final cannot be subclassed. There are two reasons why one wants to do this: security and design purpose.

  • Security: To subvert systems, One of the mechanism hackers do use is, create subclasses of a class and substitute their class for the original. The subclass looks same as the original class but it will perform vastly different things, causing damage or getting into private information possibly. To prevent this subversion, you should declare your class as final and prevent any of the subclasses from being created.
  • Design: Another reason us to declare a class as final is object-oriented design reason. When we feel that our class is “perfect” and should not have subclasses further. We can declare our class as final.

To specify that the class is a final class, we should use the keyword “final” before the class keyword in the class declaration.If we want to declare the ImaginaryNumber class as final calss, its declaration should look like this:

final class ImaginaryNumber extends Number implements Arithmetic
{
. . .
}

 

If subsequent attempts are made to subclass ImaginaryNumber, it will result in a compiler error as the following:

Imagine.java:6: Can’t subclass final classes: class ImaginaryNumber
class MyImaginaryNumber extends ImaginaryNumber {
^
1 error

 



 

Create a Final Method

If creating final class seems heavy for your needs, and you just want to protect some of the classes methods being overriden, you can use final keyword in the method declaration to indicate the compiler that the method cannot be overridden by subclasses.



 

Writing Abstract Classes

Sometimes you may want only to model abstract concepts but don’t want to create an instance of the class. As discussed earlier the Number class in java.lang package represents only the abstract concept of numbers. We can model numbers in a program, but it will not make any sense to create a generic number object. Instead, the Number class behaves as a superclass to Integer and Float classes which do implements specific case of numbers. Classes like Number, that implements only the abstract concepts and thus should not be instantiated, are called abstract classes.
An abstract class is a class which can only be subclassed and cannot be instantiated.

To declare the class as an abstract class we use the keyword “abstract” before the keyword class in the class declaration:

abstract class Number
{
. . .
}

 

If any attempt is made to instantiate an abstract class, compiler will displays error as shown below and refuses to compile the program:

AbstractTest.java:6: class AbstractTest is an abstract class.
It can’t be instantiated.
new AbstractTest();
^
1 error

 



 

Writing the Abstract Methods

An abstract class can contain abstract methods, abstract methods are the methods, with no implementation. Therefore an abstract class can define all its programming interface and thus provide its subclasses the method declarations for all the methods that are necessary to implement the programming interface. However, an abstract class can leave implementation details of the methods to the subclasses.

You would declare an abstract class, GraphicObject, which provides the member variables and methods which are shared by all of the subclasses. GraphicObject can also declare abstract methods for the methods, such as draw(), that needs to be implemented by the subclasses, but in entirely different ways. The GraphicObject class would look like this:

abstract class GraphicObject
{
int x, y;
. . .
void moveTo(int newX, int newY)
{
. . .
}
abstract void draw();
}

 

An abstract class is not have an abstract method in it. But any of the class that do have an abstract method in it or in any of the superclasses should be declared as an abstract class. Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, shoul provide an implementation for the draw() method.

class Circle extends GraphicObject
{
void draw()
{
. . .
}
}
class Rectangle extends GraphicObject
{
void draw()
{
. . .
}
}

 



 

How to Create and Use Interfaces

Interfaces provides a mechanism to allow hierarchically unrelated classes do implement same set of methods. An interface is the collection of method definitions and the constant values which is free from dependency on a specific class or a class hierarchy. Interfaces are useful for the following purpose:

  • declaring methods which one or more than one classes are expected to implement
  • revealing the object’s programming interface without revealing its class (objects like these called anonymous objects and are useful while shipping a package of classes to the other developers)
  • capturing the similarities between unrelated classes without forcing the class relationship


 

Create an Interface

Creating an interface is similar to that of creating a new class. An interface definition consists of two components: interface declaration and interface body.

interfaceDeclaration
{
interfaceBody
}

 

The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.



 

Use an Interface

An interface is used when the class claims to implement that interface. A class do declares all the interfaces that are implemented in the class declaration. To declare that the class implements one or more interfaces, make use of the keyword “implements” followed by comma-delimited list of the interfaces implemented by the class.

Suppose that we are writing a class that implements a FIFO queue. Since the FIFO queue class is a collection of objects (an object which contains other objects) it doesnot make any sense to implement the Countable interface. The FIFOQueue class would declare that it do implements the Countable interface as shown below:

class FIFOQueue implements Countable
{
. . .
}

 

And thereby guaranteeing that it provides implemenations for currentCount(), incrementCount(),setCount(), and decrementCount() methods.

 

<!–

–>

Leave a Comment

Syntax and Semantics of JAVA

Here you will learn specifics about the syntax and semantics of Java programming language, including control flow and variables, data types and operators and expressions. Here you will also come to know about the strings, the main() method, basic class definitions,variables and static methods. and how make system calls.

Application for Character-Counting

The following program reads and counts characters that are input and then it displays the number of characters read in. This program program uses several Java language components and the class libraries which is shipped with the Java development environment.

class Count
{
public static void main(String args[])
throws java.io.IOException
{
int count = 0;

while (System.in.read() != -1)
count++;
System.out.println(“Input has ” + count + ” chars.”);
}
}

 

The program given above shows the basic syntax of, how the class should be declared. How the method should be called and how to print the output on the sceen. The detailed study of these syntax and semantics will produced in the subsequent chapters.

Leave a Comment

Older Posts »