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–)
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.



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.



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





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.

. . .
. . .



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.



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.

. . .
. . .



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;
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: 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: 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.



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[])
int count = 0;

while ( != -1)
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

Anatomy of a Java Application

Anatomy of a Java Application

Java programs which do run within a browser which is Java-compatible are known as applets. Here we have discussed about the components of a stand-alone Java program, that is, a program written in the Java language which can run independently of any browser. Stand-alone programs in Java are also known as Java applications. The following application “DateApp” displays the current time and date.

import java.util.Date;
class DateApp
public static void main (String args[])
Date today = new Date();



Import statement

As we can see the first line in the program imports the Date class from the package called “java.util”. By importing we can make that class available to the file into which it has been imported. A “java.util” package is a collection of classes that do provide miscellaneous functionality. The “Date” class from the java.util package allows you to manage and also manipulate calendar dates in system independent way.


How to Define a Class

In Java language, the general form of class definition is as shown below

class name
. . .


The keyword class begins the class definition for a given classname here it is “name”. All variables and methods of the given class are held inside the curly brackets that begins and ends the definition block of a class. In the class “DateApp” has no variables and has only one method called main().


Method: main()

main() method is called the brain of the Java need to specify the name of the class which you want to run while running a Java application using the Java interpreter. Interpreter will do invokes the main() method defined in the class. The main() method will control the program flow, allocates all the resources which are needed, and will run any of the methods that do provide the functionality to the application.


Using Objects in the Programs

The first line in the method “main()”, will declare, initialize and instantiate an object called “today”. The default constructor is used to initialize today, that initializes the object new Date to contain the current time and date. In the second line of the method “main()” uses dot operator to refer to the class’s or object’s methods or variables. The above code illustrates the uses of instance variables and methods and class methods and variables


How to Save, Compile and Run an Application

To create and edit Java program, you can make use of any editor or word processing program. Java programs should be saved with the .java extension, so using any ASCII editor, write the program exactly as it appears in this page and save the program with the file name

After creating your Java program, you should compile the program using the Java compiler before running it When a Java source file is compiled, the compiler creates a .class extension file in the folder in which the source file is stored. The compiler will name the resulting .class file after the class is defined in the source file. For example, when you compile the “DateApp” class which you have created above, the compiler will name the resulting class file “DateApp.class” after the class, with regardless of the name of the source file. Even if you would save the DateApp class as, the compiler would still create a file called “DateApp.class”.

After compilation, using the Java interpreter you can run the application . The program must display the current time and date.


Leave a Comment

OOP concepts

What is Object?

The real-world objects(any living or non- living thing) share two characteristics: they do have state and behaviour. For example, dogs have a state ( like name, color, etc) and behaviour ( like barking, fetching etc). Also consider for example a Bicycles have a state such as current gear, current wheels, number of gears etc and and behaviour such as braking, accelerating etc.
After the real-world objects Software objects have been modelled in that, they too,have states and behaviours. A software object maintains states in the variables and implements behaviour by methods.


What is Encapsulation?

Packing up an object’s variables within its methods is called encapsulation. Encapsulating the related variables and methods into neat software bundle seems simple but is a powerful idea that provides two benefits to the software developer:

  • Modular programming– The source code for any of the object can be written and maintained independently from those of the source code written for other objects. Also, an object can be easily used passing around in the system. For example you can give your bicycle to someone else and it will still work for them too.
  • Information hiding– An object has a public interface by which other objects can communicate with it. But on the other hand objects can maintain private information and methods that cannot be communicated to others.


What are Messages for?

Using “messages” software objects do interact and communicate with each other. When an object say A wants another object say B to perform one of its methods, then object A can send message to object B.


There are three components comprising a message:

Following three components are enough for the receiving object to perform the desired method. No other information or context is required. Thus, objects in different processes or even on different machines can communicate to each other through the use of messages.

  • the object to whom the message is addressed (bicycle)
  • the name of the method to perform (change gears)
  • any parameters needed by the method.

The Benefit of Messages

  • Since everything that an object can do is expressed through its methods, message passing supports all possible interactions between objects.
  • To send and receive messages back and forth objects don’t need to be in the same process or even on the same machine.


What are Classes?

In object-oriented software, it’s also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind share certain characteristics and you can create a blueprint for those objects. Software blueprints for objects are called classes.


The Benefit of Classes

Objects provide the benefit of modularity and information hiding. Classes provide the benefit of reusability. Bicycle manufacturers reuse the same blueprint over and over again to build lots of bicycles. Software programmers use the same class over and over to again create many objects.


What is Inheritance?

Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don’t know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars and pedals.

Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, race bikes and tandems are all different kinds of bicycles. In object-oriented terminology, mountain bikes, race bikes and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, race bikes and tandems.


The Benefit of Inheritance

  • Subclasses provide specialized behaviours from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.
  • Programmers can implement superclasses that define “generic” behaviours (called abstract classes). The essence of the superclass is defined and may be partially implemented but much of the class is left undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

Leave a Comment

Introduction to JAVA

Getting start with

Applications and Applets are the most common Java programs. like HotJava browser,

, Applications are stand-alone programs. Applets are similar to applications, but they adhere to some sets of conventions which allow them run within a browser which is Java-compatible.


“Hello World” Application Program

By following the steps given in the page below. you can do create and also use a standalone Java application.

Create a file named with the Java code shown here:
class AppHelloWorld
public static void main (String args[])
System.out.println(“Hello World!”);



Compile the given source file

Using Java compiler compile the source file. If the compilation succeeds, then the compiler creates a file called AppHelloWorld.class. If compilation fails, make sure what you have typed in and what name you have given.


Run the application program

Using the Java interpreter run the program. You will see “Hello World!” displayed on your standard output screen.


“Hello World” Applet

By following the steps given here, you can create and use applet. When you have followed all the steps, your directory/folder structure should look something like a tree as shown here:


·         Hello.html (an HTML file you create)

· (a Java source file you create)

·         HelloWorld.class ( a Java bytecode file the compiler creates for you)


Create a directory

Create a directory that can hold your HTML pages. and do this only if you have not created any.
note: If you want to reload the applet do NOT invoke the hotjava (or any other applet viewer) from the HTML directory. Because of the way the class loader do work, an applet cannot be reloaded (for example, after making changes to its code) when you invoke applet viewer from the directory which is having the applet’s compiled code.



Create the Java source file

Create a file named in the HTML directory with the Java code shown here:

import java.awt.Graphics;
public class HelloWorld extends java.applet.Applet
public void init()
public void paint(Graphics g)
g.drawString(“Hello world!”, 50, 25);



Compile your source file

Compile your source file using Java compiler. If the compilation succeeds, then compiler creates a file called HelloWorld.class. If compilation do fails, make sure you typed in and have named the code exactly as shown above.



Then Create an HTML file that includes applet

Create an HTMl file Hello.html containing the following text in your HTML directory:

<TITLE> A Simple Program </TITLE>

Here is the output of our program:
<br> <APPLET CODE=”HelloWorld.class” WIDTH=150 HEIGHT=25>



Loading an HTML file

Load the new HTML file into HotJava by entering the file’s URL in the Document URL field near to the top of the HotJava window, as shown below:



Once the you successfully completed these steps, you should get the following in the HotJava page that comes up:

Here is the output of our program:

Hello World!


Leave a Comment

Foxpro – Calculate and Print the Multiplication Table of a Number Entered

Q : Foxpro –  Calculate and Print the Multiplication Table of a Number entered



do while ans=”y”


                input “enter the table to print :” to t


                do while i <=10


                                ?str(t)+ “  *” + str(i,4) + “  = ” + str(p,4)



                accept “want to print another table :” to ans



Leave a Comment

Older Posts »