It2EDU

Tuesday, March 7, 2017

LearnersChoice: Heap Sort: It is like a comparison based sorting, it is the improvement of selection sort. Heap sort is divide the elements into two regions so...

Sunday, March 5, 2017


Java Strings



Strings are widely used in Java programming. A string is a sequence of characters or simply says a character array. Strings are treated as Objects.
The Java platform provides the String class to create and manipulate strings.




How to create a String:




The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case,

"Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor.

The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.



public class StringDemo{


public static void main(String args[]){

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

String helloString = new String(helloArray);

System.out.println(helloString );

}

}

The above code snippet gives the output hello





“The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation”



Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.


After the following two lines of code have been executed, len equals 17:



String palindrome = "Dot saw I was Tod";

int len = palindrome.length();



String Concatenation



Concatenating means combine two strings one at the end of the other.

In strings concat(String str) is a method used to concatenate the strings.

The String class includes a method for concatenating two strings:


string1.concat(string2);


This returns a new string that is string1 with string2 added to it at the end.


You can also use the concat() method with string literals, as in:


"My name is ".concat("Rumplestiltskin");


Strings are more commonly concatenated with the + operator, as in


"Hello," + " world" + "!"


which results in


"Hello, world!"


The + operator is widely used in print statements. For example:


String string1 = "saw I was ";

System.out.println("Dot " + string1 + "Tod");


which prints


Dot saw I was Tod


Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.