Array in Java: The Ultimate Guide to Master Arrays in 30 Minutes

Array in Java: The Ultimate Guide to Master Arrays in 30 Minutes

In Java terms, an Array is a bunch of variables called components or elements containing values that have the same type. Arrays are data structures consisting of related data items of the same type.

Once created, Arrays are fixed-length entities where they remain the same length. however, a reference array may be reassigned to a new array of different lengths.

The Java Collections API provides class Arrays, which have a set of utility methods for manipulation of the java array.

Here are some of the key information about Java Arrays.

  • In Java, types are divided into primitive types and reference types. Since Java arrays are objects, they are considered reference types.
  • The elements of an array can be a reference or primitive data type.
  • Arrays in Java are different than they work in other languages like C/C++.
  • Arrays of any type can be created and might have one or more dimensions.
  • In order to refer to a particular element in a java array, the name of the reference to an array and position number of the element is specified and here the array position number is generally called as element index.

The key to solving array-based interview questions or any coding challenge is having a good knowledge of array data structure.

Declaring Creating and Initializing Arrays

As we know, all Objects in Java must be created with keyword new.

For an array, typically the programmer specifies the data type of the array elements and the number of elements as part of array creation syntax that uses keyword new.

Below is the syntax for declaring array variables and creating an array, here size is nothing but specifying array size.

datatype[ ] arrayName = new datatype [size];

Below is an example to declare and create a string array in java of 5 elements.

String[] a = new String[5];

so as per the above array declaration, it consists of total array elements of 5 with string representation.

The above can also be done in two steps

String[] a;   // declaring an array variable

a = new String[5]; // creating and initializing an java string array

Another way of creating an array is by using Array Initializer.

Array Initializer is a comma-separated list of expression which is declared inside braces { }. In this scenario, the length of the specified array is determined by the number of elements declared inside curly braces{}.

Here is the example of intializing type int array,

int x[] ={40,50,60,70}

So if you need to access array elements specifically, then you can retrieve them using the index of type int. i,e. x[2] from above returns the array index value of the 2nd position, which will be 60 in the above case. Note that position in an array always starts with 0.

Note that each element array receives a default value as null for reference types, false for boolean elements, and zero for numeric primitive type arrays.

Dimensional Arrays

Arrays can be categorized into Single Dimensional Arrays or One Dimensional array (1D array) and Multi Dimensional Arrays(2D array or more dimensional arrays).

Single Dimensional Array or One Dimensional Array

The typical declaration of a single-dimensional array is

type[] variableName;

So type declares the data type of the array and the variable name is used to identify the respective array.

int[] countArray;

In order to create and performing array initialization of a single-dimensional array, here is the syntax.

variableName = new type[size];

i,e, if you want to declare and create a single-dimensional at one go, here, is the way.

int[] countArray  = new int[5];

Combining all together, here is the java program that demonstrates a single-dimensional created array.

public class SingleDimensionalArray {

	public static void main(String[] args) {

		int[] countArray = new int[5];
		countArray[0] = 10;
		countArray[1] = 20;
		countArray[2] = 30;
		countArray[3] = 40;
		countArray[4] = 50;
		System.out.println("Count of Array Index 3 is: " + countArray[3]);
	}
}



Output:
Count of Array Index 3 is: 40

Multi Dimensional Arrays

Multi-Dimensional Arrays are nothing but arrays of arrays.

A multi-dimensional array is also referred as ragged array or jagged array.

In order to declare a multi-dimensional array, you need to specify an additional array index using another pair of [].

The typical declaration of the multidimensional array is

int[][] multiCountArray;

i,e if you want to declare and create a dimensional on a single go, here is the way.

int[][] multiCountArray  = new int[3][4];

Here is the java program that demonstrates a multi dimensional array.

public class MultiDimensionalArray {

	public static void main(String[] args) {
		int[][] multiCountArray  = new int[3][4];
		int a, b, c = 0;
		
		for(a=0; a < 3; a++)
			for(b=0; b < 4; b++) {
				multiCountArray[a][b] = c;
				c++;
			}
		
		for(a=0; a < 3; a++) {
			for(b=0; b < 4; b++) 
			System.out.println(multiCountArray[a][b] + " ");	
			System.out.println();
			}		
		
	}

}

Output:
0 1 2 3
4 5 6 7
8 9 10 11

Passing Arrays to Methods

In order to pass an argument of array type, specify the name of the array without [].

for example, array zipCodes is declared as below

int[] zipCodes = new int[5];

if the method and method signature is declared as below

public void retrieveValues(int[] codes);

then passing an array to the method will be as follows

retrieveValues(zipCodes);

As we know in Java, an array object aware of its own length and can process arrays internally(i.e. by the array length field). Hence, when we pass an array object to a method, it is not required to pass the length of the array as an argument.

Accessing Array Elements

In order to access an element of an array, we can retrieve using the index number.

Following is the syntax to retrieve an element of an array.

array[index];

Here is the example of accessing array elements using the index of an array.

public class RetrieveElements {

	public static void main(String[] args) {

		String[] countries = { "USA", "AUSTRALIA", "NEWZEALAND", "INDIA", "JAPAN" };

		System.out.println("First Element: " + countries[0]);
		System.out.println("Second Element: " + countries[1]);
		System.out.println("Third Element: " + countries[2]);
		System.out.println("Fourth Element: " + countries[3]);
		System.out.println("Fifth Element: " + countries[4]);

	}

}

Output:
First Element: USA
Second Element: AUSTRALIA
Third Element: NEWZEALAND
Fourth Element: INDIA
Fifth Element: JAPAN

Sorting Arrays with the Array API

Sorting the data into specific order such as ascending or descending order is one of the critical parts of programming.

Arrays class provides method Arrays.sort() which can be used to sort the arrays, let’s see some sorted array examples.

Sorting Arrays in Ascending Order

Below is the java program which sorts Integer array elements in ascending order.

import java.util.Arrays;
import java.util.Collections;

public class SortArray {

	public static void main(String[] args) {
		
		Integer[] scores = {60,50,40,80,90};
		Arrays.sort(scores);
		System.out.println("Sorting in Ascending Order: "+Arrays.toString(scores));
	}

}

Output:
Sorting in Ascending Order: [40, 50, 60, 80, 90]

Sorting Arrays in Descending Order

Below is the java program which sorts Integer array elements in descending order.

import java.util.Arrays;
import java.util.Collections;

public class SortArray {

	public static void main(String[] args) {
		
		Integer[] scores = {60,50,40,80,90};
		Arrays.sort(scores,Collections.reverseOrder());
	    System.out.println("Sorting in Descending Order: "+Arrays.toString(scores));
	}

}

Output:
Sorting in Descending Order: [90, 80, 60, 50, 40]

Looping Array Elements

We can iterate through each element of the array using loops in Java.

Here is the example of looping array elements using for loop.

public class ForLoopArray {

	public static void main(String[] args) {

		int[] count = { 6, 8, 10 };

		for (int i = 0; i < count.length; i++) {
			System.out.println(count[i]);
		}

	}

}

Output:
6
8
10

We can also loop through array elements using for each loop, here is the example

public class ForEachArray {

	public static void main(String[] args) {

		int[] count = { 6, 8, 10 };

		for (int i : count) {
			System.out.println(i);
		}

	}

}

Output:
6
8
10

Searching Arrays

In order to determine whether an array contains a value that matches a specific key-value, a search will be performed which is nothing but locating a key value in an array.

we have search techniques like a linear search and binary search for searching and matching array values.

Linear Search of an Array

we use linear search to search a specific element from numerous array elements.

Typically linear search is the best fit for small arrays or for unsorted arrays.

The linear search algorithm works in the following way.

  1. Traversing an array.
  2. Match the specific element with respective array element.
  3. Match the specific element with respective array element.
  4. If a matching element is found, then it will return the index position of the array element.
  5. if a matching element is not found, then it will return -1.

Here is the example program for Linear Search.

public class LinearSearch {

	public static void main(String[] args) {
		
		 int[] num= {60,50,40,80,90};  
		 int searchKey = 80;
		for(int i=0;i < num.length;i++){    
	            if(num[i] == searchKey){    
	            	System.out.println("Array Index Position is: "+i);  
	            }    
	        }    
	}

}


Output:
Array Index Position is: 3

Binary Search of an Array

For searching through larger sorted arrays, binary search is apt and provides high-speed search results.

The binary search algorithm works in the following way.

  1. Eliminates half of the elements in the given array being searched after having each comparison.
  2. It identifies the middle array element and compares it with the key used to search.
  3. If a matching element is found, then it will return the index position of the array element
  4. if a matching element is not found and if the search key is less than the middle array element, the first half of the array will be searched; else, the second half of the array will be searched.
  5. The search continues until the search key is equal to the middle element of a subarray or till the subarray consists of one element that is not equal to the search key.

Here is the example program for Binary Search.

public class BinarySearch {

	public static void main(String[] args) {
		
		 int[] num= {10,20,30,40,50};  
		 int searchKey = 40;
		 int first = 0 ; 
		 int last=num.length-1;  
		 
		 int midArray = (first + last)/2 ; 
		   while( first <= last ){  
		      if ( num[midArray] < searchKey ){  
		        first = midArray + 1;     
		      }else if (  num[midArray] == searchKey ){  
		        System.out.println("Array Index Position is: " + midArray);  
		        break;  
		      }else{  
		         last = midArray - 1;  
		      }  
		      midArray = (first + last)/2;  
		   }  
		   if ( first > last ){  
		      System.out.println("Array Element is not Found");  
		   }  
		 }  
	}

Output:
Array Index Position is: 3

we can also utilize Arrays.binarySearch() method to perform a binary search in an array. Here is the example

import java.util.Arrays;

public class BinarySearchArray {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] num = { 10, 20, 30, 40, 50 };
		int searchKey = 40;
		int resultPostion = Arrays.binarySearch(num, searchKey);
		System.out.println("Array Index Position is: " + resultPostion);
	}
}

Output:
Array Index Position is: 3

In Java terms, an Array is a bunch of variables called components or elements containing values that have the same type. Arrays are data structures consisting of related data items of the same type.

Once created, Arrays are fixed-length entities where they remain the same length. however, a reference array may be reassigned to a new array of different lengths.

The Java Collections API provides class Arrays, which have a set of utility methods for manipulation of the java array.

Here are some of the key information about Java Arrays.

  • In Java, types are divided into primitive types and reference types. Since Java arrays are objects, they are considered reference types.
  • The elements of an array can be a reference or primitive data type.
  • Arrays in Java are different than they work in other languages like C/C++.
  • Arrays of any type can be created and might have one or more dimensions.
  • In order to refer to a particular element in a java array, the name of the reference to an array and position number of the element is specified and here the array position number is generally called as element index.

The key to solving array-based interview questions or any coding challenge is having a good knowledge of array data structure.

Dynamic Array in Java

we know that the array contains is a fixed-size entity, which means we have to specify the number of elements while array declaration.

so the challenge is if we need to insert an element but there is no more space available to accommodate the new element? Here comes the savior called Dynamic Array which expands the array size dynamically.

Java Dynamic Array grows automatically when there is no enough space to accommodate the insertion of the new element.

In Java, dynamic array is nothing but an ArrayList.

Dynamic Array Features

  • Add Array Element.
  • Delete Array Element.
  • Resizing an Array.

Advantages of Dynamics Array

  • Cache Friendly.
  • Dynamic Variable Size.
  • Quick Looping.

Disadvantages of Dynamics Array

  • Inserts and Deletes taking more time.
  • Slow Appends.

Array vs ArrayList

Here are the notable difference between an Array and ArrayList.

  • Array is having a fixed length, where as in Arraylist the length will be dynamic.
  • Array length cannot be changed once it created, where as in Arraylist the length can be changed.
  • Array can store both primitive types and Objects, where as Arraylist can only store Objects but not primitive types.
  • To access the elements in an ArrayList, we use the .get method, and to update elements in an ArrayList, we use the .set method. If we want to add an element, we can use the .add element.

Array of Objects

Array of Objects, the name itself mentions that it is meant for storing an array of objects.

Take a note that, the reference of the object will be stored not the Object itself.

Creating Array of Objects

Array of Objects is created using the Objects class and here is the syntax

Class_Name[ ] arrayReference;

For example, if you have a class Employee then we can create an array of Employee objects as below:

Employee[ ] employeeObjects;

Instantiate an Array of Objects

In order to instantiate the array of objects in java, here is the syntax.

Class_Name object[ ]= new Class_Name[ArrayLength];

For example, if you have a class Employee, and want to declare and instantiate an array of Employee objects then it can be implemented as:

Employee[ ] employeeObjects = new Employee[4];

Now let’s see an example program for an array of objects in java as below.


public class Employee {

	private int id;
	private String name;
	private String dept;

	Employee(int id, String name, String dept) {
		this.id = id;
		this.name = name;
		this.dept = dept;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", dept=" + dept + "]";
	}

}


public class ArrayObjects {

	public static void main(String[] args) {
		
		Employee[] employeeObjects = new Employee[3];
		employeeObjects[0] = new Employee(1, "Sam", "CSE");
		employeeObjects[1] = new Employee(2, "John", "ECE");
		employeeObjects[2] = new Employee(3, "Mike", "IT");

		for (Employee i : employeeObjects) {
			System.out.println("Array Data is : " + i);
		}
	}

}


Output:
Array Data is : Employee [id=1, name=Sam, dept=CSE]
Array Data is : Employee [id=2, name=John, dept=ECE]
Array Data is : Employee [id=3, name=Mike, dept=IT]

Concatenate Arrays

In order to concatenate arrays in java, we can achieve this in numerous ways.

Let’s see some sample implementation’s below for concatenating arrays.

Here is the example using ArrayUtils.addAll(T[], T...) method from Apache Commons Lang library.

import org.apache.commons.lang3.ArrayUtils;

public class ConcatenateArrays {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = ArrayUtils.addAll(first, second);

		System.out.println("Concatenate Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
Concatenate Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

Also using Java 8 Stream, we can concatenate arrays.

Here is the example program which uses Java Stream.

import java.util.Arrays;
import java.util.stream.Stream;

public class ConcatenateStream {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);

		System.out.println("Stream Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
Stream Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

We can use flatMap which is another Java 8 method that can be used to concatenate arrays.

Here is the example which uses Java flatMap.

import java.util.stream.Stream;

public class ConcatenateFlatMap {

	public static void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		String[] result = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);

		System.out.println("FlatMap Results are : " + result.length);

		for (String x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}

Output:
FlatMap Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f

Using Generics, we can achieve concatenation of arrays by leveraging reflection concept.

As you might know, reflection allows methods to access array and array component types, creating new arrays, retrieving, and setting array component values.

Here is the example which uses Generics implementation.

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.stream.Stream;

public class ConcatenateGenerics {

	public static  void main(String[] args) {

		String[] first = { "a", "b", "c" };
		String[] second = { "d", "e", "f" };

		T[] result = Stream.concat(Arrays.stream(first), Arrays.stream(second))
				.toArray(size -> (T[]) Array.newInstance(first.getClass().getComponentType(), size));

		System.out.println("Generic Results are : " + result.length);

		for (T x : result) {
			System.out.println("Array Element is : " + x);
		}
	}

}


Output:
Generic Results are : 6
Array Element is : a
Array Element is : b
Array Element is : c
Array Element is : d
Array Element is : e
Array Element is : f
Class StringBuffer in Java – A Definitive Guide

Class StringBuffer in Java – A Definitive Guide

Class StringBuffer in Java: StringBuffer is a associate class of String which provides majority of functionality of strings.

As you know String for its immutable character sequences and fixed-length.

In contrast, StringBuffer speaks for its growable and writeable character sequences.

StringBuffer might have substrings and characters appended at the end or inserted in the middle.

Moreover StringBuffer will grow automatically for additions and often it has more characters preallocated than the actual need.

Both String and StringBuffer used more often in Java, but many developers most deal only with String and let Java to manipulate StringBuffer’s in background by using the overloaded + operator.

Introduction to StringBuffer

String objects are constant strings, whereas StringBuffer objects are modifiable strings.

Java distinguishes constant strings from modifiable strings for optimization purposes.

In particular, Java performs specific optimizations including String objects (like sharing one String object across multiple references) because it knows there will be no change in objects.

when given the choice between using a String object to represent a string versus a StringBuffer object to represent that string, always prefer a String object if the string will not change; this improves performance for sure.

StringBuffer Constructors

Class StringBuffer provides four types of constuctors through which it will be initialized.

Default Constructor:

StringBuffer buffer = new StringBuffer()

Above constructor is the default StringBuffer constuctor to create a StringBuffer with no characters in it and an intitial capacity of 16 characters (default for a StringBuffer).

Integer Argument Constructor:

Syntax:

StringBuffer buffer = new StringBuffer(int size);

Example:

StringBuffer buffer = new StringBuffer(20);

Above type of constuctor takes an integer argument to create a StringBuffer with no characters in it and the intitial capacity specified by the integer argument.

String Argument Constructor:

Syntax:

StringBuffer buffer = new StringBuffer(String str);

Example:

StringBuffer buffer = new StringBuffer(“TracedDynamics”);

Above variation of constructor takes a String argument (i.e, in this example case a string literal) to create a StringBuffer containing the characters in the String argument.

The inital capacity is the number of charcters in the string argument plus 16.

CharacterSequence Argument Constructor:

Syntax:

StringBuffer buffer = new StringBuffer(CharSequence chars);

Above constructor creates an object that contains the character sequence contained in chars.

You May Also Like,

StringBuffer Methods

Following are the different methods provided by the StringBuffer.

length()

The current length of a StringBuffer can be found via using the length() method.

public class Main {
  public static void main(String[] args) {

   try {
	StringBuffer buffer = new StringBuffer("TraceDynamics");
	System.out.println("StringBuffer Length: "+buffer.length());
  } catch (Exception e) {
	 e.printStackTrace();
  }
 }
}

Output:
StringBuffer Length: 13

capacity()

This method provides the total allocated capacity through the capacity() method.

public class Main {
  public static void main(String[] args) {

  try {
   StringBuffer buffer = new StringBuffer("TraceDynamics");
   System.out.println("StringBuffer Capacity: "+buffer.capacity());
  } catch (Exception e) {
	e.printStackTrace();
  }
 }
}
Output:
StringBuffer Capacity: 29

So whats the logic behind capacity output value of 29 in above program ? Since StringBuffer by default allocates space for 16 additional characters, total length of input string plus 16 will be the capacity.

In this the input string length is 13 and StringBuffer default allcoation is 16, so 13+16 = 29 is the capacity.

ensureCapacity()

If you are looking to preallocate space for a specific number of characters after a StringBuffer has been constructed, we can use ensureCapacity() method to set the size of the buffer.

This way of implementation is useful if you know in prior that you will be appending a huge number of small strings to a StringBuffer.

Syntax: ensureCapacity(int capacity)

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer();
	 System.out.println("Before Setting ensureCapacity : " +buffer.capacity());
	 buffer.ensureCapacity(20);
	 System.out.println("After Setting ensureCapacity : " +buffer.capacity());
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
Before Setting ensureCapacity : 16
After Setting ensureCapacity : 34

setLength()

Using setLength() method, we can set the length of the string within a StringBuffer object.

Syntax: setLength(int length)

Note that, the length value should be non negative.

When you increase the size of a string, the null characters are added to the end. If you call setLength() with a value less than the current valu returned by length() method, then the characters stored above the new length will be lost.

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("TraceDynamics");
	 System.out.println("Before Setting Length : " +buffer.length());
	 buffer.setLength(20);
	 System.out.println("After Setting Length : " +buffer.length());
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
Before Setting ensureCapacity : 16
After Setting ensureCapacity : 34

charAt()

Using charAt() method, we can obtain the value of a single character from a StringBuffer.

Syntax: charAt(int index).

Note that, the index value should be non negative.

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("TraceDynamics");
	 System.out.println("Char at: " +buffer.charAt(2));
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
Char at: a

setCharAt()

Using setCharAt() method, we can set the value of a character from a StringBuffer.

Syntax: setCharAt(int index, char ch)

Note that, the index value should be non negative.

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("TraceDynamics");
	 buffer.setCharAt(2, '$');
	 System.out.println("Set Char at: "+buffer);
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
Set Char at: Tr$ceDynamics

getChars()

Using getChars()< method, we can copy a substring of a StringBuffer into array. Syntax: getChars(int startIndex, int endIndex, char target[], int targetStartIndex)

Here the startIndex specifies the index of the beginning of the substring, and endIndex specifies a index that is one past the end of desired substring.

This means that the substring contains the characters from startIndex through endIndex-1. The array that wil receive the characters is specified by target.

The index within target at which the substring will be copied is passed in targetStartIndex.

We have to assure that the target[] is big enough to hold the number of characters in the specified substring.

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("Trace Dynamics");
	 char[] array = new char[] { 'w', 'e', 'l', 'c', 'o', 'm', 'e' };
	 buffer.getChars(6, 9, array, 3);
	 System.out.println(array);
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
welDyne

append()

Basically the method append() concatenates the representation string of any other type of data to the end of the triggering StringBuffer object.

Inorder to obtain string representation for each parameter, String.valueOf() method is called.

Also append() method has numerous overload versions, here are they.

  • append(String str)
  • append(boolean b)
  • append(int i)
  • append(Object obj)
  • append(char c)
  • append(char[] str)
  • append(CharSequence s)
  • append(float f)
  • append(double d)
  • append(long lng)
  • append(StringBuffer sb)
  • append(CharSequence s, int start, int end)
  • append(char[] str, int offset, int len)
public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("Trace Dynamics");
	 System.out.println("before inserting: " + buffer);
	 buffer.insert(14, " Welcomes You");
	 System.out.println("After inserting: " + buffer);
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
before appending: TraceDynamics
After appending: TraceDynamics Welcomes You

insert()

The method insert() inserts one string into another.

This method is overloaded to accept the values of all the primitive types, Objects, Strings and CharSequences.

Likewise append() method, insert() also String.valueOf() to obtain the string representation of the value it is called with.

String.valueOf() method called to obtain a string representation for each parameter.

Here are the different forms of insert() methods.

  • insert(int index, String str)
  • insert(int index, char ch)
  • insert(int index, Object obj)

In above, index specifies at which point the string will be inserted into the invoking StringBuffer object.

public class Main {
	public static void main(String[] args) {

	try {
	 StringBuffer buffer = new StringBuffer("Trace Dynamics");
	 System.out.println("before inserting: " + buffer);
	 buffer.insert(14, " Welcomes You");
	 System.out.println("After inserting: " + buffer);
   } catch (Exception e) {
	  e.printStackTrace();
   }
 }
}

Output:
before inserting: Trace Dynamics
After inserting: Trace Dynamics Welcomes You

reverse()

The method reverse() is used to reverse the characters with in a StringBuffer object.

Syntax:

  • reverse()
  • public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 System.out.println("StringBuffer Reverse: " + buffer.reverse());
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer Reverse: scimanyDecarT
    

    delete()

    The method delete() is used to delete the characters with in a StringBuffer object.

    Syntax:

    • delete(int indexStart, String indexEnd)
    public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 System.out.println("StringBuffer Delete: " + buffer.delete(0,5));
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer Delete: Dynamics
    

    deleteCharAt()

    The method delete() is used to delete the characters at a specified index.

    Syntax:

    • deleteCharAt(int index)
    public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 System.out.println("StringBuffer DeletCharAt: " + buffer.deleteCharAt(0));
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer Delete: Dynamics
    

    replace()

    The method replace() is used to replace the characters at a specified index.

    Syntax:

    • replace(int indexStart, String indexEnd, String str)
    public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 System.out.println("StringBuffer Delete: " + buffer.replace(0,5,"Test"));
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer Delete: TestDynamics
    

    substring()

    The method substring() is used to retrieve a portion of a string at a specified index.

    Syntax:

    • substring(int indexStart)
    • substring(int indexStart, String indexEnd)

    The second syntax above returns the substring which starts at indexStart and process through indexEnd-1.

    Here is the code example which utilizes second syntax above.

    public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 System.out.println("StringBuffer substring: " + buffer.substring(0,5));
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer substring: Trace
    
    

    Why StringBuffer is Mutable?

    As per builtin behaviour String class in Java is Immutable, which means whenever we declare a String variable we cannot modify the data or perform any manipulations.

    For some specific instances we might have to modify the data of a String, for such scenarios we can leverage StringBuffer which is mutable(modifiable) by nature.

    • substring(int indexStart)
    • substring(int indexStart, String indexEnd)

    Convert StringBuffer to String

    Converting StringBuffer to String is a straight forward task, we just have to leverage toString() method.

    Applying toString() method on StringBuffer object will serve the purpose.

    Here is the example.

    public class Main {
    	public static void main(String[] args) {
    
    	try {
    	 StringBuffer buffer = new StringBuffer("TraceDynamics");
    	 String output = buffer.toString();
    	 System.out.println("StringBuffer to String: " +output);
       } catch (Exception e) {
    	  e.printStackTrace();
       }
     }
    }
    
    Output:
    StringBuffer to String: TraceDynamics
    
    

    Note:
    In JDK 1.5 version, Java introduced StringBuilder for handling string capabilities.

    This is very much similar to StringBuffer apart from one one important difference, StringBuilder is not synchorized(not thread safe).

    Faster Performance is great advantage of StringBuilder.

    To conclude this java tutorial, we covered various constructors, methods of class StringBuffer in Java.

    Convert Java File to InputStream | Tracedynamics

    Convert Java File to InputStream | Tracedynamics

    In this article, we have discussed how to convert a java file to an InputStream. There are 5 very easy ways to convert a java file to InputStream by Using Traditional java IO Package, using Java 8, Using Apache Common IO Library, Using Guava Library. Let’s look at some of the Java InputStream examples in this tutorial. Let’s convert a File to an InputStream in numerous ways of implementation. Before starting to convert a file to InputStream, let’s know what is an InputStream and

    What is InputStream?

    InputStream is an abstract class of Java API.

    Its a superclass of all classes defining an input stream of bytes.

    InputStream extends Object and its implemented Interfaces are Closeable, AutoCloseable.

    InputStream Subclasses are AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream.

    These are particularly helpful for reading and write operations on file streams or input files.

    Again let’s go in detail about first, second, third ways of converting File to InputStream.

    Convert using Traditional Java IO Package

    Our first method to convert Java File To Inputstream.

    In the first place, let’s leverage the Java IO package to convert a File format to different InputStream’s.

    Of course under the IO package, the first one we use is FileInputStream.

    Following Java code read a file from the file path/folder directory location.

    Furthermore it converts into InputStream using method FileInputStream().

    public static void main(String[] args) throws IOException {
    	try {
    		File file = new File("src/resources/hello.txt");
    		InputStream is = new FileInputStream(file);
    		System.out.println("InputStream is: " + is);
            is.close();
    	} catch (Exception e) {
    			e.printStackTrace();
    	}
    }
    
    Output:
    InputStream is: [email protected]
    

    As per output, the program reads a text file and converts a File to an InputStream.

    of course, next is by using SequenceInputStream.

    Java program concatenates the input data stream of two files to a single InputStream.

    public static void main(String[] args) throws IOException {
    try {
    	File file = new File("src/resources/Hello.txt");
    	File file2 = new File("src/resources/Test.txt");
    	InputStream firstIS = new FileInputStream(file);
    	InputStream secondIS = new FileInputStream(file2);
    	InputStream is = new SequenceInputStream(firstIS, secondIS);
    	System.out.println("SequenceInputStream is: "+is);
        firstIS.close();
    	secondIS.close();
    	is.close();
        } catch (Exception e) {
    	  e.printStackTrace();
    	}
    }
    
    Output:
    SequenceInputStream is: [email protected]
    

    Not to mention, finally using DataInputStream.

    This will read primitive data stream or binary data from a file.

    public static void main(String[] args) throws IOException {
    try {
    	 File file = new File("src/resources/Hello.txt");
     	 InputStream is = new DataInputStream(new FileInputStream(file));
      	 System.out.println("DataInputStream is: "+is);	
         is.close();
    	 } catch (Exception e) {
    	  e.printStackTrace();
    	}
    }
    
    Output:
    DataInputStream is: [email protected]
    

    These just for you,

    File to InputStream using Java 8

    Using Java 8 method to convert Java File to Inputstream.

    Using Java 8, we can save the input stream to file as below

    public static void main(String[] args) throws IOException {
    		String TARGET_PATH = "C:\\test\\wikipedia.txt";
    	try {
    		URI uri = URI.create("https://www.wikipedia.com/");
    		InputStream inputStream = uri.toURL().openStream();
    		Files.copy(inputStream, Paths.get(TARGET_PATH),StandardCopyOption.REPLACE_EXISTING);
    		System.out.println("File copied to location: " + TARGET_PATH);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    
    }
    
    Output:
    File copied to location: C:\test\wikipedia.txt
    

    By using Apache Commons IO Library

    Using Apache Commons IO Library API, we can convert java File to an InputStream as below.

    public static void main(String[] args) throws IOException {
    try {
    	File file = new File("src/resources/Hello.txt");
    	InputStream is = FileUtils.openInputStream(file);
    	System.out.println("Apache Commons InputStream is: "+is);		
    	} catch (Exception e) {
    	  e.printStackTrace();
    	}
    }
    
    Output:
    Apache Commons InputStream is: [email protected]
    

    Apache Commons IO library can be download from here.

    Java File to InputStream using Guava Library

    It is my favorite, using Guava Library converts to inputstream in java.

    As we know Guava is an open-source Java API library from Google.

    Using Guava we can convert File to an InputStream with below source code.

    public static void main(String[] args) throws IOException {
    try {
    	File file = new File("src/resources/Hello.txt");
    	InputStream is = Files.asByteSource(file).openStream();
    	System.out.println("Guava Google InputStream is: "+is);		
    	} catch (Exception e) {
    	  e.printStackTrace();
    	}
    }
    
    Output:
    Guava Google InputStream is: [email protected]
    

    Read a File using InputStream in Java

    file to input stream in java

    java file to inputstream

    There are numerous ways to read the contents of a file using Java InputStream.

    Using BufferReader readLine() method

    Read streams of raw bytes using Java InputStream and decode them into characters using charset.

    Here readLine() method read bytes from the file and convert into characters.

    This method will read the InputStream line by line in Java.

    public static void main(String[] args) throws IOException {
    
    	File file = new File("src/resources/hello.txt");
    	String result = null;
    	String line;	
    	try {
    	StringBuilder sb = new StringBuilder();
    	InputStream in = new FileInputStream(file);
    	BufferedReader br = new BufferedReader(new InputStreamReader(in));
    	while ((line = br.readLine()) != null) {
    		sb.append(line + System.lineSeparator());
    	}
    		result = sb.toString();	
    		br.close();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	System.out.println(result);
    	}
    }
    
    Output:
    Welcome
    

    As the file “hello.txt” contains Welcome, it prints the same in the output above.

    With Apache Commons IO package

    Last but not the least, want to know how to convert file to an inputstream using Commons IO package?

    We can leverage the IOUtils class of Apache Commons IO library which will accept an InputStream

    and displays the contents as a string using the specified content type.

    The imports package for IOUtils is .apache.commons.io.IOUtils

    public static void main(String[] args) throws IOException {
    
    		File file = new File("src/resources/hello.txt");
    		String results;
    		try (InputStream in = new FileInputStream(file)) {
    			results = IOUtils.toString(in, StandardCharsets.UTF_8);
    			System.out.println(results);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    Output:
    Welcome
    

    Using InputStream read() method

    Last but not the list in file to inputstream,

    Here read() method reads a byte data from the InputStream.

    public static void main(String[] args) throws IOException {
    
    		File file = new File("src/resources/hello.txt");
    		int result;
    		try (InputStream in = new FileInputStream(file)) {
    			while ((result = in.read()) != -1) {
    				System.out.print((char)result);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    Output:
    Welcome
    

    Tip:

    Likewise, if you are looking to read a zip file, then use ZipInputStream to achieve it.

    For reading large files like large CSV files, we can use Stream API from Java 8.

    Also for parsing a CSV file, we can use Apache commons CSV library and BufferedReader.

    To conclude this java tutorial, we covered various examples using different packages/libraries.

    Interview FAQ

     

    How to read InputStream line by line in Java?

    We can use BufferedReader with FileInputStreamReader to read InputStream line by line.

    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(inputStream));
    while(bufferReader.ready()) {
    String line = bufferReader.readLine();
    }

    What is ByteArrayInputStream?

    ByteArrayInputStream will read byte array as input stream.

    This class consists an internal buffer which uses to read the byte array as a stream.

    Also the ByteArrayInputStream buffer grows according to the data.

    What is InputStreamReader?

    InputStreamReader class translate bytes of an InputStream as text instead of numeric data.

    Also we can set and get the character encoding using InputStreamReader.

    You can set the character encoding using method Charset.forName(“UTF-8”).

    InputStream inputStream = new FileInputStream(“sample.txt”);
    InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName(“UTF-8”));

    Also you can get the character encoding using method getEncoding().

    FileInputStream fileStream = new FileInputStream(“sample.txt”);
    InputStreamReader reader = new InputStreamReader(fileStream);
    String encoding = reader.getEncoding();

    Best and Different Approaches About How To Sort ArrayList In Java

    Best and Different Approaches About How To Sort ArrayList In Java

    How to sort ArrayList in Java: Find the best solution for this in this article.

    Let’s explore different approaches for sorting elements of an ArrayList in this post.

    ArrayList is one of the widely used collection classes of the Collection Framework in Java.

    ArrayList is nothing but a List implementation that implements a dynamic array to store the elements internally.

    Thus, an ArrayList will dynamically grow and reduce as long as you add and remove elements.

    How To Sort ArrayList in Java

    ArrayList Is Widely used classes of the framework in Java. Let’s check out the best approaches to sort ArrayList in Java in every order Ascending order, Descending order, integer objects, and more. To sort the Arraylist in Java you need to call to collection.sort() methods.

    You may like,

    Whether Number or String is Palindrome in Java.

    Sorting ArrayList of String Objects

    Assume an ArrayList that holds State names as String Objects.

    In order to sort the ArrayList, we need to call a method Collections.sort().

    Here we need to pass the ArrayList object as an argument to the Collections.sort() method.

    Note that, by default, this method returns the sorted list of String in ascending order alphabetically.

    If You have any doubts about How to sort ArrayList in java, feel free to comment on us, we will definitely answer your doubt.

    Sort String in Ascending Order

    Let’s write the code to sort the ArrayList of String in Ascending order.

    Let’s Initialize the ArrayList object in the constructor and add the states to the ArrayList.

    Finally pass the Arraylist object to Collections.sort() method.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Main
    {
     public static void main(String[] args) {
    
      try {
    	  ArrayList stateList = new ArrayList<>();         
    	  stateList.add("Florida");         
    	  stateList.add("Illinois");         
    	  stateList.add("Alabama");         
    	  stateList.add("Texas");
    	  Collections.sort(stateList);
    	  System.out.println("Sorted Results : "+stateList);
    	} catch (Exception e) {
    	   e.printStackTrace();
    	}
    }
    }
    
    Output:
    Sorted Results : [Alabama, Florida, Illinois, Texas]
    

    Here the output above is in List of String format, you can also convert the List to String in Java as per the need.

    Sort String in Descending Order

    Let’s write the code to sort the ArrayList of String in Descending order.

    Apart from passing the ArrayList object, here we also need to pass a Comparator argument.

    So we will pass Collections.reverseOrder() as comparator in below code.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Main
    {
     public static void main(String[] args) {
    
      try {
    	  ArrayList stateList = new ArrayList<>();         
    	  stateList.add("Florida");         
    	  stateList.add("Illinois");         
    	  stateList.add("Alabama");         
    	  stateList.add("Texas");
    	  Collections.sort(stateList,Collections.reverseOrder());
    	  System.out.println("Sorted Results : "+stateList);
    	} catch (Exception e) {
    	   e.printStackTrace();
    	}
    }
    }
    
    Output:
    Sorted Results : [Texas, Illinois, Florida, Alabama]
    

    Sorting ArrayList of Integer Objects

    sort arraylist in java

    Sort ArrayList in Java

    it’s one of more how to sort ArrayList in java by sorting Arraylist of integer objects.

    Assume an ArrayList that holds numbers as Integer Objects.

    In order to sort the ArrayList, we need to call a method Collections.sort().

    Here we need to pass the ArrayList object as an argument to the Collections.sort() method.

    Note that, by default, this method returns the sorted list of Integer in ascending order.

    Sort Integer in Ascending Order

    Let’s write the code to sort the ArrayList of Integer in Ascending order.

    Let’s Initialize the ArrayList object in the constructor and add the numbers to the ArrayList.

    Finally pass the Arraylist object to Collections.sort() method.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Main
    {
     public static void main(String[] args) {
    
      try {
    	 ArrayList numberList = new ArrayList<>();         
    	 numberList.add(7);         
    	 numberList.add(5);         
    	 numberList.add(15);         
    	 numberList.add(3);
    	 Collections.sort(numberList);
    	 System.out.println("Sorted Results : "+numberList);
       } catch (Exception e) {
    	  e.printStackTrace();
       }
    }
    }
    
    Output:
    Sorted Results : [3, 5, 7, 15]
    

    Sort Integer in Descending Order

    Our last but not the least on how to sort ArrayList in java by the integer descending order.

    Let’s write the code to sort the ArrayList of String in Descending order.

    Apart from passing the ArrayList object, here we also need to pass a Comparator argument.

    So we will pass Collections.reverseOrder() as comparator in below code.

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Main
    {
     public static void main(String[] args) {
    
      try {
    	  ArrayList numberList = new ArrayList<>();         
    	  numberList.add(7);         
    	  numberList.add(5);         
    	  numberList.add(15);         
    	  numberList.add(3);
    	  Collections.sort(numberList,Collections.reverseOrder());
    	  System.out.println("Sorted Results : "+numberList);
        } catch (Exception e) {
    	   e.printStackTrace();
    	}
    }
    }
    
    Output:
    Sorted Results : [15, 7, 5, 3]
    

    Conclusion

    Above are some of the best approaches w.r.t how to sort ArrayList in java.

    To conclude this tutorial, we covered various types of implementation to sort ArrayList in Java.

    Palindrome Program In Java: Learn How To Check its a number or a string

    Palindrome Program In Java: Learn How To Check its a number or a string

    Looking to explore Palindrome in Java? Let’s discuss the details in this post.

    Introduction to Palindrome In Java?

    A palindrome is a phrase, number, digit, word, or sequence of characters which can read the same from backward as forward.

    Let’s see some of the examples of the Palindrome algorithm.

    Numeric Palindrome

    Palindrome Numbers:

    11, 121, 333, 5555

    Palindrome Time:

    12:21, 13:31, 11:11

    Palindrome Words, Sentences, Names

    1. Palindrome Words

    rotor, civic, level, racecar

    2. Palindrome Names

    anna, eve, bob

    3. Palindrome Sentences

    was it a car or a cat i saw, mr owl ate my metal worm, do geese see god.

    Using Java Implementation

    Let’s write a Java Palindrome program to check whether the given number is Palindrome or not.

    Here the input we provided in the below Java program is number 151(declared as integer variable).

    In this case, we are using for loop logic for iteration.

    We declared temp variable “actualValue”, to store the original string and compare it with reversed string.

    Palindrome Number Validation

    public static void main(String[] args) {
    
    	try {
    		int number = 151; 
    		int reverseValue = 0;
    		int reminder; 
    		int actualValue;
    		actualValue = number;
    		for(;number!= 0; number /= 10)
    	       {
    	           reminder = number % 10;
    	           reverseValue = reverseValue * 10 + reminder;
    	       }
    		if (actualValue == reverseValue)
    			System.out.println(actualValue + " is a valid palindrome.");
    		 else
    			System.out.println(actualValue + " is not a valid palindrome.");
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    Output:
    151 is a valid palindrome.
    

    As per the above output step, we can see the original input number 151 is matching with reversed number 151 which results in invalid palindrome.

    Let’s check the same implementation by using a while loop iteration in below Java program.

    public static void main(String[] args) {
    
    	try {
    		int number = 151; 
    		int reverseValue = 0;
    		int reminder; 
            int actualValue;
    		actualValue = number;
    		while (number != 0) {
    			reminder = number % 10;
    			reverseValue = reverseValue * 10 + reminder;
    			number /= 10;
    		}
    		if (actualValue == reverseValue)
    			System.out.println(actualValue + " is a valid palindrome.");
    		else
    			System.out.println(actualValue + " is not a valid palindrome.");
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    Output:
    151 is a valid palindrome.
    

    As per the above output, the original number is matching with the reversed number.

    In other words, it should be the same from first to the last digit and last to the first digit.

    You May Like,

    Palindrome String Validation

    in this section, you will know palindrome string validation in palindrome in java.

    Let’s write a Palindrome program to check whether the input string is Palindrome or not.

    Here is an example.

    public static void main(String[] args) {
    
    	try {
    		String inputValue = "rotor"; 
    		String reverseValue = "";
    		int length = inputValue.length();   
    			for ( int x = length - 1; x >= 0; x-- )  
    			 reverseValue = reverseValue + inputValue.charAt(x);  
    		if (inputValue.equals(reverseValue))
    			System.out.println(inputValue + " is a valid palindrome.");
    		else
    			System.out.println(inputValue + " is not a valid palindrome.");
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    Output:
    rotor is a valid palindrome.
    

    As per the above output, the input character is matching with the reversed character.

    Palindrome Validation using Reverse Method

    java palindrome

    Palindrome java validation

    in this section lets validate palindrome in java using the reverse method.

    Let’s leverage the Java library method reverse() of StringBuffer.

    Using the Palindrome program below, let’s use the reverse method to check whether the given string is Palindrome or not.

    The program will compare the original string with the reversed string and delivers the result accordingly.

    public static void main(String[] args) {
    
    	try {
    		String inputValue ="Ana";
    		String reverseValue = new StringBuffer(inputValue).reverse().toString(); 		  
    		if (inputValue.equalsIgnoreCase(reverseValue)) 		      
    		    System.out.println(inputValue + " is a valid palindrome.");		  
    		   else
    			System.out.println(inputValue + " is not a valid palindrome.");
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    Output:
    Ana is a valid palindrome.
    

    As per the output above, we can see the input is matching with reverse order or reverse string and thus results in invalid Palindrome.

    To conclude this tutorial, we covered various types of solution to validate Palindrome in Java.

    Write String to a File in Java

    Write String to a File in Java

    Looking to Write String to File Java? Lets explore different ways to achieve it.

    Using BufferedWriter

    Let’s use BufferedWriter of Java to write a String to a new text file.

    public static void main(String[] args) throws IOException {
    try {
    	 String value = "Welcome";
    	 BufferedWriter bw = new BufferedWriter(new FileWriter("src/resources/hello.txt"));
    	 bw.write(value);
    	 bw.close();
    	 System.out.println("Output written to hello.txt is: " +value);		 
    	} catch (Exception e) {
    		 e.printStackTrace();
    	}
    
    }
    
    Output:
    Output written to hello.txt is: Welcome
    

     

    With FileOutputStream

    Let’s use FileOutputStream class to write binary data to a text file.

    Below code converts a String byte array and writes the bytes to a file using FileOutputStream.

    The file path is passed to the output stream to write the desired string value as per the program.

    public static void main(String[] args) throws IOException {
     try {
    	  String value = "Welcome";
    	  FileOutputStream fos = new FileOutputStream("src/resources/hello.txt");
    	  byte[] bytes = value.getBytes();
    	  fos.write(bytes);
    	  fos.close();
    	  System.out.println("Output written to hello.txt is: " +value);		 
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    
    }
    Output:
    Output written to hello.txt is: Welcome
    

     

    Using PrintWriter

    We can use PrintWriter object to write formatted text to a file.

    First the file path is passed to the FileWriter class.

    And then PrintWriter class will process the Java FileWriter to print the formatted text in a file.

    public static void main(String[] args) throws IOException {
     try {
    	 FileWriter fileWriter = new FileWriter("src/resources/hello.txt");
    	 PrintWriter pw = new PrintWriter(fileWriter);
    	 pw.printf("Welcome to %s in Year %d", "Java World", 2020);
    	 pw.close();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    
    }
    
    Output:
    Output written to hello.txt is below
    
    Welcome to Java World in Year 2020
    

     

    With DataOutputStream

    Let’s leverage DataOutputStream to write a String to a file.

    Also the writeUTF method takes care of character encoding format that has to be written to a file.

    The default character encoding is modified UTF-8 format.

    public static void main(String[] args) throws IOException {
     try {
    	 String value = "Welcome";
    	 FileOutputStream fs = new FileOutputStream("src/resources/hello.txt");
    	 DataOutputStream os = new DataOutputStream(new BufferedOutputStream(fs));
    	 os.writeUTF(value);
    	 os.close();
    	 System.out.println("Output written to hello.txt is: " +value);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    
    }
    
    Output:
    Output written to hello.txt is: Welcome
    

     

    Using FileChannel

    Let’s use FileChannel to write a String to a file.

    Also FileChannel will be faster than the traditional Java IO.

    public static void main(String[] args) throws IOException {
     try {
    	RandomAccessFile stream = new RandomAccessFile("src/resources/hello.txt", "rw");
    	FileChannel channel = stream.getChannel();
    	String value = "Welcome";
    	byte[] strBytes = value.getBytes();
    	ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    	buffer.put(strBytes);
    	buffer.flip();
    	channel.write(buffer);
    	stream.close();
    	channel.close();
    	System.out.println("Output written to hello.txt is: " +value);
     } catch (Exception e) {
    	e.printStackTrace();
    	}
    
    }
    
    Output:
    Output written to hello.txt is: Welcome
    

     

    Create and Write to a Temporary File

    Let’s create a temporary file using createTempFile method from File Object.

    And then to write a String to a file, lets use Java FileWriter class.

    public static void main(String[] args) throws IOException {
     try {
    	String value = "Welcome";
    	File tempFile = File.createTempFile("testfile", ".tmp");
    	FileWriter writer = new FileWriter(tempFile);
    	writer.write(value);
    	writer.close();
      } catch (Exception e) {
    	e.printStackTrace();
      }
    
    }
    
    Output:
    The testfile.tmp will be created in Temp folder and the value 'Welcome' written to the temp file.
    

     

    To conclude this java tutorial, we covered various examples to write string to a file in Java.

    Happy Coding Readers 🙂

    Pin It on Pinterest