Study Anytime Any Where We Will Open The Knowledge For You Anish Sir 24x7 Learning solution It Is Time to join JOB
23 October 2017

Study Anytime Any Where

23 October 2017

We Will Open The Knowledge For You

23 October 2017

Anish Sir 24x7 Learning solution

23 October 2017

It Is Time to join JOB

C Programming

C++ Programming

JAVA Programming

Android Language

Android-logo.png

.Net Programming

net-logo-b55c217213ae49991589ed43d7ed58a7.png

c# Programming

photo_1389636992_quiz_image_temp.png

Asp .Net

asplogo-square.png

PHP Programming

58481791cef1014c0b5e4994.png

Search Your Topic

config
Anish Sir

Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

Website URL: http://toshiyas.in
Saturday, 05 August 2017 08:04

Java Swing

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.


Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components are platform-independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. Swing follows MVC.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

hierarchy of javax swing


Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:

  • By creating the object of Frame class (association)
  • By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.


Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

 
  1. import javax.swing.*;  
  2. public class FirstSwingExample {  
  3. public static void main(String[] args) {  
  4. JFrame f=new JFrame();//creating instance of JFrame  
  5.           
  6. JButton b=new JButton("click");//creating instance of JButton  
  7. b.setBounds(130,100,10040);//x axis, y axis, width, height  
  8.           
  9. f.add(b);//adding button in JFrame  
  10.           
  11. f.setSize(400,500);//400 width and 500 height  
  12. f.setLayout(null);//using no layout managers  
  13. f.setVisible(true);//making the frame visible  
  14. }  
  15. }  

simple example of java swing


Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

 
  1. import javax.swing.*;  
  2. public class Simple {  
  3. JFrame f;  
  4. Simple(){  
  5. f=new JFrame();//creating instance of JFrame  
  6.           
  7. JButton b=new JButton("click");//creating instance of JButton  
  8. b.setBounds(130,100,10040);  
  9.           
  10. f.add(b);//adding button in JFrame  
  11.           
  12. f.setSize(400,500);//400 width and 500 height  
  13. f.setLayout(null);//using no layout managers  
  14. f.setVisible(true);//making the frame visible  
  15. }  
  16.   
  17. public static void main(String[] args) {  
  18. new Simple();  
  19. }  
  20. }  

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.


Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

 
  1. import javax.swing.*;  
  2. public class Simple2 extends JFrame{//inheriting JFrame  
  3. JFrame f;  
  4. Simple2(){  
  5. JButton b=new JButton("click");//create button  
  6. b.setBounds(130,100,10040);  
  7.           
  8. add(b);//adding button on frame  
  9. setSize(400,500);  
  10. setLayout(null);  
  11. setVisible(true);  
  12. }  
  13. public static void main(String[] args) {  
  14. new Simple2();  
  15. }}  
What we will learn in Swing Tutorial
  • JButton class
  • JRadioButton class
  • JTextArea class
  • JComboBox class
  • JTable class
  • JColorChooser class
  • JProgressBar class
  • JSlider class
  • Digital Watch
  • Graphics in swing
  • Displaying image
  • Edit menu code for Notepad
  • OpenDialog Box
  • Notepad
  • Puzzle Game
  • Pic Puzzle Game
  • Tic Tac Toe Game
  • BorderLayout
  • GridLayout
  • FlowLayout
  • CardLayout
Tuesday, 01 August 2017 06:18

Java AWT Label

The object of Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly.

AWT Label Class Declaration

 
  1. public class Label extends Component implements Accessible  

Java Label Example

 
  1. import java.awt.*;  
  2. class LabelExample{  
  3. public static void main(String args[]){  
  4.     Frame f= new Frame("Label Example");  
  5.     Label l1,l2;  
  6.     l1=new Label("First Label.");  
  7.     l1.setBounds(50,100100,30);  
  8.     l2=new Label("Second Label.");  
  9.     l2.setBounds(50,150100,30);  
  10.     f.add(l1); f.add(l2);  
  11.     f.setSize(400,400);  
  12.     f.setLayout(null);  
  13.     f.setVisible(true);  
  14. }  
  15. }  

Output:

java awt label example 1

Java AWT Label Example with ActionListener

 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class LabelExample extends Frame implements ActionListener{  
  4.     TextField tf; Label l; Button b;  
  5.     LabelExample(){  
  6.         tf=new TextField();  
  7.         tf.setBounds(50,50150,20);  
  8.         l=new Label();  
  9.         l.setBounds(50,100250,20);      
  10.         b=new Button("Find IP");  
  11.         b.setBounds(50,150,60,30);  
  12.         b.addActionListener(this);    
  13.         add(b);add(tf);add(l);    
  14.         setSize(400,400);  
  15.         setLayout(null);  
  16.         setVisible(true);  
  17.     }  
  18.     public void actionPerformed(ActionEvent e) {  
  19.         try{  
  20.         String host=tf.getText();  
  21.         String ip=java.net.InetAddress.getByName(host).getHostAddress();  
  22.         l.setText("IP of "+host+" is: "+ip);  
  23.         }catch(Exception ex){System.out.println(ex);}  
  24.     }  
  25.     public static void main(String[] args) {  
  26.         new LabelExample();  
  27.     }  
  28. }  

Output:

TextField: www.toshiyas.in

IP Of www.toshiyas.in is 144.18.16.18

Button : Find IP

 

Tuesday, 01 August 2017 06:09

Java AWT Button

The button class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed.

AWT Button Class declaration

 
  1. public class Button extends Component implements Accessible  

Java AWT Button Example

 
  1. import java.awt.*;  
  2. public class ButtonExample {  
  3. public static void main(String[] args) {  
  4.     Frame f=new Frame("Button Example");  
  5.     Button b=new Button("Click Here");  
  6.     b.setBounds(50,100,80,30);  
  7.     f.add(b);  
  8.     f.setSize(400,400);  
  9.     f.setLayout(null);  
  10.     f.setVisible(true);   
  11. }  
  12. }  

Output:

java awt button example 1

Java AWT Button Example with ActionListener

 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class ButtonExample {  
  4. public static void main(String[] args) {  
  5.     Frame f=new Frame("Button Example");  
  6.     final TextField tf=new TextField();  
  7.     tf.setBounds(50,50150,20);  
  8.     Button b=new Button("Click Here");  
  9.     b.setBounds(50,100,60,30);  
  10.     b.addActionListener(new ActionListener(){  
  11.     public void actionPerformed(ActionEvent e){  
  12.             tf.setText("Welcome to Toshiyas IT");  
  13.         }  
  14.     });  
  15.     f.add(b);f.add(tf);  
  16.     f.setSize(400,400);  
  17.     f.setLayout(null);  
  18.     f.setVisible(true);   
  19. }  
  20. }  

Output:

welcome to Toshiyas IT

Click Here

Tuesday, 01 August 2017 05:27

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

  1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:

  • Button
    • public void addActionListener(ActionListener a){}
  • MenuItem
    • public void addActionListener(ActionListener a){}
  • TextField
    • public void addActionListener(ActionListener a){}
    • public void addTextListener(TextListener a){}
  • TextArea
    • public void addTextListener(TextListener a){}
  • Checkbox
    • public void addItemListener(ItemListener a){}
  • Choice
    • public void addItemListener(ItemListener a){}
  • List
    • public void addActionListener(ActionListener a){}
    • public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:

  1. Within class
  2. Other class
  3. Anonymous class

Java event handling by implementing ActionListener

 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent extends Frame implements ActionListener{  
  4. TextField tf;  
  5. AEvent(){  
  6.   
  7. //create components  
  8. tf=new TextField();  
  9. tf.setBounds(60,50,170,20);  
  10. Button b=new Button("click me");  
  11. b.setBounds(100,120,80,30);  
  12.   
  13. //register listener  
  14. b.addActionListener(this);//passing current instance  
  15.   
  16. //add components and set size, layout and visibility  
  17. add(b);add(tf);  
  18. setSize(300,300);  
  19. setLayout(null);  
  20. setVisible(true);  
  21. }  
  22. public void actionPerformed(ActionEvent e){  
  23. tf.setText("Welcome");  
  24. }  
  25. public static void main(String args[]){  
  26. new AEvent();  
  27. }  
  28. }  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.

event handling in java


2) Java event handling by outer class

 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent2 extends Frame{  
  4. TextField tf;  
  5. AEvent2(){  
  6. //create components  
  7. tf=new TextField();  
  8. tf.setBounds(60,50,170,20);  
  9. Button b=new Button("click me");  
  10. b.setBounds(100,120,80,30);  
  11. //register listener  
  12. Outer o=new Outer(this);  
  13. b.addActionListener(o);//passing outer class instance  
  14. //add components and set size, layout and visibility  
  15. add(b);add(tf);  
  16. setSize(300,300);  
  17. setLayout(null);  
  18. setVisible(true);  
  19. }  
  20. public static void main(String args[]){  
  21. new AEvent2();  
  22. }  
  23. }  
 
  1. import java.awt.event.*;  
  2. class Outer implements ActionListener{  
  3. AEvent2 obj;  
  4. Outer(AEvent2 obj){  
  5. this.obj=obj;  
  6. }  
  7. public void actionPerformed(ActionEvent e){  
  8. obj.tf.setText("welcome");  
  9. }  
  10. }  

3) Java event handling by anonymous class

 
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent3 extends Frame{  
  4. TextField tf;  
  5. AEvent3(){  
  6. tf=new TextField();  
  7. tf.setBounds(60,50,170,20);  
  8. Button b=new Button("click me");  
  9. b.setBounds(50,120,80,30);  
  10.   
  11. b.addActionListener(new ActionListener(){  
  12. public void actionPerformed(){  
  13. tf.setText("hello");  
  14. }  
  15. });  
  16. add(b);add(tf);  
  17. setSize(300,300);  
  18. setLayout(null);  
  19. setVisible(true);  
  20. }  
  21. public static void main(String args[]){  
  22. new AEvent3();  
  23. }  
  24. }  

 

Tuesday, 01 August 2017 05:22

Java AWT Tutorial

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.


Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

hierarchy of awt

Container

The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The classes that extends Container class are known as container such as Frame, Dialog and Panel.


Window

The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.


Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.


Frame

The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.


Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

  • By extending Frame class (inheritance)
  • By creating the object of Frame class (association)

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button component on the Frame.

 
  1. import java.awt.*;  
  2. class First extends Frame{  
  3. First(){  
  4. Button b=new Button("click me");  
  5. b.setBounds(30,100,80,30);// setting button position  
  6. add(b);//adding button into frame  
  7. setSize(300,300);//frame size 300 width and 300 height  
  8. setLayout(null);//no layout manager  
  9. setVisible(true);//now frame will be visible, by default not visible  
  10. }  
  11. public static void main(String args[]){  
  12. First f=new First();  
  13. }}  
 

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example that sets the position of the awt button.

awt example


AWT Example by Association

Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are showing Button component on the Frame.

 
  1. import java.awt.*;  
  2. class First2{  
  3. First2(){  
  4. Frame f=new Frame();  
  5. Button b=new Button("click me");  
  6. b.setBounds(30,50,80,30);  
  7. f.add(b);  
  8. f.setSize(300,300);  
  9. f.setLayout(null);  
  10. f.setVisible(true);  
  11. }  
  12. public static void main(String args[]){  
  13. First2 f=new First2();  
  14. }}  
 

awt example

Monday, 24 July 2017 04:30

Java toString() method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.


Understanding problem without toString() method

Let's see the simple code that prints reference.

 
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  String city;  
  5.   
  6.  Student(int rollno, String name, String city){  
  7.  this.rollno=rollno;  
  8.  this.name=name;  
  9.  this.city=city;  
  10.  }  
  11.   
  12.  public static void main(String args[]){  
  13.    Student s1=new Student(101,"Raj","lucknow");  
  14.    Student s2=new Student(102,"Vijay","ghaziabad");  
  15.      
  16.    System.out.println(s1);//compiler writes here s1.toString()  
  17.    System.out.println(s2);//compiler writes here s2.toString()  
  18.  }  
  19. }  
Output:Student@1fee6fc
       Student@1eed786

As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:

Example of Java toString() method

Now let's see the real example of toString() method.

 
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  String city;  
  5.   
  6.  Student(int rollno, String name, String city){  
  7.  this.rollno=rollno;  
  8.  this.name=name;  
  9.  this.city=city;  
  10.  }  
  11.    
  12.  public String toString(){//overriding the toString() method  
  13.   return rollno+" "+name+" "+city;  
  14.  }  
  15.  public static void main(String args[]){  
  16.    Student s1=new Student(101,"Raj","lucknow");  
  17.    Student s2=new Student(102,"Vijay","ghaziabad");  
  18.      
  19.    System.out.println(s1);//compiler writes here s1.toString()  
  20.    System.out.println(s2);//compiler writes here s2.toString()  
  21.  }  
  22. }  
Output:101 Raj lucknow
       102 Vijay ghaziabad
Monday, 24 July 2017 04:29

How to create Immutable class?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:

Example to create Immutable class

In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.
 
  1. public final class Employee{  
  2. final String pancardNumber;  
  3.   
  4. public Employee(String pancardNumber){  
  5. this.pancardNumber=pancardNumber;  
  6. }  
  7.   
  8. public String getPancardNumber(){  
  9. return pancardNumber;  
  10. }  
  11.   
  12. }  

The above class is immutable because:

  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.

There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

StringBuffer Example

 
  1. public class BufferTest{  
  2.     public static void main(String[] args){  
  3.         StringBuffer buffer=new StringBuffer("hello");  
  4.         buffer.append("java");  
  5.         System.out.println(buffer);  
  6.     }  
  7. }  
hellojava

StringBuilder Example

 
  1. public class BuilderTest{  
  2.     public static void main(String[] args){  
  3.         StringBuilder builder=new StringBuilder("hello");  
  4.         builder.append("java");  
  5.         System.out.println(builder);  
  6.     }  
  7. }  
hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.

 
  1. public class ConcatTest{  
  2.     public static void main(String[] args){  
  3.         long startTime = System.currentTimeMillis();  
  4.         StringBuffer sb = new StringBuffer("Java");  
  5.         for (int i=0; i<10000; i++){  
  6.             sb.append("Tpoint");  
  7.         }  
  8.         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
  9.         startTime = System.currentTimeMillis();  
  10.         StringBuilder sb2 = new StringBuilder("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb2.append("Tpoint");  
  13.         }  
  14.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  15.     }  
  16. }  
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:

No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings.
3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class.

Performance Test of String and StringBuffer

 
  1. public class ConcatTest{  
  2.     public static String concatWithString()    {  
  3.         String t = "Java";  
  4.         for (int i=0; i<10000; i++){  
  5.             t = t + "Tpoint";  
  6.         }  
  7.         return t;  
  8.     }  
  9.     public static String concatWithStringBuffer(){  
  10.         StringBuffer sb = new StringBuffer("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb.append("Tpoint");  
  13.         }  
  14.         return sb.toString();  
  15.     }  
  16.     public static void main(String[] args){  
  17.         long startTime = System.currentTimeMillis();  
  18.         concatWithString();  
  19.         System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
  20.         startTime = System.currentTimeMillis();  
  21.         concatWithStringBuffer();  
  22.         System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
  23.     }  
  24. }  
Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms

String and StringBuffer HashCode Test

As you can see in the program given below, String returns new hashcode value when you concat string but StringBuffer returns same.

 
  1. public class InstanceTest{  
  2.     public static void main(String args[]){  
  3.         System.out.println("Hashcode test of String:");  
  4.         String str="java";  
  5.         System.out.println(str.hashCode());  
  6.         str=str+"tpoint";  
  7.         System.out.println(str.hashCode());  
  8.    
  9.         System.out.println("Hashcode test of StringBuffer:");  
  10.         StringBuffer sb=new StringBuffer("java");  
  11.         System.out.println(sb.hashCode());  
  12.         sb.append("tpoint");  
  13.         System.out.println(sb.hashCode());  
  14.     }  
  15. }  
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462
Monday, 24 July 2017 04:23

Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.

Java StringBuilder Examples

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

 
  1. class StringBuilderExample{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.append("Java");//now original string is changed  
  5. System.out.println(sb);//prints Hello Java  
  6. }  
  7. }  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.

 
  1. class StringBuilderExample2{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.insert(1,"Java");//now original string is changed  
  5. System.out.println(sb);//prints HJavaello  
  6. }  
  7. }  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.

 
  1. class StringBuilderExample3{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.replace(1,3,"Java");  
  5. System.out.println(sb);//prints HJavalo  
  6. }  
  7. }  

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

 
  1. class StringBuilderExample4{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.delete(1,3);  
  5. System.out.println(sb);//prints Hlo  
  6. }  
  7. }  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

 
  1. class StringBuilderExample5{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.reverse();  
  5. System.out.println(sb);//prints olleH  
  6. }  
  7. }  

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

 
  1. class StringBuilderExample6{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. }  
  10. }  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

 
  1. class StringBuilderExample7{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. sb.ensureCapacity(10);//now no change  
  10. System.out.println(sb.capacity());//now 34  
  11. sb.ensureCapacity(50);//now (34*2)+2  
  12. System.out.println(sb.capacity());//now 70  
  13. }  
  14. }  

 

 

Page 6 of 31