Which of the following statements is preferred to create a string "Welcome to Java Programming"?

Options
- String str = “Welcome to Java Programming”
- String str = new String( “Welcome to Java Programming” )
- String str; str = “Welcome to Java Programming”
- String str; str = new String (“Welcome to Java Programming” )


CORRECT ANSWER : String str = “Welcome to Java Programming”

Discussion Board
VISIX

A is correct :
String value is known, compile time initialization gives more performance than run time initialization

Nageswar Rao 01-31-2017 01:04 AM

String Method

String is an array of characters and it is implemented with the help of instances of the class. Strings are constants i.e. their values can't be changed after they are created. String objects are immutable i.e. the objects of the string can be shared. But String buffers support mutable strings also. Example:

String str = "abc";
can also be written as:

char data[] = {'a', 'b', 'c'};
String str = new String(data);

There are many ways a string can be used:

System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

String class uses methods to examine individual characters of the sequence, for comparison, for searching, for extractions, for copy characters and translation purpose from uppercase to lowercase.
So, as per the string definition the preferred method that is given as an answer is correct as it uses less lines and code to call a method.

Rohit Sharma 07-30-2014 03:05 AM

preffered option

here all are correct options. but question is which of these is most preffered?
answer will be String str = “Welcome to Java Programming”.
because it creates only one object of “Welcome to Java Programming” in string poool. and here declaration and inisialization is in same line. so less line of code is used.

meera 07-2-2014 04:39 AM

correct option

option A & B both are correct


ravi 02-3-2014 03:01 AM

Write your comments

 
   
 
 

Enter the code shown above:
 
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement