Java Programs  «Prev 

Building Character with Strings

You work with text in a Java program by using strings, which are comprised of a series of text characters. Following are some examples of strings:
"Howdy", "ABC", "123", "$99.99", and "Hello, world."

Since strings consist of a series of characters, they have a length associated with them. The length of a string is simply how many characters there are in the string. You can also access and manipulate individual characters within a string.
How can you build characters using Strings in Java?
In Java, you can build characters using Strings by using the charAt() method, which returns the character at a specific index in the String. For example, let's say you have a String variable called myString that contains the value "Hello World". You can retrieve the character 'H' from this String by calling the charAt() method with an index of 0, like this:
char firstChar = myString.charAt(0);

This assigns the value 'H' to the variable firstChar. You can also concatenate Strings to build new Strings. For example, let's say you have two String variables called firstName and lastName that contain the values "John" and "Doe", respectively. You can concatenate these two Strings to build a new String that contains the full name "John Doe" like this:
String fullName = firstName + " " + lastName;

The plus sign (+) is used to concatenate the Strings. The space between the two quotes is necessary to add a space between the first and last name. You can also use the concat() method to concatenate Strings. For example:
String fullName = firstName.concat(" ").concat(lastName);

This is equivalent to the previous example using the plus sign.

Creating and Using Arrays

Which of the following statements are valid ?
Select 2 options
  1. String[ ] sa = new String[3]{ "a", "b", "c"};
  2. String sa[ ] = { "a ", " b", "c"};
  3. String sa = new String[ ]{"a", "b", "c"};
  4. String sa[ ] = new String[ ]{"a", "b", "c"};
  5. String sa[ ] = new String[ ] {"a" "b" "c"}
Answer: b,d
Explanation:
a. You cannot specify the length of the array ( i.e. 3, here) if you are using the initializer block while declaring the array.
c. Here sa is not declared as array of strings but just as a String.
e. There are no commas separating the strings.