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?

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 us...

Read full answer

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=" + myCharA...

Read full answer

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');

Read full answer

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" : Syste...

Read full answer

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 (Stri...

Read full answer

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 ...

Read full answer

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 cre...

Read full answer

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 ...

Read full answer

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" , "...

Read full answer

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\n Allow: /" + " \r\n Sitemap: http://www.javapedia.net/sitemap...

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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

All the three classes are final.

Read full answer

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.

Read full answer

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)

Read full answer

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 char...

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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 advantag...

Read full answer

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.

Read full answer

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 mor...

Read full answer

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 StringB...

Read full answer

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.

Read full answer

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 concurren...

Read full answer

«
»

Comments & Discussions