Wednesday, 27 July 2016

StringBuilder in Java

StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

Internally StringBuilder objects are treated like variable-length arrays that contain a sequence of characters.

StringBuilder class provides an API compatible with StringBuffer, how it differs from StringBuffer is that StringBuilder is not thread-safe whereas StringBuffer is thread-safe.
As per Java docs – This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Constructors for StringBuilder

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

  • StringBuilder() - Constructs a string builder with no characters in it and an initial capacity of 16 characters.
  • StringBuilder(CharSequence seq) - Constructs a string builder that contains the same characters as the specified CharSequence.
  • StringBuilder(int capacity) - Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
  • StringBuilder(String str) - Constructs a string builder initialized to the contents of the specified string.

length and capacity method

Since we are talking about capacity here so it is very relevant to discuss length and capacity method here. As it becomes confusing for some people to distinguish between these two methods.

  • public int capacity() - Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
  • public int length() - Returns the length (character count).

So you can see where length() method returns the length of the sequence of characters currently represented by this StringBuilder object, the capacity() method will return the current capacity. So if you create an empty StringBuilder object its length will be 0 but capacity will be 16 (default).

Example code

public class StringBuilderDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());

 }
}

Output

length 0
capacity 16

Where as when you initialize StringBuilder with a string "Test" where length of the string is 4 then length method will return 4 where as capacity method will return 20 as in that case initial capacity of the string buffer is 16 plus the length of the string argument.

Example code

public class StringBuilderDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("Test");
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());

 }
}

Output

length 4
capacity 20

insert and append method

The principal operations on a StringBuilder are the append and insert methods. Most of the times you will use StringBuilder class over String when you are appending or inserting to a string. That won't result in creating lots of new string objects with every append as StringBuilder object is mutable.

append and insert methods are overloaded so as to accept data of any type. So there are overloaded versions which takes primitive data types like int, float, long, double as parameter apart from having versions which take String, StringBuffer, Object as parameter.

Each of these overloaded versions effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder.

The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

Example Code

public class SBAppendDemo {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder();
  StringBuilder sb1 = sb.append("This").append(" is").append(" Number ").append(1).append(" and ").append(1.101);
  System.out.println("After append -- " + sb.toString());
  
  if(sb == sb1){
   System.out.println("True - same reference");
  }else{
   System.out.println("false - reference changed");
  }

  
  String str = new String();
  String str1 = str.concat("This").concat(" is");
  if(str == str1){
   System.out.println("True - same reference");
  }else{
   System.out.println("false - reference changed");
  }
 }
}

Output

After append -- This is Number 1 and 1.101
True - same reference
false - reference changed

Here note that append method is used with string and primitive data types as parameters and appended to the StringBuilder. Just to check whether the reference remains same or changes a new reference sb1 of StringBuilder is created. It can be seen that sb and sb1 both are pointing to the same StringBuilder object, new object is not created for every append.

Same thing is done with String and data is concatenated to the original string, here again another reference str1 is created but str and str1 are not pointing to the same String object because new String object is created with every concatenation as String is immutable.

Example code for insert method

public class SBDemo {

 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("let");
  sb.insert(2, "n");
  System.out.println("After insert -- " + sb.toString());
 }
}

Output

After insert – lent

toString method

Another important method is toString(), this method returns 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.

reverse method

One more convenient utility method provided by StringBuilder class is reverse() method, in String class there is no such method. In case you want to reverse a string with StringBuilder it is just a method call.

public StringBuilder reverse() - Causes this character sequence to be replaced by the reverse of the sequence.

Example code

public class SBRevDemo {
 public static void main(String[] args) {
  StringBuilder sb = new StringBuilder("Test");
  sb.reverse();
  System.out.println("reversed - " + sb.toString());
 }
}

Output

reversed – tseT

StringBuilder class also has subString and indexOf(), lastIndexOf() methods which provide the same functionality as in String class.

That's all for this topic StringBuilder in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. Splitting a String using split() method in Java
  4. String join() method in Java 8
  5. How to find the longest palindrome in the given String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Tuesday, 26 July 2016

StringBuffer in Java

StringBuffer class is the companion class of String class in Java. StringBuffer is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls.

This characterstic of StringBuffer becomes very handy if you are doing a lot of changes to your String class object by appending or inserting to that string. Since StringBuffer is mutable a new String object is not created every time string is modified, which in turn results in less memory consumptions and not having lots of intermediate String object for garbage collection.

StringBuffer is thread-safe

String buffers are safe for use by multiple threads. If you don't have to bother about thread safety then use StringBuilder class as it supports all of the same operations but it is faster, as it performs no synchronization.

Constructors for StringBuffer

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.

  • public StringBuffer() - Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
  • public StringBuffer(int capacity) - Constructs a string buffer with no characters in it and the specified initial capacity.
  • public StringBuffer(String str) - Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.
  • public StringBuffer(CharSequence seq) - Constructs a string buffer that contains the same characters as the specified CharSequence. The initial capacity of the string buffer is 16 plus the length of the CharSequence argument.

length and capacity method

Since we are talking about capacity here so it is very relevant to discuss length and capacity method here. As it becomes confusing for some people to distinguish between these two methods.

public int capacity() - Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

public int length() - Returns the length (character count).

So you can see where length() method returns the character count with in the string buffer the capacity() method will return the current capacity. So if you create an empty StringBuffer object its length will be 0 but capacity will be 16 (default).

public class SBCapacity {

 public static void main(String[] args) {
  StringBuffer sb = new StringBuffer();
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());
 }
}

Output

length 0
capacity 16
Where as when you initialize StringBuffer with a string "Example" where length of the string is 7 then length method will return 7 where as capacity method will return 23 as in that case initial capacity of the string buffer is 16 plus the length of the string argument.
public class SBCapacity {
 public static void main(String[] args) {
  StringBuffer sb = new StringBuffer("Example");
  System.out.println("length " + sb.length());
  System.out.println("capacity " + sb.capacity());
 }
}

Output

length 7
capacity 23

insert and append method

The principal operations on a StringBuffer are the append and insert methods. Most of the times you will use StringBuffer class over String when you are appending or inserting to a string. That won't result in creating lots of new string objects with every append as StringBuffer object is mutable.

append and insert methods are overloaded so as to accept data of any type. So there are overloaded versions which takes primitive data types like int, float, long, double as parameter apart from having versions which take String, StringBuffer, Object as parameter.

Each of these overloaded versions effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer.

The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

Example code for append method

public class SBDemo {

 public static void main(String[] args) {
  StringBuffer sb = new StringBuffer();
  StringBuffer sb1 = sb.append("This").append(" is").append(" Number ").append(1).append(" and ").append(1.101);
  System.out.println("After append -- " + sb.toString());
  
  if(sb == sb1){
   System.out.println("True");
  }else{
   System.out.println("false");
  }

  
  String str = new String();
  String str1 = str.concat("This").concat(" is");
  if(str == str1){
   System.out.println("True");
  }else{
   System.out.println("false");
  }
 }
}

Output

After append -- This is Number 1 and 1.101
True
false

Here note that append method is used with string and primitive data types as parameters and appended to the StringBuffer. Just to check whether the reference remains same or changes a new reference sb1 of StringBuffer is created. It can be seen that sb and sb1 both are pointing to the same StringBuffer object, new object is not created for every append.

Same thing is done with String and data is concatenated to the original string, here again another reference str1 is created but str and str1 are not pointing to the same String object because new String object is created with every concatenation as String is immutable.

Example code for insert method

public class SBDemo {

 public static void main(String[] args) {
  StringBuffer sb = new StringBuffer("let");
  sb.insert(2, "n");
  System.out.println("After insert -- " + sb.toString());
 }
}

Output

After insert -- lent

toString method

Another important method is toString, this method returns 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.

reverse method

One more convenient utility method provided by StringBuffer class is reverse() method, in String class there is no such method. In case you want to reverse a string with StringBuffer it is just a method call.

public StringBuffer reverse() - Causes this character sequence to be replaced by the reverse of the sequence.

Example code

public class SBRevDemo {

 public static void main(String[] args) {
  StringBuffer sb = new StringBuffer("Test String");
  sb.reverse();
  System.out.println("reversed - " + sb.toString());
 }

}

Output

reversed - gnirtS tseT

StringBuffer class also has subString and indexOf(), lastIndexOf() methods which provide the same functionality as in String class.

That's all for this topic StringBuffer in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. Splitting a String using split() method in Java
  2. String comparison in Java
  3. String join() method in Java 8
  4. Check whether a given String/Number is a palindrome or not
  5. How to find all the permutations of the given String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Friday, 22 July 2016

String join() method in Java 8

There are many scenarios when you want to join multiple strings to create a new string may be with a delimiter too between two strings (like | or ,). Earlier you would have used StringBuilder or StringBuffer class to append the string one by one for joining or may be you would have used any third party library like Apache Commons which has StringUtils class.

Code snippet using StringBuilder

StringBuilder sb = new StringBuilder();
boolean firstFlg = true;
String delimiter = “,”;
for (String str: strArray){
        if (firstFlg){
         firstFlg = false;
        }
      else{       
  sb.append(delimiter);
        }
      sb.append(str);
}
return
sb.toString();

join() method

Though String is a very important class and it provides a lots of methods for comparison of strings, searching with in string but somehow there was no method for joining multiple strings. With Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings so let's see an example how to join strings in Java 8.

join() method in String class

join method has two overloaded versions -
  • public static String join(CharSequence delimiter, CharSequence... elements) - Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
  • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String

Example code

  1. If you have 3 string variables which you want to join with space in between or with '-' in between then it can be done using the following Java code -
    public class StringJoin {
    
     public static void main(String[] args) {
      String str1 = "An";
      String str2 = "example";
      String str3 = "string";
      
      // joining with space
      String finalStr = String.join(" ", str1, str2, str3);
      System.out.println("str - " + finalStr);
      // joining with hyphen
      finalStr = String.join("-", str1, str2, str3);
      System.out.println("str - " + finalStr);
      
     }
    }
    

    Output

    str - An example string
    str - An-example-string
    
  2. If you have 3 string variables day, month and year which you want to join to create a date in format dd/mm/yyyy.
    public class StringJoin {
    
     public static void main(String[] args) {
      String str1 = "26";
      String str2 = "01";
      String str3 = "2016"; 
      String finalStr = String.join("/", str1, str2, str3);
      System.out.println("str - " + finalStr);
      
     }
    }
    

    Output

    str - 26/01/2016
    
  3. If you have list of Strings then you can use the second join method to join all the strings with in the list.
    import java.util.ArrayList;
    import java.util.List;
    
    public class ListJoin {
    
        public static void main(String[] args) {
            List<String> strList = new ArrayList<String>();
            strList.add("An");
            strList.add("example");
            strList.add("string");
            // joining with comma as delimiter
            String finalStr = String.join(",", strList);
            System.out.println("str - " + finalStr);
    
        }
    }
    

    Output

    str – An,example,string
    

StringJoiner Class

In Java 8 there is also a StringJoiner class that can be used for joining the Strings. It has two constructors.

  • StringJoiner(CharSequence delimiter) - Constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter.
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) - Constructs a StringJoiner with no characters in it using copies of the supplied prefix, delimiter and suffix.

Example code

Let us see an example to clarify things.

  1. If you have three strings which you want to join and delimiter is ':' then it can be done using StringJoiner class as follows -
    import java.util.StringJoiner;
    
    public class StringJoinerDemo {
     public static void main(String[] args) {
      String str1 = "An";
      String str2 = "example";
      String str3 = "string";
      // providing delimiter
      StringJoiner sj = new StringJoiner(":");
      // adding strings that are to be joined
      sj.add(str1).add(str2).add(str3);
      System.out.println(sj.toString());
     }
    }
    

    Output

    An:example:string
    
  2. If you want to get the joined strings with suffix and prefix so that the end string looks like this - (An,example,string)
    import java.util.StringJoiner;
    
    public class StringJoinerDemo {
     public static void main(String[] args) {
      String str1 = "An";
      String str2 = "example";
      String str3 = "string";
      // providing delimiter and suffix, prefix
      StringJoiner sj = new StringJoiner(",", "(", ")");
      // adding strings that are to be joined
      sj.add(str1).add(str2).add(str3);
      System.out.println(sj.toString());
     }
    }
    

That's all for this topic String join() method in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. String charAt() and subString() methods in Java
  4. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  5. Splitting a String using split() method in Java
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Wednesday, 20 July 2016

Splitting a String using split() method in Java

String provides a split method in order to split the string into one or more substring based on the given regular expression.

split() method has 2 variants -

  • split(String regex) - Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that matches the given expression.The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
  • split(String regex, int limit) - The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

Example Code

  1. If you have a string where one (or more) spaces are used and you want to split it around those spaces.
    public class StringSearch {
     public static void main(String[] args) {
      String str1 = "split example    program";
      String[] strArray = str1.split("\\s+");
      System.out.println("" + strArray.length);
      for(String w : strArray){
       System.out.println("words - " + w);
      }
     }
    }
    

    Output

    3
    words - split
    words - example
    words – program
    
  2. If you have a date in dd/mm/yyyy format and you want to split it into day, month and year.
    public class StringSearch {
     public static void main(String[] args) {
      String date = "20/01/2016";
      String[] dateArr = date.split("/");
      System.out.println("" + dateArr.length);
      System.out.println("day " + dateArr[0] + " Month " + dateArr[1] + " Year " + dateArr[2]);
     }
    }
    

    Output

    3
    day 20 Month 01 Year 2016
    

Using with limit argument

Suppose you just want the day part of the date then you can use the split() method which also passes limit as argument -

public class StringSearch {

 public static void main(String[] args) {
  String date = "20/01/2016";
  String[] dateArr = date.split("/", 2);
  System.out.println("" + dateArr.length);
  System.out.println("day " + dateArr[0]);

 }

}
Output
2
day 20

That's all for this topic Splitting a String using split() method in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. String charAt() and subString() methods in Java
  4. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  5. How to find all the permutations of the given String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Tuesday, 19 July 2016

Searching within a String using indexOf(), lastIndexOf() and contains() methods

There are scenarios when you want to find characters or substrings within a string. For that purpose String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().

  • indexOf() - This method search forward from the beginning of the string and returns the index within this string of the first occurrence of the specified character/substring. If a character or substring is not found indexOf() returns -1.
  • lastIndexOf() - This method search backward from the end of the string and returns the index within this string of the last occurrence of the specified character/substring. If a character or substring is not found lastIndexOf() returns -1.

The String class also provides a search method, contains, that returns true if the string contains a particular character sequence. Use this method when you only need to know that the string contains a character sequence, but the precise location isn't important.

indexOf() and lastIndexOf()

There are various overloaded versions of indexOf() and lastIndexOf() methods.

indexOf()

  • indexOf(int ch) - Returns the index within this string of the first occurrence of the specified character.
  • indexOf(int ch, int fromIndex) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
  • indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring.
  • indexOf(String str, int fromIndex) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

lastIndexOf()

  • lastIndexOf(int ch) - Returns the index within this string of the last occurrence of the specified character.
  • lastIndexOf(int ch, int fromIndex) - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
  • lastIndexOf(String str) - Returns the index within this string of the last occurrence of the specified substring.
  • lastIndexOf(String str, int fromIndex) - Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

Examples of using indexOf() and lastIndexOf()

  1. If you get date as String in the dd/mm/yyyy format and you want to get the first index of char '/'.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.indexOf('/'));
     }
    
    }
    

    Output

    index 2
    
  2. Using the same date string if you want to get the month part of it.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.indexOf('/'));
      String month = date.substring(0, date.indexOf('/'));
      System.out.println("month " + month);
     }
    }
    

    Output

    index 2
    month 12
    
  3. Using the same date string if you want to get the year part then you can use lastIndexOf() method.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.lastIndexOf('/'));
      String year = date.substring(date.lastIndexOf('/') + 1);
      System.out.println("year " + year);
     }
    }
    

    Output

    index 5
    year 2016
    
  4. If you get some string in the format “xx/xx/xx” and you want the middle substring.
    public class StringSearch {
    
     public static void main(String[] args) {
      String path = "home/index/test.html";
      
      String str = path.substring(path.indexOf('/') + 1, path.lastIndexOf('/'));
      System.out.println("str - " + str);
    
     }
    
    }
    

    Output

    str - index
    

contains() method

public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

Example code

public class StringSearch {

 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "example";
  System.out.println("str1 contains str2 " + str1.contains(str2));
 }
}

Output

str1 contains str2 true

Here note that str2 which is passed as an argument in contains() method is a string not CharSequence, so string can be used in place of CharSequence. It is possible because CharSequence is an interface which is implemented by String.

If you want to use contains() method ignoring case then you can convert both strings to upper or lowercase while searching.

As example – In previous program if str2 is changed to “Example” then contains will return false.

public class StringSearch {
 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "Example";
  System.out.println("str1 contains str2 " + str1.contains(str2));
 }
}

Output

str1 contains str2 false

Now, if you want to ignore case then you can change both to lower case.

public class StringSearch {

 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "Example";
  System.out.println("str1 contains str2 " + str1.toLowerCase().contains(str2.toLowerCase()));
 }

}
str1 contains str2 true

It won't change the original strings as strings are immutable and using methods like toLowerCase will create a new string.

That's all for this topic Searching within a String using indexOf(), lastIndexOf() and contains() methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. String charAt() and subString() methods in Java
  4. How to reverse a string in Java
  5. How to add double quotes to a String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Monday, 18 July 2016

String charAt() and substring() methods in Java

If you are trying to get characters and substrings by index with in a String then charAt() and substring() methods respectively can be used.

  • If you are looking for methods to compare string in java using methods like startsWith(), endsWith(), equals() etc.refer String comparison in Java

Using charAt() method

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1.

As example – If you want to get the character at index 3 in a string:

String str = "Example String";
char resChar = str.charAt(3);

Using substring() method

If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -

  • String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1 which means beginIndex is inclusive where as endIndex is exclusive. IndexOutOfBoundsException is thrown if the beginIndex is negative, or endIndex is larger than the length of this String object, or sbeginIndex is larger than endIndex.
  • String substring(int beginIndex) - Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string. IndexOutOfBoundsException is thrown if beginIndex is negative or larger than the length of this String object.

Example Code

public class SubStringDemo {

 public static void main(String[] args) {
  String str = "Example String";
  
  System.out.println("Value - " + str.substring(0, 7));
  
  System.out.println("Value - " + str.substring(8));
  
  System.out.println("Value - " + str.substring(14)); 
 }
}

Output

Value - Example
Value - String
Value - 

0

1

2

3

4

5

6

7

8

9

10

11

12

13

E

x

a

m

p

l

e


S

t

r

i

n

g

String in Java

It’ll be easy to understand with the image, when substring method is called with indexes 0 and 7, returned substring would be “Example” which is index 0-6 as starting index is inclusive and endIndex is not inclusive.

Same way when substring method is called with startIndex as 8 then returned string would be from index 8 till end that’s why String is returned.

If substring() method is called with the length of the string (14 in this case) then empty space is returned. Passing any argument beyond that (more than 14) will result in IndexOutOfBoundsException.

That's all for this topic String charAt() and substring() methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  3. StringBuffer in Java
  4. StringBuilder in Java
  5. Java String interview questions

You may also like -

>>>Go to Java Basics page

Sunday, 17 July 2016

String comparison in Java

In String class there are number of methods provided to compare the Strings or the portion of the strings.

Some of the most used are mentioned here -

startsWith() and endsWith() methods

  • boolean startsWith(String prefix) - Returns true if this string begins with the substring specified as an argument to the method.
  • boolean startsWith(String prefix, int offset) - Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
  • boolean endsWith(String suffix) - Returns true if this string ends with the substring specified as an argument to the method.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  // Should be true
  System.out.println(str.startsWith("This"));
  // test start at index 10, so returns true
  System.out.println(str.startsWith("test", 10));
  
  // returns false
  System.out.println(str.endsWith("test"));
  // returns true
  System.out.println(str.endsWith("test string"));
  // returns true
  System.out.println(str.endsWith("string")); 
 }
}

Output

true
true
false
true
true

equals() and equalsIgnoreCase() methods

  • boolean equals(Object anObject) - Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • boolean equalsIgnoreCase(String anotherString) - Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str = "This is a test string";
  String str1 = new String("This");
  System.out.println("String for comparison -- " + str.substring(0, 4));
  // Should be true
  System.out.println(str.substring(0, 4).equals("This"));
  // will be false, equals is case sensitive
  System.out.println(str.substring(0, 4).equals("this"));
  
  // returns true, case is ignored
  System.out.println(str.substring(0, 4).equalsIgnoreCase("this"));
  // returns true
  System.out.println(str1.equalsIgnoreCase("this"));
 }
}

Output

String for comparison -- This
true
false
true

Here original string is substringed to give a part of the String (“This”). That part is then used for comparison. Even when a new String is created which will have different reference equals or equalsIgnoreCase will return true as content is matched here not reference.

compareTo() and compareToIgnoreCase() methods

  • int compareTo(String anotherString) - Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
  • int compareToIgnoreCase(String str) - Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

In lexicographical comparison if two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both.

If character is different at some position then, compareTo returns the difference of the two character values, As Example if you are comparing run with sun then first char itself is different and difference between them is 1 so in that case -1 is retruned.

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings.

Example code

public class StringComparison {

    public static void main(String[] args) {
        String str1 = "run";
        String str2 = new String("run");
        String str3 = "gun";
        String str4 = "sun";
        
        //equal so returns 0
        System.out.println(str1.compareTo(str2));
        
        //str1 > str3 so returns positive integer
        System.out.println(str1.compareTo(str3));
        // that's how used generally
        if(str1.compareTo(str3) > 0){
            System.out.println("str1 is greater than str3");
        }else{
            System.out.println("str1 is less than str3");
        }
        
        // str1 < str4 so returns negative integer
        System.out.println(str1.compareTo(str4));       
    }
}

Output

0
11
str1 is greater than str3
-1

regionMatches() method

  • boolean regionMatches(int toffset, String other, int ooffset, int len) - Tests whether the specified region of this string matches the specified region of the String argument.
    Region is of length len and begins at the index toffset for this string and ooffset for the other string. This method is case sensitive.
  • boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) – Here first argument indicates whether case should be ignored; if true, case is ignored when comparing characters.

Example code

public class StringComparison {

 public static void main(String[] args) {
  String str1 = "This is an example string";
  String str2 = new String("example");
  String str3 = "Example";
  // returns true
  System.out.println(str1.regionMatches(11, str2, 0, str2.length()));
  // returns false
  System.out.println(str1.regionMatches(11, str3, 0, str3.length()));
  // returns true
  System.out.println(str1.regionMatches(true, 11, str3, 0, str3.length()));
 }

}

Output

true
false
true

Here in the first regionMatches() method the task is to compare “example” is the string str1 with the string str2. Since example starts at the index 11 so that becomes the offset for the first string. Comparison is to be done with the string str2 so that is the second argument. In str2 offset is 0. Here region to be comapred is the complete length of string str2 so str2.length() method is used.

In second case everything is same except the matched string str3 which has the content “Example”. Since method is case sensitive so returns false.

In third case first argument is passed as true so the case is ignored while comparing. That is why true is returned even when str1 and str3 are compared.

Matches() method for string comparison

  • public boolean matches(String regex) - Tells whether or not this string matches the given regular expression.

Example code

Let's say there is a String array with some strings and you want to match and print only those strings which doesn't contain any digit or special character. Then using matches method and providing a regular expression [a-z]+ which will match one or more chars it can be done as follows

.
public class StringComparison {

 public static void main(String[] args) {
  String[] words = {"a123","*67t","test","54&ty"};
  for(String str : words)
  {
      if(str.matches("[a-z]+"))
      {
          System.out.println("matched string - " + str);
      }
  }
 }
}

Ouput

matched string - test

That's all for this topic String comparison in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. How to reverse a string in Java
  3. How to add double quotes to a String
  4. String and thread-safety in Java
  5. Java String interview questions

You may also like -

>>>Go to Java Basics page

Thursday, 14 July 2016

String in Java

In Java String class represents character strings which means; Strings in Java are objects and all strings are instances of the String class. Internally in String class Strings are stored as character array.

String literals and string pool

Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument.

As Example - String str = new String(“abc”);

But the most preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every string literal Java automatically constructs a String object.

As example - String str = “abc”;

String pool

But having String literals bring another dimension to store Strings. If it were only String objects those will go in the heap with their own space. But String literals are treated differently they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.

When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.

String pool in Java
String pool in Java

Let’s see it with an example

In this program two string literals will be created with the same content and then these two string objects are checked for equality. Since we are not comparing the content but the references of two objects so “==” operator will be used.

public class StringDemo {
 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
 }
}

Output

str1 and str2 are same

Now if we create two more strings using new operator and then compare reference they should be different.

public class StringDemo {
 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }

  String str3 = new String("abc");
  String str4 = new String("abc");
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are not same

Here it can be seen that str3 and str4 are having separate reference as those strings are created using new operator.

String intern() method

Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String  object is added to the pool and a reference to this String object is returned.

In the previous Java program if str4 is changed to have interned string then the code will look like –

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  if(str1 == str2){
   System.out.println("str1 and str2 are same");
  }else{
   System.out.println("str1 and str2 are not same");
  }
  String str3 = new String("abc");
  String str4 = new String("abc").intern();
  if(str3 == str4){
   System.out.println("str3 and str4 are same");
  }else{
   System.out.println("str3 and str4 are not same");
  }
  
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str2 are same
str3 and str4 are not same
str1 and str4 are same

It can be seen that str1 and str4 are having the same reference now.

String is immutable

Once you create a String object the content of that string cannot be modified. As we have already seen Java maintains a string pool where references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why string is immutable.

Here being immutable means whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is. If there are no references to the original string it is garbage collected.

As example – Using any of the methods like toLowerCase, toUpperCase, concatenating using concatenate() method or ‘+’ operator will result in creating a new string object.

In the case string is modified frequently consider using StringBuffer or StringBuilder classes which are mutable.

String class is final

As already mentioned above whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content.

Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content.

Another scenario - You extend the String class and override hashCode() and equals() method in such a way that two dissimilar strings return the same hashCode and at the same time equals() return true. Then you can have different strings sharing the same reference in the String pool.

To avoid these kind of scenarios String class is declared as final and it can’t be overridden.

String and thread-safety

Since String objects are immutable thus thread-safe.

Overloaded operator in String

Apart from using concatenate method to concatenate two strings ‘+’ operator can be used to do the same. Actually + and += are two operators which are overloaded for String in Java.

So, if you have two strings
String str1 = "Hi";
String str2 = "Hello";

You can use ‘+’ operator to concatenate them

str1 = str1 + str2;
System.out.println("str1 " + str1);

Or, to make it more concise

str1 += str2;
System.out.println("str1 " + str1);

Comparing Strings using .equals method

In the section about string pool we used == to compare references but what if you want to compare content of two strings even if their references are different. You have to use .equals method in that case.

public class StringDemo {

 public static void main(String[] args) {
  String str1 = "abc";
  String str4 = new String("abc");
  // comparing content
  if(str1.equals(str4)){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
  // comparing references
  if(str1 == str4){
   System.out.println("str1 and str4 are same");
  }else{
   System.out.println("str1 and str4 are not same");
  }
 }
}

Output

str1 and str4 are same
str1 and str4 are not same

Though str1 and str4 have same content but they will have different references as str4 is created using new operator. That is why comparing using "==" prints "str1 and str4 are not same" as references are different but comparing using .equals prints "str1 and str4 are same", as content is compared in that case.

Points to note

  1. Internally in String class Strings are stored as character array.
  2. Strings in Java are objects and all strings are instances of the String class.
  3. Strings can be created by assigning String literal directly to a String reference like String str = “abc”; which may look like assigning to a primitive data type but don't forget Strings are objects.
  4. String literals are treated differently they are stored in a String pool and that is a common pool.
  5. If there are two strings literals having the same content then those string will share the space in the pool.
  6. String is immutable once you create a String object the content of that string cannot be modified.
  7. Since string is immutable whenever you perform any operation on string which alters its content a new string object is created which contains the modified string. Original string is left as it is.
  8. Since String is immutable it is also thread safe.
  9. String class is declared as final and it can’t be overridden.
  10. "+" operator is overloaded for String and it is used for concatenating strings.
  11. Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
  12. For comparing the content of two strings .equals() method is used. If you want to ignore case then use .equalsIgnoreCase().
  13. From Java 7 string can also be used in switch case statement.
  14. join() method is added in String class in Java 8 which makes it very easy to join multiple strings.

That's all for this topic String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String charAt() and subString() methods in Java
  2. String comparison in Java
  3. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  4. String join() method in Java 8
  5. StringBuffer in Java
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

Wednesday, 13 July 2016

How to append to a file in Java

In the post writing file in Java we have already seen how to write to a file in Java but the code given there creates a new file every time and writes the lines in the file. But there are many cases when you actually want to append to the already existing file.

In this post we’ll see how to append to a file in Java. Both FileOutputStream and FileWriter classes have a constructor with a boolean argument, which when passed as true, means appending to a file. Here FileOutPutStream and FileWriter are classes provided by Java to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably.

It is always advisable to use BufferedOutputStream or BufferedWriter because that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.

Appending to a file using BufferedOutputStream

In the code if the file is not existing already it will be created and lines will be written to it. If it already exists then lines will be appended. You can run this program twice to see that.

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileAppend {

 public static void main(String[] args) {
  // Change path for windows
  writeFile("/home/netjs/Documents/text.txt");

 }
 /**
  * 
  * @param fileName
  */
 public static void writeFile(String fileName){
  FileOutputStream fos;
  BufferedOutputStream bos = null;
  try {
   fos = new FileOutputStream(fileName, true);
   bos = new BufferedOutputStream(fos);
   // For windows you may need /r/n for new line
   bos.write("Writing first line\n".getBytes());
   bos.write("Writing second line\n".getBytes());
  }
  catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   try {
    if(bos != null){
     bos.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

}

Appending to a file using BufferedWriter

In the code if the file is not existing already it will be created and lines will be written to it. If it already exists then lines will be appended. You can run this program twice to see that.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileAppendWrite {

 public static void main(String[] args) {
  //Change path for windows
  writeFile("/home/netjs/Documents/test.txt");
 }
 /**
  * 
  * @param fileName
  */
 public static void writeFile(String fileName){
  // Using Java 7 try-with-resources
  try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true))){
   bw.write("Writing first line");
   bw.newLine();
   bw.write("Writing second line");
   bw.newLine();
  }
  catch (FileNotFoundException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Appending using Files class methods

In Java 7 Files class is added which provides write() method to write to a file. There is also a newBufferedWriter method with 2 arguments, added in Java 8 that can be used to write to a file.

Using write() method

There are 2 overloaded versions of write method

  • public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException – Write bytes to a file specified by the path. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
  • public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException - Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.

Example code

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileWrite8 {
 public static void main(String[] args) {
  String content = "This is the line to be added.\nThis is another line.";
  try {
   Files.write(Paths.get("G://test.txt"), content.getBytes(), StandardOpenOption.APPEND);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
}

Here note that String is converted to Byte array and also StandardOpenOption.APPEND is provided as options varargs parameter which means appending to a file.

Using newBufferedWriter method

There are 2 overloaded versions of newBufferedWriter method

  • public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
  • public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.

Example Code

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileWrite8 {
 public static void main(String[] args) {
  Path path = Paths.get("G://test.txt");
  try (BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) {
      writer.write("Hello World");
      writer.newLine();
      writer.write("Hello again");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that StandardOpenOption.APPEND is provided as options varargs which means appending to a file.

That's all for this topic How to append to a file in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to read file from the last line in Java
  2. Reading file in Java using BufferedReader
  3. Zipping files in Java
  4. How to create PDF from XML using Apache FOP
  5. try-with-resources in Java 7

You may also like -

>>>Go to Java Programs page

Monday, 11 July 2016

Writing file in Java

Though Java provides classes like FileOutPutStream and FileWriter to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably.

It is always advisable to use BufferedOutputStream or BufferedWriter because that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.

It is same as reading file using BufferedReader where again the advantage of using buffered I/O streams is that; in case of Buffered input streams data is read from a memory area known as a buffer.

Writing file using BufferedOutputStream

BufferedOutputStream is a wrapper class over the OutputStream class and it adds buffering capability to the output stream.

Here one thing to note is – If your file contains character data, the best approach is to use character streams like BufferedWriter. Byte streams should only be used for the most primitive I/O.

The write method of the BufferedOuputStream takes either a byte array or an int as an argument thus you have to call getBytes() on any String that is passed to the write method.

Java code

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriteDemo {

 public static void main(String[] args) {
  writeFileContent("G:\\test.txt");
 }
 
 /**
  * 
  * @param fileName
  */
 private static void writeFileContent(String fileName){
  BufferedOutputStream bs = null;
  try {
   bs = new BufferedOutputStream(new FileOutputStream(fileName));
   bs.write("Writing one line".getBytes());
   // For windows, only \n for linux
   bs.write("\r\n".getBytes());
   bs.write("Writing second line".getBytes());
   
  } catch (IOException ioExp) {
   // TODO Auto-generated catch block
   ioExp.printStackTrace();
  }finally{
   if(bs != null){
    try {
     bs.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }

}

Writing file using BufferedWriter

Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

Constructors

  • BufferedWriter(Writer out) - Creates a buffered character-output stream that uses a default-sized output buffer.
  • BufferedWriter(Writer out, int sz) - Creates a new buffered character-output stream that uses an output buffer of the given size.

Java code

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWrite {

 public static void main(String[] args) {
  writeFileContent("G:\\test1.txt");

 }
 
 /**
  * 
  * @param fileName
  */
 private static void writeFileContent(String fileName){
  //BufferedWriter bw = null;
  // Using try-with-resources here 
  try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
   //bw = new BufferedWriter(new FileWriter(fileName));
   bw.write("Writing one line");
   bw.newLine();
   bw.write("Writing second line");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

Note that in this program try-with-resources is used to automatically manage resources. It is available from Java 7 and above.

Writing using Files class methods

In Java 7 Files class is added which provides write() method to write to a file. There is also a newBufferedWriter method with 2 arguments, added in Java 8 that can be used to write to a file.

Using write() method

There are 2 overloaded versions of write method

  • public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException – Write bytes to a file specified by the path. Options varargs specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the  CREATE, TRUNCATE_EXISTING, and WRITE options are present.
  • public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException - Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.

Example code

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileWrite8 {
 public static void main(String[] args) {
  String content = "This is the line to be added.\nThis is another line.";
  try {
   Files.write(Paths.get("G://test.txt"), content.getBytes());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
}

Here note that String is converted to Byte array and also there is no option parameter which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

Using newBufferedWriter method

There are 2 overloaded versions of newBufferedWriter method
  • public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. If no options are present then this method works as if the CREATE,  TRUNCATE_EXISTING, and WRITE options are present.
  • public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException - Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.

Example Code

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileWrite8 {
 public static void main(String[] args) {
  Path path = Paths.get("G://test.txt");
  try (BufferedWriter writer = Files.newBufferedWriter(path)) {
      writer.write("Hello World");
      writer.newLine();
      writer.write("Hello again");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Here note that no option parameter is given which means creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

That's all for this topic Writing file in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading delimited file in Java using Scanner
  2. How to read file from the last line in Java
  3. How to find last modified date of a file in Java
  4. Reading file in Java 8
  5. Zipping files in Java
  6. try-with-resources in Java 7

You may also like -

>>>Go to Java Programs page