Understanding String in java programming tutorial



In this lesson we will learn what is a String and how to use strings. So the string type represents a sequence of zero or more Characters or in simple words it represents text. Concatenating many strings is not a good practice since every time we concatenate string new string object is created, Strings are immutable, That means when you create a string there is no way to change it, In other words, you can't make string smaller or larger, you can't change character inside the string, Even that syntax makes it appear as if you are changing string Mutable is another word for changeable so immutable is opposite and it means that once the object has been created it cannot be changed. So let's see Example below

COMPLETE CODES:

public class StringDemo{
public static void main(String[] args){
String dog = "Dog";
String dog2 = new String(new char[]{'D','o','g'});
System.out.println("dog == dog2 =>" +(dog ==dog2));
System.out.println("dog.equals(dog2) =>" +dog.equals(dog2));

String cat = "Cat";
String cat2 = new String("Cat");
String cat3 = cat2; // 2 references(cat2, cat3) to same object in memory

System.out.println("reference equality=>"+(cat==cat2));  // false
System.out.println("reference equality=>"+(cat==cat2));  // false
System.out.println("reference equality=>"+(cat==cat2));  // true

String lizard = "Lizard";
System.out.println("lizard first letter=" +lizard.charAt(0));
System.out.println("lizard contains iz=" +lizard.contain
("iz"));

//imutability
lizard.toUpperCase(); // common mistake, this does not change string it creates new string

System.out.println("lizard=" +lizard);
lizard = lizard.toUpperCase(); //assigns new value to variable or reference
System.out.println("lizard =" +lizard);
}
}

So first we will declare a variable String dog ="Dog" Literal inside ("") is "Dog", So now we create a new object of Strings that contains Characters "D", "o", "g" Now to create another String declare String dog2 = new String(new char[]{'D','o','g'}) And string class has a constructor that accepts a character value's or arrays of character so we can type "new char[]" and then Anonymous array "{'D','o','g'}" Single quotes are used for a single character or char type, Now we want to check the equality of those two strings or in other words, you want to see if those two strings contain the same characters, So run "System.out.println("dog == dog2");" First we will use (==) operator. This is the first one we are going to check and we've just add equals and greater than symbol (=>) just to treat them as a sign so we can easily read it in console plus(+) then inside braces(dog==dog2), which you can see also from the above example, Again we can see a warning when using (==) Operator's but let's not worry about this warning for now. With (==) operators we are checking the reference equality or in other words, we are checking if those two object or references "dog" and "dog2" point to the same object in memory we are not checking the logical equality or structural equality which means we are not checking that these two variables or references contain the same Character, To check if they contain same characters we've to use "equals()" method like this "System.out.println("dog.equals(dog2) =>"+ dog.equals(dog2));" And now let's run the code and see the output, The string as you probably already know is a reference type, so the equality operators "==" is defined to compare the reference's string objects and equality operator in java is used to compare references not content to check if two strings have the same content we have to use "equals()" method, Now notice how "dog==dog2 =>" is saying "false" means that these two strings, even that they have the same content, They are not the same object in memory So as you can see with (==) We can't compare strings in java, But when we say "dog.equals(dog2)=>" it will be equal to "true" because these two strings contain the same characters. Now let's try a different approach and let's declare three more things below

String cat = "Cat";
String cat2 = new String("Cat");
String cat3 = cat2;

So now Cat3 equals Cat2 Basically saying that "Cat2" and "Cat3" are the same reference So that two point to the same object in memory, and we've added little comments "//2 references (cat2,cat3) to an equivalent object in memory" And now let's print a reference equality System.out.println("reference equality=>"+(cat==cat2)); //false Now this will print "false" because they are two different objects, Let me just add two more lines copying the code above

System.out.println("reference equality=>"+(cat==cat3)); //false
System.out.println("reference equality=>"+(cat2==cat3)); //true

String lizard = "Lizard";
System.out.println("lizard first letter =" +lizard.charAt(0));
System.out.println("lizard contains iz =" +lizard.contains("iz"));



So now if we run the code you will see how the first reference (==) will be "false" and second also is "false" but third is "true" And that is because "cat3", "cat2" references to the same object in memory, Now there are many useful methods in string class that we can use for example to check if some string contains another string, Mistake that beginners usually make is calling a method on a string and expecting that it will change straight, Whenever you call a method on the string or any other immutable object you need to be aware that it doesn't change your original object it creates a new object. But let's first see some of the useful methods that string class has.

String lizard = "Lizard";
System.out.println("lizard first letter =" +lizard.charAt(0));


Now to get a Character specific you can use the method charAt() method and indexed "0" will give us the first letter of our string Now to see whether "lizard" contains letters "iz" we'll type System.out.println("lizard contains iz =" + lizard.contains("iz")); Now let's run the code and see what is going to be in console, now notice lizard first letter is a capital letter "L", contains() method is used to check if our string contains some other string and it returns a "boolean" and as you can see it "true". Now we are going to talk more about immutability and the mistake that beginners usually make when they call a method on a string, So what beginners usually do is type "lizard.toUpperCase();" And this method doesn't change the string. It creates a new string notice when we check the Documentations of "toUpperCase" it returns a new String object, And now when we try to print that you will expect it has changed to uppercase but it didn't change because it is immutable. Notice that "lizard =Lizard" It didn't change two applicants so to change or in other words to re-assign a new value to our variable we need to type lizard =lizard.toUpperCase(), and then our "lizard" will be uppercase "LIZARD" when we print it using (S.O.Println) like the code System.out.println("lizard=" +lizard); Since we are assigning a new value we are not changing the original string we are just saying that our reference lists will point to a different object in memory, Now if we run the code you will see the last "lizard" or the last line will be "LIZARD" in uppercase. Now it is good idea to check other methods in string class that can be useful so there is toUppercase(),toLowercase(),getBytes(),indexof(), isEmpty() So there are many useful methods.




Post a Comment

0 Comments