Friday, December 30, 2011

String and StringBuffer

Strings:

A string is a sequence of characters. Strings are not primitive types in Java; they are objects. Strings are constant; their values cannot be changed after they are created. Because String objects are immutable they can be shared.

Creating the String object:

There are several ways to construct a string, an object of String.

  1. String name=”JSLTech”;
  2. String name=new String(“JSLTech”);
  3. char[] cname=new char[]{'J','S','L','T','E','C','H'};  String name=new String(cname);
The JVM stores string literals in a special memory called the string pool. Because String objects are immutable, instances in the string pool can be shared.

Example:

package com.jsl.core.book;
public class StringDemo {
public static void main(String[] args) {
                    
                    String name="JSLTech";
                    String fname="JSLTech";
                    System.out.println(name==fname);
            }
}

The output is true; here the string object is created by the JVM and stories into String constant pool. If try to create another object, first JVM checks in the constant pool with same content object is existing or not, if existing it return the same object otherwise it create new object.

== and equals:

== operator compares the weather two reference variables are pointing to the same object or not, if both are pointing to the same objects then it returns true otherwise returns false.

equals() :

The equals method compares the content of the objects, if both objects content is same then it reutrns true otherwise returns false.

Note: equals( ) method is java.lang.Object class method. By default this method return true if the both reference variables pointing to the same object. If objects has compare the content then that class must override the equals method. String class is api class they have overridden the equals method.


Example:

package com.jsl.core.book;
public class StringDemo {
public static void main(String[] args) {
     
                  String name=new String("JSLTech");
                  String fname=new String("JSLTech");
                  
                  System.out.println(name==fname);
            
                                        /* Returns false because name,fname are two different object */
                 
                  System.out.println(name.equals(fname));

                                      /* Teturns true, the equals method compare the content of the object */
           }
}

The user defined class to compare the content we must override the equals method , for example

package com.jsl.core.book;
class Product{
        
              private int pid;
              private String name;
        
             Product(int pid,String name){
                           
                                    this.pid=pid;
                                    this.name=name;
             }
           @Override
             public boolean equals(Object obj) {

                                    if(this==obj)
                                    return true;
                                    if(obj instanceof Product){

                                    Product p=(Product)obj;
                                    if(p.pid==this.pid && p.name.equals(name))
                                    return true;
            }
            return false;
          }
}
public class StringDemo {
        public static void main(String[] args) {
              
                     Product p1=new Product(1001,"Dell-Inspiron");
                     Product p2=new Product(1001,"Dell-Inspiron");
                     Product p3=new Product(1002,"Dell-XPS");

                     System.out.println(p1.equals(p2));
                     System.out.println (p1.equals(p3));
                     System.out.println(p2.equals(p3));
         }
}


o/p:
     true
     false
     false

String class methods:

The following methods are some of the more commonly used methods in the String class, and also see the more methods in java api doc.

char charAt(int index): Returns the char value at the specified index.

int compareTo(String anotherString): Compares two strings lexicographically.

int compareToIgnoreCase(String str): Compares two strings lexicographically, ignoring case differences.

String concat(String str): Concatenates the specified string to the end of this string.

Boolean contains(CharSequence s): Returns true if and only if this string contains the specified equence of char values.

boolean contentEquals(CharSequence cs): Returns true if and only if this String represents the same sequence of char values as the specified sequence.

boolean endsWith(String suffix): Tests if this string ends with the specified suffix.

boolean equals(Object anObject): Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString): Compares this String to another String, ignoring case considerations.

int hashCode(): Returns a hash code for this string.

String replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replace(CharSequence target, CharSequence replacement): Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

String replaceAll(String regex, String replacement): Replaces each substring of this string that matches the given regular expression with the given replacement.

String substring(int beginIndex): Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.

char[] toCharArray(): Converts this string to a new character array.

String toLowerCase(): Converts all of the characters in this String to lower case using the rules of the default locale.

String toLowerCase(Locale locale): Converts all of the characters in this String to lower case using the rules of the given Locale.

String toString(): This object (which is already a string!) is itself returned.

String toUpperCase(): Converts all of the characters in this String to upper case using the rules of the default locale.

String trim(): Returns a copy of the string, with leading and trailing whitespace omitted.

/* program to demonstrate the string methods*/

package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {

                   String message="hi welcome to JSLTech.com";
                   System.out.println("The original String :"+message);
                   System.out.println("The upper case String :"+message.toUpperCase());
                   System.out.println("The company name : "+message.substring(14,21));
         System.out.println("The company name length is :"+message.substring(14,21).length());
                   System.out.println("The hi repalce to hello :"+message.replace("hi", "hello"));
                  }
}

Output:

         The original String :hi welcome to JSLTech.com
         The upper case String :HI WELCOME TO JSLTECH.COM
         The company name : JSLTech
         The company name length is :7
         The hi repalce to hello :hello welcome to JSLTech.com

/* program to demonstrate the string methods*/

package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {
         
                         String message="Welcome";
                         System.out.println(message.concat(" To Bangalore" ));
                         System.out.println(message);
            }
}

Output:

          Welcome To Bangalore
          Welcome

Here first message=”Welcome” object will be created by the JVM in constant pool, then concat method is called on message object, the JVM will create new object with the “Welcome to Bangalore”.
                String message="Welcome";
                System.out.println(message.concat(" To Bangalore" ));
                System.out.println(message);

But no reference variable is holding the object “Welcome to Bangalore”, then it prints the object content and its available for garbage collector. Next printf statement the object content will be printed.

/* program to demonstrate the string methods*/

package com.jsl.core.book;
public class MainClass {
public static void main(String[] args) {

                     String s1="Welcome to Bangalore";
                     String s2="Welcome to ";
                     s2=s2.concat("Bangalore");

                     System.out.println("The content of the s1: "+s1);
                     System.out.println("The content of the s2: "+s2);
                     System.out.println("The first String length :"+s1.length());
                     System.out.println("The second String length :"+s2.length());

                     if(s1==s2)
                                 System.out.println("Both are same");
                    else
                                System.out.println("Not same ");

            }
}

String s1="Welcome to Bangalore";
String s2="Welcome to ";
s2=s2.concat("Bangalore");

When concat method is invoked on S2 then the JVM create the new object with new operator, Even content of the objects are same but they are two different objects, so the output prints as “Not same”.

The StringBuilder and StringBuffer Classes

The java.lang package contains two classes for representing strings as a mutable sequence of characters: StringBuilder and StringBuffer. The StringBuffer class has been around since the first version of Java, while StringBuilder was added in J2SE 5.0. The two classes have the exact same method signatures and constructor parameters. The only difference between them is that StringBuffer is thread-safe and StringBuilder is not. If you are working with arrays of characters in a multithreaded application, use the StringBuffer class. Otherwise, if threads are not an issue for your particular situation, use the String-
Builder class.
StringBuufer Object creation:

                StringBuffer sb = new StringBuffer("Hello Dear!");

You can also pass in a String reference as a variable:

                  String str = "Hello Dear!";

                  StringBuffer sb = new StringBuffer(str);


StringBuffer class methods:

StringBuffer append(String str): Appends the specified string to this character sequence.

int capacity(): Returns the current capacity.

char charAt(int index): Returns the char value in this sequence at the specified index.

StringBuffer delete(int start, int end): Removes the characters in a substring of this sequence.

StringBuffer deleteCharAt(int index): Removes the char at the specified position in this sequence.

StringBuffer insert(int offset, Object obj): Inserts the string representation of the Object argument into this character sequence.

StringBuffer insert(int offset, String str): Inserts the string into this character sequence. Returns the index within this string of the last occurrence of the specified substring.

int length(): Returns the length (character count).

StringBuffer replace(int start, int end, String str): Replaces the characters in a substring of this sequence with characters in the specified String.

StringBuffer reverse(): Causes this character sequence to be replaced by the reverse of the sequence.

String substring(int start): Returns a new String that contains a subsequence of characters currently contained in this character sequence.

String substring(int start, int end): Returns a new String that contains a subsequence of characters currently contained in this sequence.

String toString(): Returns a string representing the data in this sequence.

StringBuffer StringBuilder

A thread-safe, mutable sequence of characters Not thread-safe, mutable sequence of characters All the methods are synchronized Methods are not synchronized


/* program to demonstrate the stringBuffer methods*/

package com.jsl.core.book;
public class StringBufferDemo {
public static void main(String[] args) {
    
                  StringBuffer sb=new StringBuffer("Wlcome");
                  System.out.println(sb);
                  System.out.println(sb.append(" to JSLTech"));
                  System.out.println(sb);
       }
}

The output:

               Wlcome
               Wlcome to JSLTech
               Wlcome to JSLTech

Task

1. Write a program to accept string from user and display the length of the string. Also display the string into uppercase and lower case and check whether it is a palindrome or not?
2. Write a program to accept the string from the user and count the number of vowels and consonants in the given string?
3. Write a program to create the class with
     
      firstName
      middleName
      lastName

When you call the display() it should display full name with ‘ _’ separator.

Example:
               firstnName=”Miani”
               middleName=”ites”
               lastName=”education”

                  output:” miani-ites-education”
4. Write a program to search for a string in a given group of strings?

               String s=”miani,lakshman.java,malli,narayana”;
               searchString sc=”narayan”

                output: found at position 4
5. Write a program to accept the string and find the
   
               1. No. of letters
               2. No. of digits
               3. No. of whitespaces

Example: “I am in Bangalore my house number is 6 and my phone no. 9632133889”.

Java final keyword

final (keyword)


In Java, final keyword is applied in various contexts.
1. If class is marked as final that class cannot be inherited

2. If method is marked as final that method cannot be overridden

3. If the variable is declared as final then the value can’t be changed or reassigned

4. If the Arguments of a method declared as final those variables cannot be modified within the method.

                                  final int i=10;

The variable i declared as final only once we can assign the value. If try to modify it leads to the compilation error.

                                  final int var;


The final variables won’t be initialized with default values by JVM. It’s compulsory we should perform initialization before compilation of the constructor.

/* Program to demonstrate the blank final variables */

package com.jsl.core.book;
public class FinalKeywordExample {

 final int var; // Blank final variables.

 public FinalKeywordExample() {

  var = 100;
 }

 public void display( ){
     
  System.out.print(“The value of final variable is :”+var); 
        }
}
/* Program to demonstrate the final local variables */

package com.jsl.core.book;
import java.util.Scanner;

public class FinalKeywordExample {

public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the no : ");
  int no = sc.nextInt();
  double res = factorialOfNumber(no);
  System.out.println("The factorial of : " + res);
 }

 private static double factorialOfNumber(final double no) {

  double res = 1;
  for (int i = 1; i <= no; i++)
   res = res * i;
  return res;
 }
}

The static final variable must be initialized when it is declared or must be initialized inside the static block.

/* Program to demonstrate the static final variables */

package com.jsl.core.book;
public class FinalKeywordExample {
        
                       private final static int var1=5;
                       private final static int var2; // Blank static final variable. 

                       static{
                                     var2=10;
                        }

public static void main(String[] args) {
             
                         System.out.println("The product of "+var1+" and "+var2+" = "+(var1*var2));
              }
}

If the final variable is declared inside the method that variable must be initialized before using, otherwise its leads to the compilation error.

public void showNumber( ){

                        final int no;
                        System.out.print(“The value of no is : “+no)
                       //Its leads to the compilation error. The local variable no must be initilzed before using.
}

/* Program to demonstrate final local variables */

package com.jsl.core.book;
public class FinalKeywordExample {

            public static void showNumber(){

                               final int no=100;
                               System.out.println("The value of no is : "+no);
}

public static void main(String[] args) {
             
                             showNumber();
             }
}

final methods:

The final keyword prevents a method from being overridden in a subclass, normally if methods, not necessary to change the functionality, then those methods can be marked as final.


public final void getSimpleInterest( ){
            
                          body
                           -----------------

}

/* program to demonstrate the final methods */

package com.jsl.core.book;
public class FinalKeywordExample {

              public final static double calSimpleInterest(double p,double t,double r){
              
                             return (p*t*r)/100;
              }
}

/* Main class to access the methods */

package com.jsl.core.book;
public class MainClass {

public static void main(String[] args) {
                   
                           Double interest=FinalKeywordExample.calSimpleInterest(100000, 12, 1);
                           System.out.println("The interest is : "+interest);
         }
}

final reference variable:

final reference variables cannot refer to a different object once the object has been assigned to the final variable. final reference variables must be initialized before the constructor completes.

There is no such thing as a final object. An object reference marked final does not mean the object itself is immutable. That object allows you to make the modification and behaves like a mutable object.


/* program to demonstrate the final reference variables */ 

package com.jsl.core.book;
public class MainClass {
                   
                   public static void main(String[] args) {
                   final String fname=new String("Lakshman");
                   fname=new String("JSLTech");
                  // Leads compilation error. The final reference variable can be assigned only once.
            }
}

final classes:

A final class cannot be sub classed i.e. that classes can’t be inherited. If classes is declared as final then all that class methods behave like final methods.

/* Program to demonstrate the final classes */

package com.jsl.core.book;
          
          public final class FinalKeywordExample {
          private FinalKeywordExample(){
}
public static double calSimpleInterest(double p,double t,double r){
            
           return (p*t*r)/100;
}
public static double currencyConversion(final int amount,final int price){
              
           return amount*price;
      }
} 
/* Main class to access the final class methods */

package com.jsl.core.book;
public class MainClass {

                public static void main(String[] args) {
                System.out.println(FinalKeywordExample.calSimpleInterest(100000,10, 1.50));
                System.out.println(FinalKeywordExample.currencyConversion(5000,68));
       }
}

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...