Monday 9 March 2020

Java String | String class in java | java string methods - Online Help

In this post, we are discussing what is java string? that is what is a string class in java.let's see the string constructors and methods available in java. The topic which we will be going to cover in this post is

Java String | String class in java - Online Help

String class in Java:

A combination of characters is a string. Strings are instances of the class string. They are real objects and enable combination, testing, and modification. When a string literal is used in the program, Java automatically creates an instance of the String class. 

The string is a sequence of characters enclosed within double quotes “ “. This class is used to represent the constant string.it is fixed size. These classes are contained in the package java.lang that represents a string in Java that provides two fundamental classes that represent a string in Java. They are:


String declaration in Java:

Before we use a string in our program we have to declare it. so the java string Syntax is,

String stringname;

Where,

  • String is the java literal
  • Stringname is the name of the string

Example:
String s;

String initialization in Java:

The string can be initialized at the time of the string declaration. The value which we assign to the string should be enclosed with the double quotes " ''. so the initialization of the string is,

String strname=” variables”;

Example:

String s=” Sania”;

We can use an array in the declaration and initialization of string. let’s pass the array of values to the string,

String name[]={“Rohit”,” Rahul”,” Rohan”,” pooja”,” Sneha”};

Accessing the string:

In order to access the string, we have to create an instance for the string class. With the help of instance, we can access the string.

In the next section, let's see how to create Constructors and what are the different ways available in constructors so that we can understand the topics on how to create and access the instance.

Drawbacks of string class:


  • String class objects are immutable because once it is created the content of the string cannot be modified.
  • Because it is immutable it needs more memory space.

String program in Java:

Declaration and access of strings
Class strings
{
int i;
String name[]={“aaaa”,”bbbb”,”cccc”,”dddd”};
Void show()
{
System.out.println(“my favourite names are”);
for(i=0;i<5;i++)
System.out.println(name[i]);
}
}
Public static void main(String args[])
{
Strings s=new strings();
s.show();
}
}

The output is:

aaaa
bbbb
cccc
dddd

String constructors in Java:

Different types of String constructors are available in Java so that you can use the string in different ways as per your requirement. With these constructors, you will go through with different types of string declaration and initialization. The different types of the constructor are:

Empty string:

Let's see how empty string is created using the class string. It is the default constructor with no parameter.

The general form is,

String stringname;
Stringname=new String();

In the above statement is equivalent to the following statement:

String stringname=new string();

Example:

String str1;
str1=new String();

Is equivalent to

String str1=new String();

Or

String str=” ”; // empty string

The example will create an instance of a string with no characters in it.

String with character:

In order to create a string initialized with the character, we need to pass an array of characters to the constructor. let's see how the string is created with the character.

The general format is,

String strname=new String(character);

where the string and new are keywords. Strname is the name of the string. The String(character) is the constructor character in which the character is to assign.

Example:
Char chars[]={‘z’,’u’,’h’,’a’};
String s=new String(name);
System.out.println(s);

The above example creates a string instance with the four characters from the char as the initial value of the string s.

String with another string:

let's see how a string is created with another string. The general format to create a string with another string is,

String strname1=new String(strname2);

Where,

  • The string and new are keywords
  • The strname1,2 is the name of the string. 
  • In the string(), strname1 is assigned to the strname2

Example:
String str1=”sneha”;
String str2=new String(str1);
System.out.println(str2);

String with substring:

A string is created using the substring that allowed the specification of the starting index and the number of characters that have to be used. The general format is,

String strname=new String(char chars[],int startIndex, int numberofchar);

Where,

  • The String and new are keywords
  • char chars[] is the original string of character
  • startIndex is the starting index of the substring
  • Numberofchar is the ending number of substring.

Example:
char name[]={‘s’,’n’,’e’,’h’,’a’}
String str=new String(name,1,4);
System.out.println(str);

The example given above will print neha because when ‘n’ was at the index at 1 and we specified the count of 4 characters to be used to construct the string.

String with an array of ASCII:

let's see how a string is created with the array of ASCII parameters. The general format is,

String strname=new String(ASCIInum);

Where,

  • String and new are keywords. 
  • strname is the name of the string 
  • ASCII num is the ASCII value.

Example:

int value[]={77,65,78};
String str1=new String(value);
System.out.println(str1);

it will return the output as MAN.

string methods in Java:

The string class contains a number of methods that allow you to perform string manipulation. Most commonly used string methods are as follow:

Methods
Description
General format
length()
Number of character in string
Stringobject.length()
charAt()
The char at a location in the string
Stringobject.charAt(int indexvalue);
getChars(),getBytes()
Copy chars or bytes into a external array
Stringobject.getChars();
toCharArray()
Produces a char[]contains the character in the string
Stringobject.toCharArray()
equals(),equalsIgnoreCase()
An equality check on the content of the two strings
Stringobject.equals(string);
compareTo()
Results is negative,0 or + depending on the lexicographical ordering of the string and the argument. Uppercase and the lower case are not equal.
Stringobject.compareTo(string1);
regionMatches()
Boolean result indicates whether the region matches
 boolean regionMatches()
startWith()
Boolean result indicating whether the region matches
 boolean startWith()
endsWith()
The boolean result indicates if the argument is a suffix
boolean endsWith()
indexOf(),lastIndexOf()
Return -1 if the argument is not found within the string,otherwise returns the index where the arguments start. lastIndexOf() searches backward from the end.
Stringobject.indexOf(char);
Stringobject.lastIndexOf(char);
Substring()
Return a new string object contains the specified character set.
1.   Stringobject.substring(int beginindex);
2.   Stringobject.substring(int indexbegin,int endindex);
Concat()
Return a new string object contain the original strings character followed by the characters in the argument.
Stringobject.concat(string);
Replace()
Return a new string object with the replacements made.uses the old string if no matches found.
Stringobject.replace(oldstring,newstring);
toLowerCase(),toUpperCase()
Return a new string object with the case of all letter changed.uses the old string if no changes need to be made.
Stringobject.toLowerCase();
Stringobject.toUpperCase();
Trim()
Return the new string object with the whitespace removed from each end.uses the old string if no changes need to be made.
Stringobject.trim();
valueOf()
It returns a string containing a character representation of the argument.
String valueOf();
Intern()
Produces one and only string handle for each unique character sequence.
 String intern()


It is seen that every string method returns a new string object when it is necessary to change the contents. Also noticed that if the content does not require any change, the method will just return a handle to the original string. This saves storage and overhead.

Java String method example:

equal():

Class equaldemo
{
Public static void main(String args[])
{
String s1=”welcome”;
String s2=”welcome”;
String s3=”good morning”;
String s4=”welcome”
System.out.println(s1+”equals”+s2+”is”+s1.equals(s2));
System.out.println(s1+”equals”+s3+”is”+s1.equals(s3));
System.out.println(s1+”equals”+s4+”is”+s1.equals(s4));
}
}

The output is:

Welcome equals welcome is true
Welcome equals good morning is false
Welcome equals welcome is false

Sample program for :
length(),toLowerCase(),toUpperCase(),charAt(),concat(),indexOf(),lastIndexOf(),substring(),replace(),and trim()


Class st
{
Public static void main(String args[])
{
String s=”johny johny yes papa”+”eating sugar no papa”+”telling lies no papa”;
String s1=”hello world”;
String s2=”hello”;
String s3=”HELLO”;
String s4=”monkey”;
String s5=”don”
System.out.println(“index of e=”+s.indexOf(‘e’));
System.out.println(“last index of e=”+s.lastIndexOf(‘e’));
System.out.println(s1.substring(6));
System.out.println(s1.length());
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(“world”));
System.out.println(s2.replace(‘l’,’w’));
System.out.println(s2.toUpperCase());
System.out.println(s3.toLowerCase());
System.out.println(s3.charAt(3));
System.out.println(s1.trim());
System.out.println(s4.compareTo(s5);
}
}

The output will be

johny johny yes papa eating sugar no papa telling lies no papa
index of e:14
11
last index of e: 62
world
lo wo
helloworld
hewwo
HELLO
Hello
l
hello world
6

String arithmetic:

The ‘+’ sign doesn't mean “addition” when it is used with the string object. The Java string class has something called operator overloading”, in another word the ‘+’ sign, when used with the string object, behave differently that does with everything else.

For string, it means: “concatenate these two strings”. when it is used with the strings and other objects creates a single string that contains the concatenation of all its operands.

When a numerical value is added to a string, the compiler calls the method that turns the numerical value( int, float, etc) into a string which can then be added with the Plus sign.

Any object or type you can convert to the string if the method to string() is implemented. To create a string, add all the parts together and output them. The +=operator will also work for the strings.

Example:
class sample
{
String fname=”rohit”;
String lname=”sharma”;
void show()
{
System.out.println(“The full name is+” “+fname+” “+lname);
}
Public static void main(String args[])
{
sample s1=new sample();
s1.show();
}
}

The output is;

The full name is rohit sharma

I hope you find this article useful. if you have any queries regarding this or something went wrong. Then please do comment.

Recommended post(you may like):




No comments:

Post a Comment