× Home

String and Stringbuilder

  1. Stack memory ↓
    • When we declare a variable
    • E.g. → int a = 10;
    • So, here the reference variable is stored in stack memeory
  2. Heap memory ↓
    • Reference variable stored in stack memory is pointing to the object of that variable which are store in heap memory.
  3. Memory allocation ↓
    • Memory allocations specifies the memory address to a program.
    • There are two types of memory
      1. Stack Memory
      2. Heap memory
  4. Static memory allocation ↓
    • It performs type checking at compile time
    • Here, errors will show at compiler time
    • Declare datatype before you use it.
    • More control & runtime erros are reduced.
    • Here you've to write a little bit more code, but you've more control over the type of data.
  5. Dynamic memory allocation ↓
    • Perform type checking at runtimes
    • Here, errors might not shown till the program runs
    • No need to declare a datatype of variable
    • It saves time in writing code but might give error at runtime.
  6. Garbage collections : ↓
    • More than one reference variable can points to the same object
    • If any changes made in the object of an reference variable that will be reflected to all other pointing to the same object
    • If there is an object without reference variable then the object will be destroyed by "garbage collection".
    • So that's how garbage collection works

What are strings ?

  • Strings are pile or a sequence of characters for E.g "Giovanni"
  • It a datatype & it a non-primitive
  • Syntax : String name = "Giovanni Georgio";
  • It is the most commonly used class in the JAVA class library
  • Every string that you create it's actually an object of type string

Concepts

1 → String pool

  • It is a seperate memory structure inside the heap

Why seperate pool? why not just putting it out in the heap normally like every other object?

  • All the similar values of strings are not like recreated in the pool.
  • Eg:
    • String a = "Giovanni"
      String b = "Giovanni"
      • So it's gonna be like it already exists in the pool so no need to create it again
  • Use case : It maakes our program more optimized

Note → If you try to change this object via this reference variable it will not change for b.

  • Why?
    • Immutability
      • Strings are immutable in java, we can't change the object or modify object.
      • If you wanna rename to "kunal" you've to create a new object for that
      • Strings are immutable for security purpose.

Why strings are immutable?

  • All person's named as kunal → All of them will be having just one object "kunal"
  • Suppose one person decides to change their name
    • If it was not immutable, if a person 1 decided to change their name to karan.
    • So, that will change his name to karan
  • If it was allowed to modify this than all person 1, 2, 3 & 4 will name will be karan in the database
  • Therefore for the security reasons strings are immutable

Comparisons of strings

== method → comparitor

  1. a → "kunal"
    b → "kunal"
    a == b → in this case it gives false
  2. a → "kunal"
    b → a
    a == b → in this case it gives true
comparitor actually checks for value and reference variable
If the reference variable is pointing to the same object

How to create different objects of same values

  • By using new keyword
    • String a =("kunal");
      String b = new String("kunal");
  • So these values are getting created in heap outside the pool
    • because it is object so it will be in heap only.
    • Even though the values are same but these two a & b are not pointing to the same object in that case it will give false

When you only need to check value, use .equals method

                                

                                    String name1 = new String("kunal");
                                    String name2 = new String("kunal");

                                    system.out.println(name1.equals(name2)); // true
                                
                            

here it does not care whether the reference variable are pointing to same object or not it just care about the value.

  • Class is a name group of properties and funtcions.
  • We can't do ↓
    • System.out.println(name1[0]);
  • But in arrays we can do this
  • Though it's sort of collection of characters but we cannot do ↑ this

So, we have to use a method called charAt()

                            

                                System.outprintln(name.charAt(0));
                                // here out is a variable of type printstream
                                // printstream is a class, it has method in it called println
                            
                        

function overloading or method overloading

  • Function overloading happens when two functions have same name.
                            

                                // Eg
                                fun () {
                                    // code 
                                }           // ✗ function overloading
                                fun () {
                                    // code 
                                }
                            
                        
                            

                                // Eg 2
                                fun (int a) {
                                    // code 
                                } 

                                 // ✓ It is allowed having different arguments with same function / method name
                                
                                 fun (int a, int b) {
                                    // code 
                                }
                            
                        

At compile time it decides which function to run.

Pretty printing :-

                            

                                float a = 453.1234f;
                                System.out.printf(" formatted number is %.2f " + a);
                                // printf → formatted string
                                // %.2f → place holder 
                            
                        
  • Well % means a place holder & till how many decimal value do we want.
    • For eg → 2 → %.2f (f because it's float)
  • It rounds off all as well.
                            

                                // For π
                                System.out.printf(Math.PI);

                                // For string
                                System.out.printf("Hello my is %s but everybody calls me %s", "Giovanni Georgio", "Georgio");
                                // o/p → Hello my name is Giovanni Georgio but everybody calls me Georgio
                            
                        

Some common format specifiers :-

  1. %c → Character
  2. %d → Decimal number (base 10)
  3. %e → Exponential floating - point number
  4. %f → Floating - point number
  5. %i → Interger (base 10)
  6. %o → Octal number (base 8)
  7. %s → String
  8. %u → Unsigned decimal (integer) number
  9. %x → Hexadecimal number (base 16)
  10. %f → date/time
  11. %n → Newline

Operator Overloading

Operator + ('Overloaded for string type')

                            

                                System.out.println('a' + 'b'); // 195 - both char get converted to int

                                System.out.println("a" + "b"); // ab - these are in string type

                                System.out.println('a' + 3); // 100

                                System.out.println((char) ('a' + 3)); // d

                                // Note → when you're doing the addition with characters
                                // it converts into its value into a number 
                                // then it use that number to solve the problem


                                System.out.println("a" + 1);
                                // interger will be converted to Integer that will call toString()
                                // Note → when an integer is concatenated (added)
                                // with a string it gets converted to its wrapper callse interger

                                // this is same as after a few steps: "a" + "1"
                        
                                System.out.println("kunal" + new ArrayList<>()); // kunal[]
                                // System.out.println("kunal" + new Integer(46));
                                // ↑ gives error
                                // operator '+' cannot be applied to integer and arraylist.
                            
                        
  • Operator '+' in Java is only defined for primitives and when any one of these values is a string.
  • Operator '+
  • you can only use with primitive and you can only use this with all complex objects as well
    • But, the only condition is at least one of those objectc should be of type string.
                            

                                // Eg
                                sout(new Integer(56) + " " + new Arraylist<>(););
                                       ↓                ↓           ↓ 
                                 complex obj     string type      complex object
                                 
                                 // here the entire result will be of string type 
                                 // o/p 56[]
                            
                        

So, on string objects the plus operator is being overloaded, because it concatenate more than one string

  • It java operator overloading is not supported for some software engineering consideration but, in C++ it is supported.
  • In C++ & python you can modify '+' operator
    • Basically modify its purpose / functionality
  • You can also make it act like as a multiplication or subtraction, you can add complex data type as well.
  • but this results in poor code, that is why in Java it is not supported.
  • Java has only given us operator overloading exception for strings, but you cannot do it on your own type like array, hash map. It will not allow ever for the modification
  • It's the only operator that is intentionally overloads in java to support string concatination or string joining.
  • new Integer( ) → Its now deprecated.
                            

                                sout("a" + 'a'); 
                                // o/p aa 
                                // If one of the data type is string ans will be string
                            
                        

String Performance

This is important for invterview

                            

                                public class Performance {
                                    public static void main(String[] args) {
                                        String series = "";
                                        for (int i = 0; i < 26; i++) {
                                            char ch = (char) ('a'+i);
                                            series+=ch;
                                            // this is actually creating new string object in every iterations
                                        }
                                        // so as this have time complexity of O(N^2) this is not efficient
                                        // what's the better way ??
                                        // where we can easily modify the string -- is there any such data type  ??
                                        // this is where string builder comes in equations and it is different class
                                        System.out.println(series);
                                    }
                                }
                                
                            
                        
  • Here the new object is being created in every iteration, it is not changing the original object because the string are immutable therefore this one are copying the old one and its appending it with the new one.
  • So much waste of memory because of this and it won't be having any reference variable. So time complexity = O(n2) worst.
  • Solution ↓
    • Wouldn't it be great if there was a sort of datatype that will allow us to modify its value because strings fails to allow this.
    • So, the answer is "stringbuilder"
  • Stringbuilder is a seperate class
                            

                                public class SBuilder {
                                    public static void main(String[] args) {
                                        StringBuilder builder = new StringBuilder();
                                        // this one is mutable
                                        for (int i = 0; i < 26; i++) {
                                            char ch = (char) ('a'+i);
                                            builder.append(ch);
                                        }
                                        // so this comes with many methods which are self explainatory 
                                        // like builder.reverse() etc
                                        System.out.println(builder.toString());
                                    }
                                }
                            
                        

Methods that string provide (some)

1 → .toCharArray() → It converts strings into array character

                                    
                                        
                                        String name = "Giovanni Georgio";
                                        System.out.println(Arrays.toString(name.toCharArray()));
                                        // o/p ['G', 'i', 'o', 'v', 'a', 'n', 'n', 'i', ' ', 'G', 'e', 'o', 'r', 'g', 'i', 'o' ]

                                        // Even that space will be counted
                                    
                                
                                    

                                        // .length() → It will provide you the length 

                                        // .toLowerCAse() → It will convert into lowercase 
                                        // It's not actually going to convert the original object because of Immutability


                                        // .indexof → It will give the index value 

                                        // .lastIndexOf → It will give the last index value 

                                        // .strip() → While spaces are removed. 

                                        // .split() → add a regex first - after adding regex it will split it over those
                                    
                                

Code for palindrome string

                                    

                                        public class Palindrome {
                                            public static void main(String[] args) {
                                                String str = "abcba";
                                                System.out.println(isPalin(str));
                                            }
                                        
                                             static boolean isPalin(String str) {
                                                if( str == null || str.length() == 0) {
                                                    return true;
                                                }
                                                str = str.toLowerCase();
                                                // converts the string into lowercase
                                        
                                                for (int i = 0; i < str.length()/2; i++) {
                                                    char start = str.charAt(i);
                                                    char end = str.charAt(str.length()-1-i);
                                        
                                                    if(start != end)
                                                    return false;
                                                }
                                                return true;
                                            }
                                        }