• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java

Object Class in Java Example

By Dinesh Thakur

All the classes in Java that you have defined so far are subclasses by default whether or not you have specified the superclass. The class which all classes in Java are descendent of (directly or indirectly) is java.lang.Object class. So each class inherits the instance methods of Object class. It is important to be familiar with the methods provided by the Object class so that you can use them in your class.

Using Object class methods

There are methods in Object class:

Public String toString (): This method returns a string representation of an object. The default implementation returns the name of the class followed by ‘@’ and the hexadecimal representation for the object. You can override this method in your classes, to return your String object for your class.

// Returns a string that lists the host name.
// @, Returns a hexadecimal representation for the object.
public String toString(){
     return getClass().getName()+‘@’+Integer.toHexString(dataSource.hashCode());
}

It is always recommended to override toString() method,returns the desired String representation of Object. So, override of toString() method refer – Overriding toString() in Java
Note : If you print any Object reference, then internally invokes toString() method.

Teacher t = new Teacher();

// Below two statements are equivalent

System.out.println(t);

System.out.println(t.toString());

public boolean equals (Object obj): It compares two objects for equality and returns true if they are equal and false otherwise. The comparison is case-sensitive. The code below is the equals() method in the Object class. The method is checking whether the current instance is the same as the previously passed Object.

public boolean equals(Object obj) {
    return(this== obj);
}

public final class getClass(): This method returns a class Object (package Java.lang) that is locked by static synchronized methods of the represented class, and that contains information about the object’s type, such as its classname, its superclass and the interfaces it implements. It also is used to get metadata of this class.

public class clObject {
   public
static void main(String[] args) {
      Object obj = new String(“ecomputernotes”);
      Class cl = obj.getClass();
      System.out.println(“The returned Class object is the : “ + c.getName());
   }
}

NOTE: The getclass() methods of the Object class declared final since their implementation are essential for proper behavior of an object, and so those methods cannot be overridden by any class.

Public int hashcode (): A hash table is a storage mechanism that creates a key-and-value pair for each element. For example, suppose you are keeping records of employees within a company. You need to develop a mechanism for retrieving these records based on employees’ social security numbers. An array really won’t work well for this because the nine-digit identification number is too large. (Vectors and arrays work best for an ordered list of sequential values.) In this situation, hash tables are the answer.

Hash tables enable quick location and retrieval of data by using a key. This key is associated with data contained within an object. The key and value can be from any object, but the key object must implement the hashCode() and equals() methods. Once these methods have implemented, the hash table computes a small integer from the key; this is the hash code and the location where the key/value pair exists. Unlike arrays and vectors, the order of values in a hash table is not important-the hash code ID is all that matters. What is important is that the keys are unique: Only one value can store for each key. If you add a value to a key that is already holding another value, then the added value replace the preexisting value.

As with other data structures, the hash table’s performance is affected by the ratio between the number of elements and the capacity of the structure. This ratio is called the load factor and represented as a percentage. Hash tables need to allocate more storage space than is needed because they generate the unique hash code from the identifying key. As the load factor increases,
so does the likelihood that two or more generated hash codes have the same value; this is called a collision. The extra space is used to ensure that all key/value pairs remain unique. Ideally, the load factor is not higher than 50%; that is, the capacity should be double the number of elements contained in the hash table. If the load factor goes over 75%, the hash table automatically doubles the capacity to ensure adequate performance.

Protected Object clone() throws CloneNotSupportedException: This method creates a copy of the object on which it is called.

Protected void finalize() throws Throwable: The finalize method is a particular method, declared in the object class which allows cleaning up of objects which are not in use (not referenced).
When any objects no longer reference an object, Java reclaims the memory space using garbage collection. Java calls a finalize method before garbage collection takes place.
Syntax:
void finalize() {
…..body of finalize method
}

Finalize methods always have a return type of void and override a default destructor in java.object.Object.
A program can call finalize directly just as it would any other method. However, calling finalize not initiate any garbage collection. It treated like any other method called directly. When Java does garbage collection, finalize is still called even if it has already been called directly by the program.
The finalize method can be overloaded also. If Java finds a finalize method with arguments at garbage-collection time, it looks for a finalize method with no arguments. If it does not find one, Java uses the default finalize method instead.
The system only calls finalize when it is ready to reclaim the memory associated with the object and not immediately after an object no longer referenced. That is, finalize() is called only when the system is running short of memory so that it may be called long after the application finishes.

Object Class in Java Example

class Rectangle extends Object 
{
     private double length,breadth;
     Rectangle(double x,double y)
     {
       length = x ;
       breadth = y ;
     }
   public void area()
   {
     System.out.println("Area of Rectangle is = " + breadth);
   }
   public void circumference()
   {
   System.out.println("Circumferen of Rectangle is= "+2*(length+breadth));
   }
}
 class ObjectClass
{
     public static void main(String[] args)
   {
           Rectangle r = new Rectangle(10,20);
           Rectangle rl = new Rectangle(10,20);
           System.out.println("String Representation = " + r.toString());
           System.out.println("Class Name = " + r.getClass());
           System.out.println("Hash Code  = " + r.hashCode());
           System.out.println("r.rquals(rl) = " + r.equals(rl));
    }
}

Object Class in Java Example

Composition in Java Example

By Dinesh Thakur

Inheritance is suitable only when classes are in a relationship in which subclass is a (kind of) superclass. For example: A Car is a Vehicle so the class Car has all the features of class Vehicle in addition to the features of its own class. However, we cannot always have. is a relationship between objects of different classes. For example: A car is not a kind of engine. To represent such a relationship, we have an alternative to inheritance known as composition. It is applied when classes are in a relationship in which subclass has a (part of) superclass.

Unlike inheritance in which a subclass extends the functionality of a superclass, in composition, a class reuses the functionality simply by creating a reference to the object of the class it wants to reuse. For example: A car has an engine, a window has a button, a zoo has a tiger.

Now consider. the following program that demonstrates the concept of composition

class Date 
{
     private int day;
     private int month;
     private int year;
     Date(int dd, int mm,int yy)
     {
       System.out.println("Constructor of Data Class is Called");
       day=dd;
       month=mm;
       year=yy;
     }
     public String toString()
     {
       return (day+"/"+month+"/"+year);
     }
}
   class Employee
{
     private int id;
     private String name;
     private Date hireDate; //object of Data class
     Employee(int num,String n, Date hire)
     {
       System.out.println("Constructor of Employee Class is Called");
       id=num ;
       name=n ;
       hireDate=hire;
     }
     public void display()
     {
       System.out.println("id = "+id);
       System.out.println("Name = "+name);
       System.out.println("Hiredate = "+hireDate);
     }
}
   public class Composition
   {
       public static void main(String[] args)
        {
                Date d = new Date(01,01,2011);
                Employee emp = new Employee(1,"Dinesh Thakur",d);
                emp.display();
        }
  }

Composition in Java Example

In this example, we first define a class Date for maintaining the date information. Then we define a class Employee that not only contains members id, name and display () but also contains a reference variable hireDate to refer objects of class Date as its member, which maintains employee’s hiredate.

The statement,

emp.display () ;

on execution will display employee’s id, name and the hiredate. The hireDate is obtained with an implicit call to the Date class’s toString () method.

Multilevel Inheritance in Java Example

By Dinesh Thakur

In Our Example illustrates Multilevel Inheritance, Here Class B is derived from superclass A which itself acts as a superclass for the subclass C. The class C inherits the members of Class B directly as it is explicitly derived from it, whereas the members of class A are inherited indirectly into class c (via class B). So the class B acts as a direct superclass and A acts as a indirect superclass for class C.

Each parent-child relationship is representing a level. So class A-class B relationship represents the first level of inheritance and class B-c1ass C represents second level of Inheritance. As the above class hierarchy contains two levels of inheritance which thus represents multilevel inheritance. In multilevel inheritance, there is no limit to the number of levels in a class hierarchy.

Now let us consider a program that shows the multi-level inheritance

class person 
{
      private String name;
      person(String s)
      {  
            setName(s);
      }
      public void setName(String s)
      {
        name = s;
      }
      public String getName()
      {
        return name;
      }
      public void display()
      {
        System.out.println("Name = " + name);
      }
}
    class Employee extends person
  {  
       private int empid;
       Employee(String sname,int id) //Constructor Method
       {
         super(sname);
         setEmpid(id);
       }
       public void setEmpid(int id)
       {
         empid = id;
       }
       public int getEmpid()
       {
         return empid;
       }
       public void display()
       {
         super.display();
         System.out.println("Empid = " + empid);
       }
   };
    class HourlyEmployee extends Employee
  {
      private double hourlyRate;
      private int hoursWorked;
      HourlyEmployee(String sname,int id,double hr,int hw)
      {     
         super(sname,id);
         hourlyRate = hr;
         hoursWorked = hw;
      }
      public double GetGrosspay()
      {
        return (hourlyRate * hoursWorked);
      }
      public void display()
      {
        super.display();
        System.out.println("Hourly Rate = " + hourlyRate);
        System.out.println("Hours Worked = " + hoursWorked);
        System.out.println("Gross pay = " + GetGrosspay());
      }
  };
    class MultilevelInheritance
 {
      public static void main(String[] args)
      {
         HourlyEmployee emp = new HourlyEmployee("Dinesh Thakur",1,15,1800);
         emp.display();
      }
 }

Multilevel Inheritance in Java Example

Method Overriding in Java with Examples

By Dinesh Thakur

In a class hierarchy, A subclass can contain a method with the same signature and return type as in its superclass, then the method in the subclass is said to override the method in the superclass. However in certain situations, the subclass need to modify the implementation (code) of a method defined in the superclass without changing the parameter list. This is achieved by overriding or redefining the method in the subclass. [Read more…] about Method Overriding in Java with Examples

Super Keyword in Java Example

By Dinesh Thakur

The super() keyword is used to reference objects for the immediate parent class. A subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass are not inherited in the subclass. They can only be invoked from constructors of the subclass( es) using the keyword super. [Read more…] about Super Keyword in Java Example

Inheritance Protected Members Java Example

By Dinesh Thakur

A protected field or method in a public class can be accessed directly by all classes within the same package and its subclasses even if the subclasses are in different packages. It is more restrictive than default (or package) access.

class Num //super class 
{
      protected int x,y; //protected Members
      Num(int a, int b)
      {
       x=a;
       y=b;
      }
      public void showxY()
      {
   
        System.out.println("x = " + x);
        System.out.println("y = " + y);
       }
}
    class Result extends Num
 {
      private int z ;
      Result(int a,int b)
      {
        super(a,b);
      }
      public void add()
      {  
        z = x+y;
      }
      public void show()
      {
       System.out.println("z = " + z);
      }
 }
    public class ProtectedInheritance
    {
        public static void main(String[] args)
       {
           Result d = new Result(5,6);
           d.showxY();
           d.add();
           d.show();
       }
   }

Inheritance Protected Members Java Example

In the above program, we create a superclass Num having protected fields x and y and a method showXY (). Then we derive a/subclass Result ,from Num which contains its own data field z and two methods add () and showZ(). The data fields x and y of superclass Num are declared as protected because we want that the method add () of the subclass can access it directly. In main () , we instantiate the object of subclass Result and initialize the fields x and y of superclass Num with values 5 and 6 respectively using a call to the constructor. Then the method add () is called, to calculate the sum of x and y and display the result using showZ() method.

Private Inheritance in Java Example

By Dinesh Thakur

Inheritance is a mechanism of creating a new class from an existing class by inheriting the features of existing class and adding additional features of its own. When a class is derived from an existing class, all the members of the superclass are automatically inherited in the subclass. However, it is also possible to restrict access to fields and method of the superclass in the subclass. This is possible by applying the access Specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The private members of the superclass remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the members of the subclass. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.

class Base 
{
       private int numl;//private member
       public void setData(int n)
       {
         numl = n;//private member accessed within the class
       }
       public int getData()
       {
         return numl;//private member accessed within the class
        }
}
            class Derived extends Base
      {
            int num2 ;
             public void product()
         {
             int num =getData();
             System.out.println("product = " + (num2 * num));
         }
     }
    public class PrivateInheritance
{
      public static void main(String[] args)
      {
          Derived d = new Derived();
          d.setData(20) ; //to set private member numl
          d.num2 = 10 ;
          d.product();
      }
}

Private Inheritance in Java Example

In the above program, numl is a private data field defined in the class Base. Only the methods setData () and getData () in the class Base can access this field directly by name from within its definition. However, it is not accessible to any other class including the Derived subclass.

In order to access the private field numl of the superclass Base in the method product () of the subclass Derived, we call the getData () method of the class Base as shown in the statement

Implementing Inheritance in Java Example

By Dinesh Thakur

Inheriting a superclass gives the ability to a subclass to define only those aspects that differ from or extend the functionality of the superclass. The syntax for creating a subclass is simple. At the beginning of your class definition, use the extends keyword after the class name followed by the name class being extended (i.e. superclass). A subclass can only inherit directly from one superclass. Unlike C++, Java does not support multiple inheritances.

class SubClassName extends SuperClassName

{

// Additional member declarations

}

Here, SubClassName is the name of the subclass and SuperClassName is the name of the superclass whose members are inherited by subclass. The extends keyword identifies that SuperClassName is the superclass for class SubClassName. This keyword establishes an inheritance relationship between the two classes. The body of the subclass contains the members declaration for all the members that are not common to that of the superclass.

The member that is inherited in the subclass is a full member of that class and is freely accessible to any method in the class .When object(s) of the subclass are instantiated, it will not only contain the members of its class but also contain all the inherited members of the superclass from which it is derived.

In order to understand how a subclass is derived from the superclass, let us consider a program having a superclass named Base that consists of a data field numl and a method

baseShow () . Suppose you want to extend the functionality of Base by adding new members. For this, we create subclass named Derived which is derived from the Base. So it inherits all the accessible members of the Base. It also extends the functionality of the Base by adding its own field num2 and methods product () and derivedShow(). These members are exclusive to the subclass and cannot be used by the object of the superclass.

class Base 
{
      int num1;
      void baseShow()
      {
        System.out.println("num1 = " + num1);
      }
}
      //subclass of Base class
      class Derived extends Base
     {
            int num2;
            void product()
          {
               System.out.println("product = " + (num1 * num2));
           }
             void derivedShow()
          {
              System.out.println("num2 = " + num2);
          }
     }
public class ImpInheritance
{
     public static void main(String[] args)
     {
          Derived d = new Derived();
          d.num1 = 20 ;
          d.baseShow();
          d.num2 = 10 ;
          d.derivedShow();
          d.product();
      }
}

Implementing Inheritance in Java Example

The above program explains how a class can be derived using inheritance. Here, class Base is the superclass and class Derived is its subclass. In the class header, ‘Derived extends Base’ means that the class Derived implicitly inherits the data fields and methods of class Base. In other words, we can say that class Derived inherits the field numl and the method baseShow () from the class Base. So these members are freely accessible to any method of the class Derived as if they are members of that class. This can be seen in the method product () of the class ‘Derived’ where numl field of class Base is referred directly.

In the main () method, when the Derived object is created, it can access both numl and

num2fields as well as can call methods baseShow () , derivedShow () and product () .

What is Wrapper Class in Java With Example

By Dinesh Thakur

Elements that can be added to the Vector must be of type java.lang.Object. In other words, vectors cannot handle primitive data types like int, float, char and double as they are not objects. So in order to work with primitive type variables as if they were objects, Java provides class for each of the primitive types. These classes are known as wrapper classes. [Read more…] about What is Wrapper Class in Java With Example

Vector in Java Example

By Dinesh Thakur

Arrays have fixed length, they are not suitable for group of things that grow and shrink over the lifetime of an application. In such situations, Java provides the Vector class which is available in the standard java.util package.

A Vector is similar to an array in that it holds multiple objects and you can retrieve the stored objects by using an index value. However, the primary difference between an array and a Vector is that it can grow itself automatically when its initial capacity is exceeded. A Vector also provides methods for adding and removing elements that you would have to normally do manually in array. To sum up, the Vector class represents an ordered collection of objects that can be referenced using indexes, and can grow and shrink in size.

At any time, a Vector contains a number of elements that is less than or equal to its capacity. The capacity represents the size of the vector in memory. After the capacity is reached, the vector must grow before a new element can be added. The amount by which the Vector should grow is represented by its attribute capacity increment. If the capacity increment is 0, the array simply doubles in capacity each time its needs to grow.

The standard Vector class, java. uti1. Vector, is a parameterized class i.e. when you create an object of that class, you must supply the underlying type. For example, to create a vector of strings, the statement is

Vector<String> v = new Vector<String>();

A Vector can only add elements of object type, you cannot directly add a primitive data type such as int to a Vector

import java.util.Vector; 
public class VectorinJava
{
       public static void main(String[]args)
    {
         Vector<String> v = new Vector<String>();
         String[] days = {"Mon","Tue","fri","sat"};
         for(String str : days)
            v.add(str);
         System.out.println("No.of Elements in Vector is : "+ v.size());
         v.add("sun");
         v.add(2,"Wed");
         System.out.println("No.of Elements in Vector is : "+ v.size());
         System.out.println("First Elements in Vector is : "+v.firstElement());
         System.out.println("Last Elements in Vector is : "+ v.lastElement());
         System.out.println("Elements at Index 3 is : "+ v.get(3));
         v.remove("Sun");
         v.remove(5);
         System.out.println("Element in Vector After Removel are....");
         for(String str : v)
         System.out.println(str);
    } 
} 

Vector in Java Example

StringBuffer deleteCharAt() Method in Java Example

By Dinesh Thakur

StringBuffer deleteCharAt (int index): This method deletes the character at the specified position index from the string buffer. For example,

StringBuffer s1= new StringBuffer (“Helloo Java”);

str.deleteCharAt(4);

As a result, the character at the index 1 from the string buffer will be deleted and will now contain “Hello Java”.

public class StringBufferdeleteCharAt 
{
          public static void main(String[] args)
      {
             StringBuffer s1 = new StringBuffer("Helloo Java");
             s1.deleteCharAt(4);
             System.out.println("s1 : " + s1);
          }
}

StringBuffer deleteCharAt() Method in Java Example

StringBuffer delete() Method in Java Example

By Dinesh Thakur

StringBuffer delete (int start, int end): This method is used to remove a sequence of characters from the StringBuffer object. The start represents the index of the first character to be deleted and end represents the index of one past the last character to remove. Therefore, the deleted substring runs from start to end -1. For example,

StringBuffer s1 = new StringBuffer(“Mr Dinesh Thakur “) :

str.delete(2,9);

results in deleting the substring starting from index 2 to 9 from this string buffer. The string buffer will now contain only “Mr Thakur”.

public class StringBufferDelete 
{
          public static void main(String[] args)
      {
             StringBuffer s1 = new StringBuffer("Mr Dinesh Thakur");
             s1.delete(2,9);
             System.out.println("sl : " + s1);
       }
}

StringBuffer delete() Method in Java Example

StringBuffer Insert() in Java Example

By Dinesh Thakur

StringBuffer insert (int index, char [] str, int offset, int len) :This method inserts a substring into the StringBuffer object starting at position index. The substring is the string representation of len characters from the str []array starting at index position offset.

For example,

char[] chArr ={‘D’,’i’,’n’,’e’,’s’,’h’,’ ‘};

StringBuffer s2 = new StringBuffer(“Mr Thakur”);

s2.insert(3,chArr,0,7);

As a result, characters from chArr array starting from position 0 will be inserted in the invoking

string buffer at the position 3.So the resulting string buffer will be “ Mr Dinesh Thakur “.

public class StringBufferInsert 
{
          public static void main(String[] args)
      {
             StringBuffer s1 = new StringBuffer("Welcome Java");
             s1.insert(7," to");
             System.out.println("sl : " +s1);
             StringBuffer s2 = new StringBuffer("Mr Thakur");
             char[] chArr ={'D','i','n','e','s','h',' '};
             s2.insert(3,chArr,0,7);
             System.out.println("s2 : " + s2);
          }
}

StringBuffer Insert() in Java Example

StringBuffer append()methods in Java Example

By Dinesh Thakur

StringBuffer append(char[] str,int offset,int len) :This method appends the substring to the end of the string buffer. The substring appended is a character sequence beginning at the index offset with the number of characters appended equal to len of the character array str. For example,

char [] chArr = {, t’ ,’o’ ” ‘,’ J’ ,’a’,’v’,’a’};

s1.append(chArr,2,5);

willl append’ ‘,’ J’ ,’a’,’v’,’a’ characters at the end of the string “Welcome”, which results in “Welcome Java”.

public class StringBufferAppendMethod 
{
       public static void main(String[] args)
     {
            StringBuffer s1 = new StringBuffer("Welcome");
            s1.append(" Dinesh Thakur");
            System.out.println("s1 : " +s1);
            s1.append(" ").append("to").append(" Home").append("!");
            System.out.println("s1 : " +s1);
            StringBuffer s2 = new StringBuffer("Welcome");
            char[] chArr = {'t','o',' ','j','a','v','a'};
            s2.append(chArr,2,5);
            System.out.println("s2 : " + s2);
      }
}

StringBuffer append()methods in Java Example

StringBuffer toString() Java Example

By Dinesh Thakur

String toString () : This method returns the value of the invoking StringBuffer object that invoked the method as a string. For example: The statement,

String s = s1.toString();

The String object s will contain “Hello Java”.

public class StringBuffertoString 
{
        public static void main(String[] args)
     {
            StringBuffer sl = new StringBuffer("Hello Java");
            System.out.println("sl.toString() : " + sl.toString());      
      }
}

StringBuffer toString() Java Example

StringBuffer setCharAt() Java Example

By Dinesh Thakur

void setCharAt (int index, char ch) : This method sets the character at the specified index in the string buffer to the new character ch. For example, s1. setCharAt (6, ‘J’) will return Hello Java.

public class StringBuffersetCharAt 
{
        public static void main(String[] args)
     {
            StringBuffer sl = new StringBuffer("Hello java");
            sl.setCharAt(6,'J');
            System.out.println("sl.setCharAt(6,'J') : " + sl);        
      }
}

StringBuffer setCharAt() Java Example

StringBuffer substring() Java Example

By Dinesh Thakur

String substring (int beginIndex) : This method returns a substring of the invoking StringBuffer. The substring returned contains a copy of characters beginning from the specified index position beginIndex and extends to the end of the string. For example, s1. substring (3) returns the substring lo Java.

String substring (int beginIndex, int endIndex) : This method is another version of previous method. It also returns a substring that begins at the specified index begin Index and extends to the character at the index endIndex-l. For example, the statement s1.substring (3, 6); returns the substring “lo”. One should always specify the valid index range.

public class StringBufferSubstring 
{
        public static void main(String[] args)
     {
            StringBuffer sl = new StringBuffer("Hello Java");
            System.out.println("sl.substring(3) =" + sl.substring(3));
            System.out.println("sl.substring(3,6)=" + sl.substring(3,6));           
      }
}

StringBuffer substring() Java Example

StringBuffer charAt() Java Example

By Dinesh Thakur

char charAt (int index) : This method returns the character in the string buffer at the specified index position. The index of the first character is 0, the second character is 1 and that of the last character is one less than the string buffer length. The index argument specified must be greater than or equal to 0 and less than the length of the string buffer. For example, strl.charAt(1) will return character e i.e. character at the index position 1 on the StringBuffer str1.

public class StringBuffercharAt 
{
        public static void main(String[] args)
     {
            StringBuffer sl = new StringBuffer("Hello Java");
            System.out.println("sl.charAt(1) : " + sl.charAt(1));
      }
}

StringBuffer charAt() Java Example

StringBuffer setLength() in Java Example

By Dinesh Thakur

void setLength(int newLength) : This method sets (change) the length of the string contained in the StringBuffer object. If the newly specified length is less than the current length of the string buffer, then the string buffer is truncated to contain exactly the number of characters contained in the newlength parameter. If the specified argument is greater than or equal to the current length, sufficient null characters (‘\ u0000′) are appended to the string buffer until the total number of characters in the string buffer is equal to the specified length. For example, if following is part of a statement, strl.setLength(10) As a result of this, the string referenced by strl will now contain “Welcome\u0000\u0000\u0000” Similarly, strl. setLength (5) will result in “Hell” .

public class StringsetLength 
{
         public static void main(String[] args)
    {
            StringBuffer s3 = new StringBuffer("Hello Java");
            s3.setLength(10);
            System.out.println("s3.capacity () =  " + s3.capacity());
            System.out.println("s3.length() =  "  +  s3.length());
           
     }
}

StringBuffer setLength() in Java Example

Stringbuffer Length() in Java Example

By Dinesh Thakur

int length (): This method returns the number of characters currently in the invoking string buffer. For example,

str1.1ength ()

will return 10, which is the number of characters in the string literal Welcome that is referenced by strl.

public class StringLength 
{
         public static void main(String[] args)
    {
            StringBuffer s1 = new StringBuffer();
            StringBuffer s2 = new StringBuffer(35);
            StringBuffer s3 = new StringBuffer("Hello Java");
            System.out.println("s1.length() =  "  + s1.length());
            System.out.println("s2.length()  = " + s2.length());
            System.out.println("s3.length() =  "  + s3.length());
           
     }
}

Stringbuffer Length() in Java Example

StringBuffer Capacity in Java Examples

By Dinesh Thakur

int capacity () : This method returns the current capacity of the string buffer i.e. number of characters it is able to store without allocating more memory. While discussing capacity () methods, we assume that the StringBuffer object str1 exists which is defined as follows,

StringBuffer str1 = new (“Hello java”);

For example,

str1. capacity ()

it will return 26 which is the sum of length of the string literal referenced by str1 and 16.

public class StringCapacity 
{
         public static void main(String[] args)
    {
            StringBuffer sl = new StringBuffer();
            StringBuffer s2 = new StringBuffer(35);
            StringBuffer s3 = new StringBuffer("Hello Java");
            System.out.println("sl.capacity()  =  " +sl.capacity());
            System.out.println("s2.capacity() = "+s2.capacity());
            System.out.println("s3.capacity () =  " + s3.capacity());
           
     }
}

StringBuffer Capacity In Java Examples

String getBytes() Method in Java Example

By Dinesh Thakur

The String class also provide methods for extracting characters from a string in an array of bytes. This is achieved using the getBytes () method in the String class. This method converts the original string characters into the character encoding used by the underlying operating system which is usually ASCII . For example : The statement,

byte[] txtArray = s1.getBytes();

extracts character from the String object s1 and stores them in the byte array txtArray. There are many other forms of getBytes () available.

public class GetBytesMethods 
{
       public static void main(String[] args)
       {
           String sl = "Hello Java" ;
           byte[] txtArray = sl.getBytes();
           for( int i=0 ;i<txtArray.length; i++)
              System.out.println("txtArray["+i+"] = " + txtArray[i]);
       }
}

String getBytes() Method in Java Example

Conversion between Strings and Arrays

By Dinesh Thakur

As we know that strings are not arrays so the String class also provides methods to convert a string to an array of characters and vice versa. These include

toCharArray();

getChars();

valueOf();

char [] toCharArray (): This method converts the invoking string to an array of individual characters. For example : The statement,

char[] ch = sl.toCharArray();

will convert the string Welcome which is referenced by sl to an array of characters such that ch [0] contains ‘W’, ch [1] contains ‘e’ and so on.

void getChars(int srcBegin, int srcEnd, chsr[] dest, int destBegin): This method copies a substring of the invoking string from index srcBegin to index srcEnd-1 into a character array dest starting from index destBegin. For example: The statement,

char[] txtArray = new char[3];

sl.getChars(3,6,txtArray,O);

will copy characters from the String object slat index position 3 to 5 (i.e. 6 – 1) inclusive, so txtArray[0] will be ‘c’, txtArray[1] will be ‘0’ and txtArray[2] will be ‘m’.

static String valueOf (char [] ch): This method will covert an array of characters to a string. For example : The statements,

char[] ch = {‘W’, ‘E’, ‘L’, ‘C’, ‘0’, ‘M’, ‘E’};

String str String.valueOf(ch);

will return the string Welcome from a character array ch and store the reference in str. There are several versions of valueOf () method that can be used to convert a character and numeric values to strings with different parameter types including in t, long, float, double and char.

Now let us consider a example to show how these work.

public class ConversionMethods 
{
         public static void main(String[] args)
      {
       
          String s1 = "Welcome" ;
          char[] txtArray = new char[3];
          char [] ch = s1.toCharArray();
          for( int i =0; i<ch.length; i++)
               System.out.println("ch["+i+"] = " +ch[i]);
               s1.getChars(3,6,txtArray,0);
               for( int i=0;i<txtArray.length;i++)
                    System.out.println("txtArray["+i+"] = "+txtArray[i]);
                    char[] c = {'W','E','L','C','O','M','E'};
                    String str = String.valueOf(ch);
                    System.out.println("str = " + str);
      }
}

Conversion between Strings and Arrays

Java Substring With Example

By Dinesh Thakur

A string is described as a collection of characters. String objects are immutable in Java, which means they can’t be modified once they’ve been created. A popular question asked in Java interviews is how to find the substring of a string. So, I’ll show you how Substring functions in Java. [Read more…] about Java Substring With Example

String matches() Methods in Java Examples

By Dinesh Thakur

boolean matches (String regex): This method tests whether or not the invoking string matches the given regular expression regex. It returns true if invoking string matches the given regular expression otherwise it returns false.It is different from the equals () method where you can only use the fixed strings. Forexample,

” DineshThakur”.matches(“Dinesh”) // returns false

” DineshThakur”.matches(“Dinesh.*”) // returns true

public class StringMatches 
{
       public static void main(String[] args)
    {
            String s1 = "DineshThakur" ;
            System.out.println("Use of matches() methods");
            System.out.println("s1.matches(\"Dinesh\") : " + s1.matches("Dinesh"));
            System.out.println("s1.matches(\"Dinesh.*\") : " + s1.matches("Dinesh.*"));
     }
}

String matches() Methods in Java

String split() in Java Example

By Dinesh Thakur

String [] split (String regex):This method splits the invoking string into substrings at each match for a specified regular expression regex and returns a reference to an array of substrings. For example, consider the statements.

String str = “Hello Java”;

String[] s = str.split(“[]”);

The first statement defines the string to be analyzed. The second statement calls the split () method for the str object to decompose the string. The regular expression includes the delimiterspace so it will return a reference to array of strings where s[0] contains Welcome, s[1] contains toand s[2] contains Java.

public class StringSplit 
{
     public static void main(String[] args)
     {
            String str3 = "Where there is a Will , there is a way";
            String str[] = str3.split(" ");
                 for(int i=0;i<str.length;i++)
                      System.out.println("str[" + i + "]  : " + str[i]);
      }
}

String split() in Java Example

String replaceFirst() in Java Example

By Dinesh Thakur

String replaceFirst (String regex, String replace): This method replaces the first substring in the invoking string that matches the given regular expression with the specified replacement string replace. For example,

s3.replaceFirst(“is”,”was”);

It will replace the first occurrence of substring is with the substring was in the given string.

public class StringReplaceFirst 
{
     public static void main(String[] args)
     {
            String str3 = "Where there is a Will , there is a way";
            System.out.println("str3.replaceFirst(\"is\" ,\"was\") = " +str3.replaceFirst("is" ,"was"));
      }
}

String replaceFirst() in Java Example

String replaceAll() in Java Example

By Dinesh Thakur

String replaceAll (String regeX, String replace): This method replaces all substrings in the invoking string that matches the given regular expression pattern regeX with the specified replacement string replace. For example,

Str1.replaceAll(“[aeiou]”,”#”);

It will replace all vowels in the invoking string with # symbol. Here [aeiou] is a regular expression which means any of the characters between the square brackets will match

Str3.replaceAll(“is”,”was”);

This statement will replace the substring is with the substring was in the given string. You can get the details of the regular expression from the Sun’s website.

public class StringReplaceAll 
{
     public static void main(String[] args)
     {
            String strl = "Welcome";
            String str3 = "Where there is a Will , there is a way";
            System.out.println("str3.replaceAll(\"is\",\"was\") = " +str3.replaceAll("is" ,"was"));
            System.out.println("strl.replaceAll(\"[aeiou]\" ,\"#\") = " +strl.replaceAll("[aeiou] " ,"#"));
      }
}

String replaceAll() in Java Example

String replace() in Java Example

By Dinesh Thakur

String replace (char oldchar, char newchar): This method returns a new string resulting from replacing all the occurrence of oldchar in the invoking string with newchar. For example,

sl.replace(‘e’, ‘E’); //returns Hello DinEsh

public class StringReplace 
{
     public static void main(String[] args)
     {
            String str1 = "Hello Dinesh";
            System.out.println("str1.replace('e','E') = "+str1.replace('e','E'));
      }
}

String replace() in Java Example

String trim() in Java Example

By Dinesh Thakur

String trim (): This method returns a copy of the string, with leading and trailing white spaces omitted. For example,

String str1 = “Hello Dinesh    “ ;

strl.trim(); //returns Hello Dinesh

String str1 = “Hello Dinesh    “ ; 
strl.trim(); //returns Hello Dinesh
public class StringTrim
{
     public static void main(String[] args)
     {
            String str1 = "     Hello Dinesh        ";
             System.out.println("str1.trim() = " + str1.trim());
      }
}

String trim() in Java Example

« Previous Page
Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW