1.

Differentiate between strings and char arrays in Java.

Answer»
StringsCharacter Arrays
A string is a sequential COLLECTION of characters that are represented as a SINGLE DATA type.A Character Array is a collection of char data types in sequential order.
Strings are IMMUTABLE which means the data or state of a String object can't be modified once it has been created; instead, a new String object is generated.Character Arrays are mutable which means the contents of a char array can be changed.
Strings can be used with built-in functions like substring() and charAt().In Java, there are no built-in functions for working with Character Arrays.
The '+' operator can be used to join two strings together to GENERATE a new one.Appending two Character Arrays with '+' is not possible.
The charAt() method is used to access characters in a String at a specific index.[] can be used to access the characters in a Character Array in the same way it can in any other language.
Strings can be stored in memory in any manner.Character Array elements are sequentially stored at increasing memory places.
The String Constant Pool contains all Strings.The Heap contains all Character Arrays.

The toCharArray() function of the String class can be used to transform a String into a Character Array.

Eg: String s = “GEEKS”;

char [] ch = s.toCharArray();

The code above converts a string into a char array.

A String Constructor can be used to transform a Character Array to a String.

Eg: char[] a = {‘G’, ‘E’, ‘E’, ‘K’, ‘S’};

String A = new String(a);

The code above converts a char array into a string.



Discussion

No Comment Found