Prev Next

Java / Using String

1. How do I iterate through every character in a String? (or) How to parse each character in a String object? 2. toCharArray() Method 3. How do I convert a char (primitive data type variable) to string in Java? 4. Can we use String in switch case control statement? 5. How do I split a pipe delimited Java String using split method? 6. How do I create a Regular expression pattern into non-greedy in Java? 7. Explain SimpleDateFormat class and its usage in Java. 8. How to check if a string is not null and not empty in Java? 9. How do I remove duplicate elements from a String Array in Java? 10. How do I write a new line character to a file in Java? 11. What is the maximum length of a String in Java? 12. How many String objects be created by the snippet and where it is stored in Java? 13. How do you convert a string object to character array in Java? 14. Is string a wrapper class in Java? 15. How many spaces does the Java String.trim() remove? 16. Can we compare String and StringBuffer objects in Java? 17. Which class is final:String, StringBuffer and StringBuider? 18. What is the initial capacity of a StringBuilder object in Java? 19. How to avoid NullPointerException when comparing two Strings in Java? 20. Does substring method cause memory leak? 21. what happens if beginIndex is equal to length of the String when calling substring(int beginIndex)? 22. When substring method throws IndexOutOfBoundException? 23. How to resolve substring memory leak issue in java version prior to JDK 1.7? 24. Where String pool is located? 25. What is the output of this statement?
System.out.println ("A"=="A");
26. What is the difference between appending a string to a StringBuilder and concatenating two strings with a + operator? 27. How string concatenation operator (+) works in Java? 28. When the concatenation of final string literal happen? 29. Is Java's SimpleDateFormat thread-safe?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. How do I iterate through every character in a String? (or) How to parse each character in a String object?

The convenient and simple way is to create a for-each statement that runs through every character at the String object after the character array is generated.

String myStr = "HelloWorld!";
char myCharArray[] = myStr.toCharArray(); // convert the String to char array
							
// iterate over the array using the for-each loop.
for (char c : myCharArray) {
	System.out.println(c);
}

2. toCharArray() Method

converts the string to a new character array.

public char[] toCharArray()

public class CharArrayExample {
	public static void main(String args[]) {
		String myString = new String("JavaPedia.net");
		char[] myCharArray = myString.toCharArray();
		System.out.println("Length of the Array=" + myCharArray.length);
		System.out.println(("Element at the first index= " + myCharArray[0]));
	}
}

Output:

Length of the Array=13

Element at the first index= J

3. How do I convert a char (primitive data type variable) to string in Java?

The below are the recommended ways to implement the conversion.

Using String.valueOf() method,

 String myString = String.valueOf('c'); 

Using Character.toString(char) method,

 String myString = Character.toString('c');

4. Can we use String in switch case control statement?

Java 7 featured the capability of switch case to use Strings, earlier java versions haven't supported it.

Example

package org.javatutorials.conditional;

public class SwitchCaseUsingString {

	public static void main(String[] args) {

		String stringObj = "ONE";
		
		switch (stringObj) {
		case "ONE":
				System.out.println("1 is entered"); break;
		case "TWO":
			System.out.println("2 is entered"); break;
		case "THREE":
			System.out.println("3 is entered"); break;
		default:
			System.out.println("Something else is entered");
		}
		
	}

}

5. How do I split a pipe delimited Java String using split method?

The pipe (|) symbol need to be escaped using \\ to treat it as a normal character since split method uses regular expression and in regex | (pipe) is a meta character representing OR operator.

String pipeDelimitedStr = "Tag1|Tag2|Tag3";
String[] tags = pipeDelimitedStr.split("\\|");
for (String tag : tags) {
    System.out.println(tag);
}

6. How do I create a Regular expression pattern into non-greedy in Java?

The non-greedy regular expression constructs are similar to the greedy modifier with a question mark (?) immediately following the meta character.

For example, * (asterisk) meta character that matches zero or more is a greedy pattern while * (asterisk) followed with question mark *? matches same zero or more characters however it is non greedy.

See below are the examples of greedy construct and its equivalent non-greedy regular expression constructs in Java.

Constructgreedynon-greedy
zero or more* *?
one or more+ +?
zero or one? ??

7. Explain SimpleDateFormat class and its usage in Java.

java.text.SimpleDateFormat concrete class is widely used in Java for parsing (text to date) and formatting of dates (date to text).

SimpleDateFormat enables choosing user defined patterns for date-time formatting. Also the date-time formatter initialized with a default format pattern could be created using either getTimeInstance, getDateInstance or getDateTime Instance methods in DateFormat class.

package com.javatutorials.date;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFmtExample {

	public static void main(String[] args) {
		String pattern = "MM/dd/yyyy";
	SimpleDateFormat format = new SimpleDateFormat(pattern);
	try {
		Date date = format.parse("06/21/2016");
		System.out.println(date);

		DateFormat dateFmt = DateFormat.getDateInstance();
		System.out.println(dateFmt.format(date));

	} catch (ParseException e) {
		e.printStackTrace();
	}
	// formatting
		System.out.println(format.format(new Date()));
	}

}

Note that the SimpleDateFormat objects are not synchronized. It is always a good practice to create separate format instances for each thread or use ThreadLocal class.

8. How to check if a string is not null and not empty in Java?

String.isEmpty() non-static method is introduced in Java SE 1.6 that evaluates the string object is empty or not given that the string object is not null otherwise it throws NullPointerException.

if(str != null && !str.isEmpty())

Be sure to use the left and the right conditions of && operator in the above order, as Java will not evaluate the right operand if the left operand is false, thus preventing the NullPointerException being thrown from str.isEmpty() if str is null.

To ignore the white space, use the trim method as shown below.

if(str != null && !str.trim().isEmpty())

Prior to Java SE 1.6, string.length method could be used to evaluate if the string is empty or not.

if(str != null && str.length()>0)

9. How do I remove duplicate elements from a String Array in Java?

Using Java Collection framework API, the duplicate elements in a string array can be removed easily by converting the string array to List, creating a HashSet from the List that removes the duplicates and converting set to String array back. See the example below.

String[] data = { "a", "c", "b", "d","a", "c", "b", "d"};
System.out.println("Actual array: " + Arrays.toString(data));

List<String> strList = Arrays.asList(data);
Set<String> strSet = new HashSet<String>(strList);
String[] result = new String[strSet.size()];

strSet.toArray(result);

System.out.println("Array without duplicates: ");
for (String s : result) {
  System.out.print(s + ", ");
}

The above program can be shortened further as shown below.

String[] data = { "a", "c", "b", "d", "a", "c", "b", "d" };

data = new HashSet<String>(Arrays.asList(data)).toArray(new String[0]);

for (String s : data) {
	System.out.print(s + ", ");
}

10. How do I write a new line character to a file in Java?

Using carriage return and line feed \r\n, a new line character can be written to a file. Two characters \r\n combined represent a new line on Windows whereas on Linux, \n represents new line.

  String robotsTxt = "User-Agent: * "+
    		"\r\nAllow: /"+
    		"\r\nSitemap: http://www.javapedia.net/sitemap.xml";
    File batFile= new File("robots.txt");
    PrintWriter batOut = null;
	try {
		batOut = new PrintWriter(batFile);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
    batOut.print(robotsTxt);

11. What is the maximum length of a String in Java?

The maximum length of a String is Integer.MAX_VALUE, which is 2^31 - 1. The return type of String length() method is int and an int could have only Integer.MAX_VALUE as its largest value.

Also Integer.MAX_VALUE is the maximum value that could be allocated for an array in Java.

12. How many String objects be created by the snippet and where it is stored in Java?

String str1 = "javapedia.net";
 
String str2 = "javapedia.net";

Only one string object will be created and this object be stored in the string (constant) pool.

13. How do you convert a string object to character array in Java?

Using toCharArray() method a string object can be converted to a character array in Java.

14. Is string a wrapper class in Java?

No, String is a class, but not a wrapper class. Wrapper classes like Integer exists for each primitive type and they can be used to convert a primitive data value into an object or vice-versa.

15. How many spaces does the Java String.trim() remove?

All the leading and trailing white spaces will be removed irrespective of number of spaces at either side of the string.

The trim method does not remove the intra-sentence spaces.

16. Can we compare String and StringBuffer objects in Java?

Although both String and StringBuffer represent String objects, we cannot compare each other and if we try to compare them, we get an exception.

17. Which class is final:String, StringBuffer and StringBuider?

All the three classes are final.

18. What is the initial capacity of a StringBuilder object in Java?

It is the length of the initial string plus 16 .For example, new StringBuilder("javapedia"), the length of the string is 9 + 16 = 25, the initial capacity of the object.

19. How to avoid NullPointerException when comparing two Strings in Java?

When a string is compared to null, equals return false and doesn't throw NullPointerException. So when a string constant is compared invoke equals on the string constant as it avoids NullPointerException.

"SomeStringLiteral".equals(str)
20. Does substring method cause memory leak?

It was and it is fixed since JDK 1.7. The issue was substring method creates new String object keeping a reference to the whole char array, thus inadvertently keep a reference to a very big character array with just a one character string.

It was fixed in Java 7, rather than sharing original character array, substring method creates a copy of it and creates new String.

21. what happens if beginIndex is equal to length of the String when calling substring(int beginIndex)?

substring returns an empty string and does not throw IndexOutOfBoundException.

22. When substring method throws IndexOutOfBoundException?

substring method will throw IndexOutOfBoundException when beginIndex is negative, beginIndex larger than endIndex or larger than length of String.

23. How to resolve substring memory leak issue in java version prior to JDK 1.7?

Simple solution is to trim the string and keep the size of character array according to the length of substring by creating new string object from string object returned by substring method.

24. Where String pool is located?

Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it cannot be expanded at runtime and is not eligible for garbage collection.

From Java 7 onwards, the Java String Pool is stored in the heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.

25. What is the output of this statement?
System.out.println ("A"=="A");

The above statement prints true. The first string literal creates an object in the string pool which is returned later for the second literal. The references are same and hence true.

26. What is the difference between appending a string to a StringBuilder and concatenating two strings with a + operator?

String is immutable while StringBuilder is not.

When concatenating two String instances, a new object is created, and strings are copied. This may cause a huge garbage collector overhead if we need to create or modify a string in a loop. StringBuilder allows handling string manipulations much more efficiently.

27. How string concatenation operator (+) works in Java?

When 2 string objects are concatenated, internally Java creates a new StringBuilder object and appends both string objects and returns a new concatenated string by calling toString method on StringBuilder object.

For example, String website="javapedia"+".net"; will translate as below.

new StringBuilder("javapedia").append(".net").toString();
28. When the concatenation of final string literal happen?

JVM concatenates the final string literals during compile time.

For example, final String website = "javapedia." + "net";, the concatenation is handled by JVM during compile time itself.

29. Is Java's SimpleDateFormat thread-safe?

No. SimpleDateFormat is not thread-safe, because it stores intermediate results in instance fields. So if one instance is used by two threads they can mess up each other's results.

It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

DateTimeFormatter in Java 8 is immutable and thread-safe alternative to SimpleDateFormat.

«
»
Exception

Comments & Discussions