Archive for the ‘SCBCD’ category

What is the getRollbackOnly method?

November 4th, 2009

The getRollbackOnly() method of the EJBContext interface is used to test if the current transaction has been marked for rollback or not. An enterprise bean with container-managed transaction demarcation can use this method. A transaction can be marked for rollback by the enterprise bean itself, by other enterprise beans, or by other components of the transaction processing infrastructure.

It is necessary that the container handle the EJBContext.getRollbackOnly() method if it is invoked from a business method executing with the REQUIRED, REQUIRES_NEW, or MANDATORY transaction attribute. The java.lang.IllegalStateException is thrown if the EJBContext.getRollbackOnly() method is invoked from a business method executing with the SUPPORTS, NOT_SUPPORTED, or NEVER transaction attribute.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

What is the <transaction-type> attribute of the persistence.xml file?

November 2nd, 2009

The <transaction-type> attribute of the persistence.xml file specifies whether the type of the entity manager used in the persistence unit is JTA or resource-local. The default transaction type for Java EE is JTA, and it is RESOURCE_LOCAL for JAVA SE. For example:

<persistence-unit name=”AccountNumber” transaction-type=”JTA”>


<persistence-unit>

Here, AccountNumber is a persistent unit, and transaction-type is JTA.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

What is the round() method?

October 30th, 2009

The round() method is a static method of the java.lang.Math class. It takes a floating-point number as an argument and returns an integer representation of the number. The value returned by the round() method is the same as the value returned by the Math.floor() method in the following conditions:

  • if the argument to the round() method is a positive number and the fractional part of the number is less than 0.5.
  • if the argument to the round() method is a negative number and the fractional part of the number is greater than 0.5.

The value returned by the round() method is the same as the value returned by the Math.ceil() method in the following conditions:

  • if the argument to the round() method is a positive number and the fractional part of the number is greater than or equal to 0.5.
  • if the argument to the round() method is a negative number and the fractional part of the number is less than or equal to 0.5.

The round() method is overloaded with separate versions for float and double arguments. The signatures of the two versions of the round() method are given below:

public static int round(float num)
public static long round(double num)

The first version of the method takes a float type value as an argument and returns a number after rounding off the value to the nearest int value.

The second version of the method takes a double type value as an argument and returns a number after rounding off the value to the nearest long value.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

Modifiers

October 29th, 2009

Modifiers are Java keywords that are used to declare features in applications. They affect either the lifetime or the accessibility of a feature. A feature may be a class, a method, or a variable.

Modifiers that affect the visibility of a feature are called access modifiers or visibility modifiers. The remaining modifiers do not fall into any clear categorization and may be called storage and lifetime modifiers.

The Access Modifiers

Access modifiers control the access of a feature. They enable a programmer to determine whether access to a feature is limited to a particular class, a class and its subclass, or a package, or if it is accessible without any restriction. Following are the features of a class:

  • The class itself
  • Its class variable
  • Its methods and constructors

Java provides three access modifiers: public, protected, and private. If none of the three access modifiers is used to declare a feature, Java provides a fourth modifier for which there is no name. It may be called a default access, a package access, or a friendly access modifier. A feature may be declared using at most one access modifier. A compile-time error will occur if more than one access modifier is used to declare a feature. The access modifiers are briefly described as follows:

  • private

    The private modifier is the most restrictive access modifier. It limits the visibility of methods and instance variables to the class in which they are defined. An instance variable declared as private is visible (or accessible) only by methods within the same class, but any other classes or objects cannot access it. A method declared as private can be invoked by methods in that same class but not by any other classes. In addition, neither private variables nor private methods are inherited by subclasses.

  • default access

    When none of the three access modifiers is used to declare a feature, the default access modifier is provided by Java. This modifier enables a feature to be accessed by any other classes, provided that the classes are in the same package in which the class that defines them belongs to. Variables or methods declared without any access modifiers are accessible to all the other classes in the same package in which the class containing them belongs to.

  • protected

    An intermediate level of access between package and private is protected. Methods or variables declared as protected are accessible to all classes within the same package in which the class that defines them belongs to. They are also accessible to subclasses of the class that have been defined outside the package.

  • public

    The most unrestrictive access modifier is public. It can be used to declare a class, a method, or a variable. A class declared as public is accessible in any program without any restriction. It also enables a method, a constructor, or a variable to be accessed anywhere in a program where its class can be accessed.

Access modifiers are generally used to declare class level variables. As variables declared within a method can only be used within its enclosing method, they may not have access modifiers.

Other modifiers

abstract

The abstract modifier can be used to declare classes and methods. A class declared as abstract is a partially implemented class. A class is declared as abstract when it contains one or more abstract methods. A class is said to contain abstract methods in any of the following conditions:

  • The body of the class explicitly declares an abstract method.
  • The class inherits one or more abstract methods from its abstract superclass for which it does not provide implementations.
  • The class directly inherits an interface that contains an abstract method but the class neither declares the method nor does it inherit a method that implements it.

If a class containing an abstract method is not declared as abstract, a compile-time error will occur. A class can also be declared as abstract even if it has no abstract methods.

As the implementation of an abstract class is incomplete, it is not possible to create an instance of an abstract class. However, subclasses of an abstract class that itself is not declared as abstract can be instantiated. Subclasses that extend an abstract class are responsible for implementing the unimplemented part of the abstract class. A class declared as abstract may also contain non-abstract methods.

An abstract method is a method without implementation, i.e., an abstract is not defined in the class in which it is declared. The following points must be noted about the declaration of an abstract method:

  • An abstract method declaration provides the signature of the method, return type, and throws clause (if any), but it does not provide an implementation of the method. The declaration of an abstract method ends with a semicolon rather than a block of code.
  • The class in which the abstract method is declared must itself be declared as abstract.
  • The use of the abstract keyword in a method declaration along with the modifiers: final, static, native, synchronized, or private is not permitted.

By default, a method is non-abstract and it requires a block of code after the declaration part.

static

The static modifier can be used to declare an inner class, a method, and a variable. Static means one per class, not one for each object no matter how many instances of the class might exist. This means that static features can be used without creating an instance of a class.

Variables declared by using the static keyword as a modifier are called static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared using the following syntax:

static type varIdentifier;

where, the name of the variable is varIdentifier and its data type is type.

Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole and not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.

A static method suffers from the following restrictions:

  1. A static method can only call other static methods.
  2. A static method must only access static data.
  3. A static method cannot reference to the current object using keywords super or this.

If a method is not declared as static, it is called an instance method. Instance methods are associated with objects and not with classes. Furthermore, they can access all the variables in a class whether they are instance fields or class fields.

Non-static variables cannot be accessed from within a static method. Therefore, the following code will not compile successfully:

  1. public class ClsStat{
  2.    int x;
  3.    public static void main(String argv[]){
  4.        System.out.println(x);        //a compile-time error
  5.    }
  6. }

In the given code a compile-time error will occur. As the main method is static, it cannot access the non-static field (i.e., x) in the ClsStat class.

The static modifier can be used to declare a nested class. A nested class declared as static is called a static nested class. A static nested class can directly access only static variables and methods defined in its enclosing class. However, it cannot refer directly to instance variables or methods defined in its enclosing class. It can refer them only through an object reference.

A static initializer is a block of code, enclosed within curly brackets and labeled as static. It is not a part of a method. A class may have one or more static initializers. All the static initializers in a class are executed exactly once and in the same order in which they appear in the class. The execution of static initializers takes place at the class load time.

final

The final modifier can be used to declare classes, methods, and variables.

A class can be declared as final if its definition is complete and no subclasses are needed. The use of the final keyword in a class declaration suggests that the class cannot be subclassed. In other words, a final class cannot have any subclasses. For example, the following class declaration will result in a compile-time error:

Class MyClass extends Math{
//other code
}

As the java.lang.Math class is final, its name cannot appear in the extends clause of another class declaration. Declaring a class as final implicitly makes all the methods in the class as final. Therefore, methods of a final class are never overridden

When a method is declared as final, it cannot be overridden or hidden by a subclass. In other words, a subclass cannot introduce a new version of the method. Methods declared as private and all the methods declared in a final class are implicitly final, and there is no need to explicitly declare them as final.

Variables declared with the keyword final as a modifier are called final variables. They are so called because once initialized a value, their values cannot be modified. Any attempt made to modify the value of a pre-initialized final variable will result in a compile-time error.

A final variable is declared as shown below:

final double IAMFINAL=0;

where, IAMFINAL is the name of variable whose data type is double. This statement declares the variable IAMFINAL as final and initializes it with the value 0 at the same time. Further attempts to change the value of IAMFINAL will result in a compile-time error.

native

Methods implemented in a language other than Java are declared using the native keyword as modifier. These methods are declared by using the native keyword. The body of a native method is replaced by a semicolon, which indicates that the implementation of the method is omitted. When a method is declared as native, the JVM arranges for a native method call to result in execution passing to native library code.

synchronized

The use of the synchronized keyword in a method declaration ensures that at a time only one thread can execute the block of statements following the method declaration. Other threads wanting access to the method are forced to wait until the currently executing thread returns from the method.

transient

Only variables can be declared as transient. When used as a modifier in a variable declaration, it suggests that a variable may not be written out when the class is serialized.

volatile

The keyword volatile can be used to declare variables. The use of the keyword volatile in a variable declaration suggests the compiler that multiple threads may access the variable. Therefore, the value of the variable may change unexpectedly. A compile-time error will occur on declaring a variable both volatile and final.

Order of appearance of modifiers:

If two or more modifiers appear in the declaration of a feature, they both affect the functionality of the feature. The order of appearance has no effect on the functionality of the feature. For example, public static means the same as static public.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

A Closer Look at Methods

October 29th, 2009

A method is a set of statements grouped together to perform a specific task. It is written to define the behavior of an object or a class. In object-oriented programming, a behavior is referred to as a message that one object sends to another object. Behavior is the only way by which an object can do anything.

Implementing Methods

A method contains executable code that can be invoked by passing a fixed number of values as arguments. A method has two major parts:

  • method declaration
  • method body

A method declaration gives a lot of information about the method to the compiler, to the runtime system, and to other classes and objects. In addition to the name of the method, the elements in a method declaration are as follows:

  • access modifier
  • additional modifiers
  • return type
  • a formal parameter list
  • checked exceptions thrown by the method

A method body contains a block of code that implements the method. It specifies those statements that execute when the method is called. All the actions take place within the method body.

The general syntax used to write a method is given below:

[access modifiers] [method modifiers] return type method name ([formal parameter list]) [throws clause]{
   // Method body
}

where, the elements given within square braces are optional. The only required elements to declare a method are the name of the method, a return type of the method, and a pair of parentheses.

Access Modifiers used in a Method Declaration

The use of an access modifier in a method declaration determines which other classes can access the method. A method can be declared with one of the following access modifiers: public, private, and protected.

  • public

    When a method is declared as public, code contained in its defining class and every other class in the same package can call the method. If the class in which the method is defined is also declared as public, code in every class whether in the same package or any other package can call the method.

  • protected

    When a method is declared as protected, code contained in its defining class, all classes in the package in which the class that defines the method belongs to, and all subclasses of that class (regardless of package) can call the method.

  • private

    When a method is declared private, only code contained in its defining class can call the method. Code in any other classes cannot call the method.

  • No access modifier

    When none of the three access modifiers is used to declare a method, the “package access” also called “default access” applies. The default access causes the method to be callable from code within its defining class and from all classes within the same package. The method cannot be called by any other class that is not declared in the same package in which the class that declares the method is defined.

Method Modifiers

  • The static modifier

    The use of the static modifier in a method declaration expression declares the method as a class method rather than an instance method. Methods declared with the keyword static as a modifier are called static methods or class methods. They are so called because they affect a class as a whole, and not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.

    A static method suffers from the following restrictions:

    1. A static method can only call other static methods.
    2. A static method must only access static data.
    3. A static method cannot reference to the current object using keywords super or this.

    If a method is not declared as static, it is called an instance method. Instance methods are associated with objects and not with classes. Furthermore, they can access all the variables in a class whether they are instance fields or class fields.

  • The abstract modifier

    An abstract method is a method without implementation, i.e., an abstract method is not defined in the class in which it is declared. The following points must be noted about the declaration of a method:

    1. An abstract method declaration provides the signature of the method, return type, and throws clause (if any), but it does not provide an implementation of the method. The declaration of an abstract method ends with a semicolon rather than a block of code.
    2. The class in which the abstract method is declared must itself be declared as abstract.
    3. The use of the abstract keyword in a method declaration along with the modifiers: final, static, native, synchronized, or private is not permitted.

    By default, a method is non-abstract and it requires a block of code after the declaration part.

  • The final modifier

    When a method is declared as final, it cannot be overridden or hidden by a subclass. In other words, a subclass cannot introduce a new version of the method. Methods declared as private and all the methods declared in a final class are implicitly final and there is no need to explicitly declared them as final.

  • The native modifier

    Methods implemented in a language other than Java are called native methods. These methods are declared by using the native keyword. The body of a native method is replaced by a semicolon, which indicates that the implementation of the method is omitted. When a method is declared as native, the JVM arranges for a native method call to result in execution passing to native library code.

  • The synchronized modifier

    The use of the synchronized keyword in a method declaration ensures that at a time only one thread can execute the block of statements following the method declaration. Other threads wanting access to the method are forced to wait until the currently executing thread returns from the method.

The Role of a return type in a Method Declaration

Java requires that a method must be declared with the data type of the value that it returns. A method declaration specifies the type of value that the method returns. If a method does not return a value, the keyword void is used, which indicates that the method does not return a value.

Method signature

The combination of the name of the method and formal parameter list forms the method signature.

  • Method name

    A method name can be any legal Java identifier.

  • Formal parameters

    The formal parameters of a method are specified by a list of comma-separated parameters specifiers. The general form of a parameter specifier is shown below:

    [final] type parameter_name

    Each parameter specifier consists of its type and name. The use of the final modifier in a parameter declaration is optional. If a method has no parameters, an empty pair of parentheses appears in the declaration of the method.

    Parameters are considered local to a method. The scope of a parameter of a method is the entire body of the method. The parameter is created each time a method is called and is destroyed when the execution leaves the method and returns to the caller of the method.

    When the method is invoked, the values of the actual arguments initialize newly created parameter variables before the execution of the body of the method. Therefore, a compile-time error will occur if a method parameter that is declared final is assigned a value within the body of the method.

The throws exceptions clause in a method declaration

A throws clause is used in a method declaration to declare any checked exceptions that can result from the execution of a method. If a method throws any checked exceptions, the method declaration must indicate the type of those exceptions by using a throws statement followed by a comma-separated list of the checked exception. Although it is not required to mention other (unchecked) exceptions in a throws clause, they can be placed in the throws clause.

The throws clause of a method mentions the exception type or a superclass of that exception for each checked exception that can result from execution of the body of a method. Failure to do so will result in a compile-time error.

Overloading methods

In Java, each method has a signature, which comprises the name of the method and the types and order of the parameters in the formal parameter list.

Java supports method name overloading, i.e., within a class, it possible to declare multiple methods with the same name as long as they differ in their parameter declarations. When this is the case, the method name is said to be overloaded, and the process is called method overloading.

For example, the class java.lang.Math class contains an overloaded method named abs, which returns the absolute value of the argument. The signatures of different versions of the method are given below:

public static int abs(int num)
public static long abs(long num)
public static float abs(float num)
public static double abs(double num)

When an overloaded method is invoked, Java uses either the type of the argument or the number of the argument, or both as its guide to determine which version of the overloaded method to execute. This means that overloaded methods must differ either in the type of parameters or number of their parameters, or both.

The Method body

A method body is a block of code that implements the method. However, if the method is either declared as abstract or native, the block of code is replaced by a semicolon, which indicates an unimplemented method. The body of an implemented method specifies those statements that execute when the method is invoked. Besides other executable statements, the body of a method may contain the following elements:

The return statement

A return statement is used within a method body to return a value from a method. Methods declared with a return type other than void return a value to the calling code using the following form of the return statement:

return expression;

where, the expression is a value returned. If a method is declared as void, its body does not contain any return statement that has an expression.

There are two points to be noted about returning a value from a method:

  1. The data type of the value after the return statement must match the return type of the method. For example, if a method is declared to return a boolean type, only the boolean values true or false may be placed after the return statement.
  2. The variable receiving the value returned by a method must be compatible with the return type with which the method was declared.

Apart from primitive types, a method may also return objects. When a method returns an object, the class of the returned object must be either a subclass of or the exact class of the return type.

The this keyword

In many situations, a method may need to refer to the object that invoked it. Java defines a keyword named ‘this’ to accomplish the task. The this keyword can be used within the body of a method to refer to the current object. The current object is the object on which the method was invoked.

The super keyword

If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.

Local variables

Variables declared within the body of a method are known as local variables. They are so called because they are not available for use outside the block where they are declared. These variables are temporary variables, which are visible to the program only within the scope of the method. The scope defined by a method begins with the block that follows the method declaration. If the method has parameters, they too are included within the scope of the method. When the program control leaves the block, all the variables in the block cease to exist.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

Things to practice for Sun test CX310-055.

October 27th, 2009

The CX310-055 (Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0) checks your real ability as a programmer. In fact it is totally scenario based, rather than knowledge based. This test requires you to have a good understanding of the Java language and the capability to write code for well-defined design applications. For this purpose, along with studying books and taking various practice tests, you should also practice with Java. There will be less number of direct questions, and more questions will be ‘find the output’ type. Besides, Drag-n-Drop questions have been added. A good number of questions will be based on new topics added to the language, i.e., on generics, autoboxing/unboxing, covariant return, variable length arguments, static import, enums and for-each loop. Although, not many direct questions will be there in the test, but practicing them will help clear your fundamentals. Practicing the following things with Java will make you confident enough to score well in the test:

  1. Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.
  2. Write code using if and switch statements.
  3. Write code using all forms of loops including labeled and unlabeled, using break and continue statements, simple and enhanced for loop.
  4. Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally).
  5. Write code that makes proper use of assertions.
  6. Write code that explicitly makes objects eligible for garbage collection.
  7. Write code to invoke overridden or overloaded methods and parental or overloaded constructors.
  8. Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable.
  9. Write code using synchronized wait, notify, and notifyAll to protect against concurrent access issues and to communicate between threads.
  10. Write code that makes use of generic collections with/without generics, and with/without wildcards and find the difference between these approaches.
  11. Write code to explore the benefits and limitations of autoboxing/unboxing.
  12. Use for-each loop in your code. Make use of static import.
  13. Write code using Scanner and find the benefits and limitations of a Scanner.
  14. Write code using the serializable interface and explain the benefits and drawbacks of using this interface.
  15. Write code that makes use of the capabilities of the java.io package for different file operations.
Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

String, StringBuffer and StringBuilder classes

October 26th, 2009

String, StringBuffer, and StringBuilder are classes present in the Object class. String objects are immutable, whereas StringBuffer and StringBuilder objects can be modified.

String Class

The String class is defined in the java.lang package, and hence it is implicitly available to all the programs in Java. The String class is declared as final, which means that it cannot be subclassed. It extends the Object class and implements the Serializable, Comparable, and CharSequence interfaces.

Java implements strings as objects of type String. A string is a sequence of characters. Unlike most of other languages, Java treats a string as a single value rather than as an array of characters.

String objects are immutable, i.e., once an object of the String class is created, the string it contains cannot be changed. In other words, once a String object is created, the characters that comprise the string cannot be changed. Whenever any operation is performed on a String object, a new String object will be created while the original contents of the object will remain unchanged. However, at any time, a variable declared as a String reference can be changed to point to some other String object.

Constructors defined in the String class: The String class defines several constructors. The most common constructor of the String class is the one given below:

public String(String value)

This constructor constructs a new String object initialized with the same sequence of the characters passed as the argument. In other words, the newly created String object is the copy of the string passed as an argument to the constructor.

Other constructors defined in the String class are as follows:

  • public String()

    This constructor creates an empty String object. However, the use of this constructor is unnecessary because String objects are immutable.

  • public String(char[] value)

    This constructor creates a new String object initialized with the same sequence of characters currently contained in the array that is passed as the argument to the constructor.

  • public String(char[] value, int startindex, int len)

    This constructor creates a new String object initialized with the same sequence of characters currently contained in the subarray. This subarray is derived from the character array and the two integer values that are passed as arguments to the constructor. The int variable startindex represents the index value of the starting character of the subarray, and the int variable len represents the number of characters to be used to form the new String object.

  • public String(StringBuffer sbf)

    This constructor creates a new String object that contains the same sequence of characters currently contained in the string buffer argument.

  • public String(byte[] asciichars)

    The array of bytes passed as an argument to the constructor contains the ASCII character set. Therefore, this array is first decoded using the default charset of the platform. Then the constructor creates a new String object initialized with the same sequence of characters obtained after decoding the array.

  • public String(byte[] asciiChars, int startindex, int len)

    This constructor creates the String object after decoding the array of bytes and by using the subarray of bytes.

New constructors in J2SE 5: Two new constructors have been added to Java in version 5, which are as follows:

  • String(int code Points[], int startindex, int numchars)

    where code Points is an array that returns integers and contains Unicode code points, startindex is an integer that represents starting index, and numchars is the number of characters in the string.

  • String(StringBuilder strBldObj)

    This constructor uses a StringBuilder object as an argument.

Special String Operations

  • Finding the length of string

    The String class defines the length() method that determines the length of a string. The length of a string is the number of characters contained in it. The signature of the length() method is as follows:

    public int length()

  • String Concatenation using the + operator

    The + operator is used to concatenate two strings, producing a new String object as the result. For example:

    String sale = “500″;
    String s = “Our daily sale is” + sale + “dollars”;
    System.out.println(s);

    This code will display the string “Our daily sale is 500 dollars”.

    The + operator can also be used to concatenate a string with other data types. For example:

    int sale = 500;
    String s = “Our daily sale is” + sale + “dollars”;
    System.out.println(s);

    This code will display the string “Our daily sale is 500 dollars”. In this case, the variable sale is declared as int rather than String, but the output produced is the same. This is because the int value contained in the variable sale is automatically converted to String type, and then the + operator concatenates the two strings.

String Comparison

The String class defines various methods that are used to compare strings or substrings within strings. Each of them is discussed in the following sections:

  • equals()

    The equals() method is used to check whether the Object that is passed as the argument to the method is equal to the String object that invokes the method. It returns true if and only if the argument is a String object that represents the same sequence of characters as represented by the invoking object. The signature of the equals() method is as follows:

    public boolean equals(Object str)

  • equalsIgnoreCase()

    The equalsIgnoreCase() method is used to check the equality of the two String objects without taking into consideration the case of the characters contained in the two strings. It returns true if the two strings are of the same length and if the corresponding characters in the two strings are the same, without considering the case. The signature of the equalsIgnoreCase() method is as follows:

    public boolean equalsIgnoreCase(Object str)

  • compareTo()

    The compareTo() method is used in conditions where a Programmer wants to sort a list of strings in a predetermined order. The compareTo() method checks whether the string passed as an argument to the method is less than, greater than, or equal to the invoking string. A string is considered less than another string if it comes before it in alphabetical order. The signature of the compareTo() method is as follows:

    public int compareTo(String str)

    where, str is the String being compared to the invoking String. The compareTo() method returns an int value as the result of String comparison. The meaning of these values are given in the following table:

    Value Meaning
    Less than zero The invoking string is less than the argument string.
    Zero The invoking string and the argument string are same.
    Greater than zero The invoking string is greater than the argument string.

    The String class also has the compareToIgnoreCase() method that compares two strings without taking into consideration their case difference. The signature of this method is given below:

    public int compareToIgnoreCase(String str)

  • regionMatches()

    The regionMatches() method is used to check the equality of two string regions where the two string regions belong to two different strings. The signature of the method is given below:

    public boolean regionMatches(int startindex, String str2, int startindex2, int len)

    There is also an overloaded version of the method that tests the equality of the substring ignoring the case of characters in the substring. Its signature is given below:

    public boolean regionMatches(boolean ignoreCase, int startindex, String str2, int startindex2, int len)

    In both signatures of the method, startindex specifies the starting index of the substring within the invoking string. The str2 argument specifies the string to be compared. The startindex2 specifies the starting index of the substring within the string to be compared. The len argument specifies the length of the substring being compared. However, in the latter signature of the method, the comparison is done ignoring the case of the characters in the substring only if the ignoreCase argument is true.

  • startsWith()

    The startsWith() method is used to check whether the invoking string starts with the same sequence of characters as the substring passed as an argument to the method. The signature of the method is given below:

    public boolean startsWith(String prefix)

    There is also an overloaded version of the startsWith() method with the following signature:

    public boolean startsWith(String prefix, int startindex)

    In both signatures of the method given above, the prefix denotes the substring to be matched within the invoking string. However, in the second version, the startindex denotes the starting index into the invoking string at which the search operation will commence.

  • endsWith()

    The endsWith() method is used to check whether the invoking string ends with the same sequence of characters as the substring passed as an argument to the method. The signature of the method is given below:

    public boolean endsWith(String prefix)

Modifying a String

The String objects are immutable. Therefore, it is not possible to change the original contents of a string. However, the following String methods can be used to create a new copy of the string with the required modification:

  • substring()

    The substring() method creates a new string that is the substring of the string that invokes the method. This method has two forms:

    public String substring(int startindex)

    public String substring(int startindex, int endindex)

    where, startindex specifies the index at which the substring will begin and endindex specifies the index at which the substring will end. In the first form where the endindex is not present, the substring begins at startindex and runs till the end of the invoking string.

  • Concat()

    The concat() method creates a new string after concatenating the argument string to the end of the invoking string. The signature of the method is given below:

    public String concat(String str)

  • replace()

    The replace() method creates a new string after replacing all the occurrences of a particular character in the string with another character. The string that invokes this method remains unchanged. The general form of the method is given below:

    public String replace(char old_char, char new_char)

  • trim()

    The trim() method creates a new copy of the string after removing any leading and trailing whitespace. The signature of the method is given below:

    public String trim(String str)

  • toUpperCase()

    The toUpperCase() method creates a new copy of a string after converting all the lowercase letters in the invoking string to uppercase. The signature of the method is given below:

    public String toUpperCase()

  • toLowerCase()

    The toLowerCase() method creates a new copy of a string after converting all the uppercase letters in the invoking string to lowercase. The signature of the method is given below:

    public String toLowerCase()

Searching Strings

The String class defines two methods that facilitate in searching a particular character or sequence of characters in a string. They are as follows:

  • IndexOf()

    The indexOf() method searches for the first occurrence of a character or a substring in the invoking string. If a match is found, then the method returns the index at which the character or the substring first appears. Otherwise, it returns -1. The indexOf() method has the following signatures:

    public int indexOf(int ch)

    public int indexOf(int ch, int startindex)

    public int indexOf(String str)

    public int indexOf(String str, int startindex)

  • lastIndexOf()

    The lastIndexOf() method searches for the last occurrence of a character or a substring in the invoking string. If a match is found, then the method returns the index at which the character or the substring last appears. Otherwise, it returns -1. The lastIndexOf() method has the following signatures:

    public int lastIndexOf(int ch)

    public int lastIndexOf (int ch, int startindex)

    public int lastIndexOf (String str)

    public int lastIndexOf (String str, int startindex)

StringBuffer and StringBuilder classes

Like the String class, the StringBuffer and StringBuilder classes are also present in the java.lang package. Therefore, they are implicitly available to all java classes.

StringBuilder is a new concept introduced in J2SE 5. It is very similar to StringBuffer class. Like String and StringBuffer it extends directly from Object class. StringBuilder can act as a replacement of StringBuffer in places where it is not multithreaded environment. That is where we are not worried about Synchronization or multithreading. The signature of StringBuilder is public final class StringBuilder extends Object implements Serializable, CharSequence. Because StringBuilder is not synchronized, it offers faster performance than StringBuffer.

Constructors defined in the StringBuffer class: The StringBuffer class defines several constructors. The most common constructor of the StringBuffer class is the one given below:

  • public StringBuffer(String value)

    This will construct a StringBuffer constructor with contents of string value and reserves space for extra 16 characters.

Other constructors defined in the StringBuffer class are as follows:

  • StringBuffer()

    This will construct a default StringBuffer constructor reserving room for 16 characters.

  • StringBuffer(int size)

    This will create a constructor with a specified initial size.

  • StringBuffer(Charsequence ch)

    This will create a constructor with a charactersequence ch.

Special StringBuffer Operations

  • Length of StringBuffer

    The StringBuffer and StringBuilder classes define the length() method that determines the length of a StringBuffer/StringBuilder. The length of a Stringbuffer is the number of characters contained in the StringBuffer. The signature of the length() method is given below:

    public int length()

    Length of a StringBuffer can be set using the setLength() method.

    public void setLength(int len)

    where len is the specified length of the StringBuffer. It is an integer value, and is always non-negative.

  • Capacity of StringBuffer

    The StringBuffer and StringBuilder classes define the capacity() method that determines the capacity of a StringBuffer/StringBuilder. The capacity of a StringBuffer is the maximum number of characters that a StringBuffer can hold. The signature of the capacity() method is given below:

    public int capacity ()

    Capacity of a pre-constructed StringBuffer can be pre-allocated using the ensureCapacity() method of StringBuffer as:

    public void ensureCapacity (int capacity)

  • Finding character at a specified location

    The StringBuffer and StringBuilder classes define the charAt() method that is used to obtain the character at a specified index in the StringBuffer/StringBuilder.

    char charAt(int index)

    A character at a given index can be set using setCharAt (int index,char ch) method of StringBuffer class.

    For both the above methods, index cannot be a negative value.

  • Appending to a StringBuffer

    public StringBuilder append(char c)

    This method of StringBuffer class appends the string representation of the char argument to the current sequence. The argument is appended to the contents of this sequence. This increases the length of the sequence by 1.

  • Inserting in a StringBuffer

    StringBuffer has methods to insert various datatypes like a character a string, a string representation of float, double etc at a specified index.
    public StringBuilder insert(int offset, char c)

    This method will insert the string representation of the char argument into this sequence.
    The second argument is inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by one.

    public StringBuilder insert(int offset, char[] str)

    This method will insert the string representation of the char array argument into this sequence.
    The characters of the array argument are inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by the length of the argument.

    public StringBuilder insert(int dstOffset, CharSequence s)

    This method will insert the specified CharSequence into this sequence.
    The characters of the CharSequence argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by the length of the argument s.

    In addition, there are insert methods with argument as an integer value, a boolean value, a long, a float, and a double.

  • Reversing the character sequence of a StringBuffer

    The StringBuffer class has a method to reverse the character sequence in a StringBuffer.

    public StringBuffer reverse()

    This will cause the character sequence to be replaced by the reverse of the sequence.

  • Replacing a sequence of character with another sequence.

    public StringBuilder replace(int start, int end, String str)

    This will replace the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end – 1 or to the end of the sequence if no such character exists.

  • Deleting a character

    The delete() method of StringBuffer class is used to delete a character from starting to the end as specified. There is another method called deleteCharAt () used to delete char from a specified index.

    public StringBuffer delete(int start, int end)

    public StringBuffer deleteCharAt(int index)

  • Obtaining a substring

    StringBuffer class has a method to obtain a substring from a given string. The substring starts from the index specified, and extends up to the end of StrigBuffer. There is also a method with starting and ending indexes specified.

    public String subString(int startindex)

    This will extract a substring from specified index startindex and extends up to end of the StringBuffer.

    public String subString(int startindex, int endindex)

    This will extract a substring from specified index startindex and extends up to specified index endindex.

  • Finding an index

    The StringBuffer class has methods for finding indexes of first and last occurrence of a specified string within the StringBuffer.

    public int indexOf(String str)

    If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.

    public int indexOf(String str, int fromIndex)

    This will return the index within this string of the first occurrence of the specified substring, starting at the specified index. If the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.

    public int lastIndexOf(String str)

    If the string argument occurs as a substring within this object, then the index of the first character of the last such substring is returned; if it does not occur as a substring, -1 is returned.

    public int lastIndexOf(String str, int fromIndex)

    This will return the index within this string of the last occurrence of the specified substring, starting at the specified index. If the string argument occurs as a substring within this object, then the index of the first character of the last such substring is returned; if it does not occur as a substring, -1 is returned.

  • Conversion to string

    A StringBuffer is converted to a string using the toString method.

    public String toString()

    This will return a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.

  • Changing the size

    StringBuffer class has a method called trimToSize, used to reduce the size of the character buffer for the invoking object to exactly fit the current contents.

    public void trimToSize()

If the buffer is larger than necessary to hold its current sequence of characters, it can be resized to become more space efficient.

Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

What is the @WebMethod annotation?

October 8th, 2009

The @WebMethod annotation is applied to a method to declare it as a Web service method. If this annotation is not used in a class annotated with the @WebService annotation, then all the methods of the class are available to the Web service. However, the @WebMethod annotation used on an end point interface is ignored and all the methods of the interface are exposed to the Web service. The attributes of the @WebMethod annotation are as follows:

  • operationName: It specifies the WSDL operation that the method annotated with the @WebMethod annotation implements. The default value of this attribute is the name of the annotated method.
  • action: It is used to generate the SOAPAction in the WSDL. This element is specified as follows:

    <operation name = “NameOfOperation”>
       <soap:operation soapAction = “http://DomainName/SubDomain”/>
       //More elements
       </operation>

  • exclude: It is used to exclude a method from the Web service. This element has a default value as false.
Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

What are the valid parameters and return types for the Web service methods?

October 8th, 2009

The valid parameters and return types for the Web service methods are as follows:

  • All primitive types
  • All wrapper types
  • java.lang.BigDecimal and java.lang.BigInteger
  • java.lang.Calendar
  • java.lang.Date
Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark

What is EJB 3.0/EJB 2.x interoperability?

October 8th, 2009

The EJB 3.0 specification requires that all containers must support bean development for all the previous EJB versions. The container for EJB 3.0 must support the following interoperability issues:

  • Packaging EJB 3.0 and EJB 2.x in the same module.
  • Invoking EJB 2.x beans from EJB 3.0 beans.
  • Invoking EJB 3.0 beans from EJB 2.x beans.
Like this post? Share it with others
If you like this article, please leave a comment or subscribe this blog via RSS or via e-mail, Bookmark and share through your network. Click the AddThis button below. Thanks.
  • Share/Bookmark
uCertify.com | Our Company | Articles | Contact Us | News and Press Release | uCertify India | Entries (RSS)
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD    Cisco Certification: CCNA, CCENT    A+, Network+, Security+ Project+
Oracle Certification: OCP 11g, OCP 10g, OCA 11g, OCA 10g    CIW foundation    EC-212-32,    CISSP    Photoshop ACE CS4    Adobe Flash ACE, PMP, CAPM
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.