Pages

Java String class Methods with example

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and cannot be changed once it has been created. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

The java.lang.String class implements SerializableComparable and CharSequence interfaces.
String in Java

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
CharSequence in Java

Creating a String

There are two ways to create a String in Java
  1. String literal
  2. Using new keyword

String literal:

Java String literal is created by using double quotes.
String s = "RameshQaPlatform";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in
String s1 = "Welcome";
String s2 = "Welcome";
Java string literal

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
By new keyword:
String strObject = new String("Java");
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable strObject will refer to the object in a heap (non-pool).

What is String literal and String Pool

Since String is one of the most used type in any application, Java designer took a step further to optimize uses of this class. They know that Strings will not going to be cheap, and that's why they come up with an idea to cache all String instances created inside double quotes e.g. "Java". These double quoted literal is known as String literal and the cache which stored these String instances are known as as String pool. In earlier version of Java, I think up-to Java 1.6 String pool is located in permgen area of heap, but in Java 1.7 updates its moved to main heap area. Earlier since it was in PermGen space, it was always a risk to create too many String object, because its a very limited space, default size 64 MB and used to store class metadata e.g. .class files. Creating too many String literals can cause java.lang.OutOfMemory: permgen space. Now because String pool is moved to a much larger memory space, it's much more safe. By the way, don't misuse memory here, always try to minimize temporary String object e.g. "a""b" and then "ab". Always use StringBuilder to deal with temporary String object. What is string constant pool?  The string constant pool, often simply referred to as the "string pool," is a special area in memory where string literals are stored. It's a feature in many programming languages, including Java, C#, and Python, that optimizes memory usage by reusing identical string literals instead of creating new instances for each occurrence of the same string.

Here's how the string constant pool works:

  1. String Literal Creation: When you create a string literal in your code (e.g., "hello"), the programming language's compiler or interpreter checks if an identical string already exists in the string pool.

  2. String Reuse: If a matching string literal is found in the pool, the new string literal refers to the existing one rather than creating a new instance. This is possible because strings are immutable; they cannot be modified after creation.

  3. Memory Efficiency: By reusing string literals, the string pool conserves memory, especially in situations where the same string literal is used multiple times throughout the program.

For example, consider the following Java code:

String str1 = "hello"; String str2 = "hello";

In this code, str1 and str2 both refer to the same string literal "hello" in the string pool. Instead of creating two separate string objects, the Java runtime optimizes memory usage by reusing the existing string literal.
String pooling offers benefits in terms of memory efficiency, performance, and even certain optimizations, such as faster string comparison (since you can compare string references rather than their content). However, it's important to note that not all strings are automatically pooled; typically, only string literals are pooled by default. Strings created using the new keyword or by concatenation are not automatically part of the string pool. Some languages also offer mechanisms (e.g., String.intern() in Java) to explicitly add strings to the pool.

Difference between String literal and String object

String literal vs New String in Java
At high level both are String object, but main difference comes from the point that new() operator always creates a new String object. Also when you create String using literal they are interned. This will be much more clear when you compare two String objects created using String literal and new operator, as shown in below example :
String a = "Java";
String b = "Java";
System.out.println(a == b);  // True
Here two different objects are created and they have different references:
String c = new String("Java");
String d = new String("Java");
System.out.println(c == d);  // False
Similarly when you compare a String literal with an String object created using new() operator using == operator, it will return false, as shown below :
String e = "JDK";
String f =  new String("JDK");
System.out.println(e == f);  // False
In general you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code. By the way any answer to this question is incomplete until you explain what is String interning, so let's see that in next section.

String interning using intern() method

Java by default doesn't put all String object into String pool, instead they gives you flexibility to explicitly store any arbitrary object in String pool. You can put any object to String pool by calling intern() method of java.lang.String class. Though, when you create using String literal notation of Java, it automatically call intern() method to put that object into String pool, provided it was not present in the pool already. This is another difference between string literal and new string, because in case of new, interning doesn't happen automatically, until you call intern() method on that object. Also don't forget to use StringBuffer and StringBuilder for string concatenation, they will reduce number
Here's a Java example that demonstrates string interning:
String str1 = "hello"; String str2 = new String("hello").intern(); System.out.println(str1 == str2); // true In this example, str1 and str2 both refer to the same string literal in the string pool because str2 was explicitly interned using the intern() method.
Always remember that literal Strings are returned from string pool and Java put them in pool if not stored already. This difference is most obvious, when you compare two String objects using equality operator (==). That's why it's suggested as always compare two String object using equals() method and never compare them using == operator, because you never know which one is coming from pool and which one is created using new() operator.
What are the differences between equals() and == in Java?

Answer: In Java, equals() is a method used to compare the content or values of two objects, while == is used to compare the references or memory addresses of two objects. Here's an example:

public class EqualsExample {
public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "Hello";
    String str3 = new String("Hello");

    System.out.println(str1.equals(str2)); // Output: true
    System.out.println(str1 == str2);  // Output: true

    System.out.println(str1.equals(str3)); // Output: true
    System.out.println(str1 == str3);  // Output: false
}
}

How does garbage collection work in Java? 

Answer: 

Garbage collection in Java automatically reclaims memory that is no longer in use by the program. It works by identifying objects that are no longer reachable through references and freeing up the memory occupied by those objects. The Java Virtual Machine (JVM) has a built-in garbage collector that runs periodically, determining which objects are no longer needed and reclaiming their memory.


Why strings are immutable?

Strings are immutable in many programming languages, including Java, C#, Python, and others, due to several important reasons:
1)Efficiency and Performance: Immutable strings are more memory-efficient and faster in certain operations. When a string is created, it can be stored in a memory pool, and subsequent strings with the same value can reference the same memory location, reducing memory usage. Additionally, because strings are immutable, they can be cached and shared among multiple threads safely, improving performance.
2)Thread Safety: Immutable strings are inherently thread-safe. In a multi-threaded environment, if one thread tries to modify a string, it cannot change the original string's content. This immutability simplifies concurrent programming and eliminates the need for explicit synchronization when working with strings.
3)Security: Immutable strings enhance security. For example, when strings are used to store sensitive information like passwords or security tokens, their immutability ensures that once set, their values cannot be changed accidentally or maliciously.
4)Hashing and Caching: Immutable strings are suitable for use as keys in hash tables (e.g., dictionaries) because their hash codes remain constant. If a string were mutable, and its value changed after being used as a key, it could lead to inconsistencies in data retrieval.
5)Consistency: Immutability ensures that a string's value remains consistent throughout its lifetime. This predictability is crucial in maintaining program correctness and making debugging easier.
6)Functional Programming: In functional programming paradigms, immutability is a fundamental concept. Immutable strings align well with functional programming principles, allowing for more predictable and maintainable code.
7)String Pooling: Many programming languages implement string pooling, where common string literals are interned or shared to reduce memory usage. Immutability makes this pooling mechanism more effective because identical string literals can safely reference the same memory location
8)Optimizations: Immutable strings allow compilers and runtime environments to perform various optimizations. For instance, they can avoid redundant string copying operations, leading to better performance.
While immutability offers several advantages, it's essential to note that there may be situations where mutable strings are more suitable, such as when you need to frequently modify the content of a string in-place for performance reasons. In such cases, mutable string-like data structures, like StringBuilder in Java, can be used. However, these mutable alternatives come with trade-offs in terms of thread safety and memory management.


String Methods:

1)int length(): Returns the number of characters in the String.
"Qaplatform".length();  // returns 10
2)Char charAt(int i): Returns the character at ith index.
"QAPlatform".charAt(3); // returns  ‘l’
3)String substring (int i): Return the substring from the ith  index character to end.
"QAPlatform".substring(3); // returns “latform”
4)String substring (int i, int j): Returns the substring from i to j-1 index.
 "QAPlatform".substring(2, 5); // returns “Pla”
5)String concat( String str): Concatenates specified string to the end of this string.
 String s1 = ”QaAutomation”;
 String s2 = ”Platform”;
 String output = s1.concat(s2); // returns “QaAutomationPlatform”
6)int indexOf (String s): Returns the index within the string of the first occurrence of the specified string.
 String s = ”Learn Share Learn”;
7)int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string, starting at the specified index.
 String s = ”Learn Share Learn”;
 int output = s.indexOf("ea",3);// returns 13
8)Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string.
 String s = ”Learn Share Learn”;
 int output = s.lastIndexOf("a"); // returns 14
9)boolean equals( Object otherObj): Compares this string to the specified object.
 Boolean out = “platform”.equals(“platform”); // returns true
 Boolean out = “Platform”.equals(“platform”); // returns false
10)boolean  equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case considerations.
 Boolean out= “Platform”.equalsIgnoreCase(“Platform”); // returns true
 Boolean out = “QaPlatform”.equalsIgnoreCase(“qaplatform”); // returns true
11) int compareTo( String anotherString): Compares two string lexicographically.
 int out = s1.compareTo(s2);  // where s1 ans s2 are
                             // strings to be compared
 This returns difference s1-s2. If :
 out < 0  // s1 comes before s2
 out = 0  // s1 and s2 are equal.
 out > 0   // s1 comes after s2.
12)int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case considerations.
 int out = s1.compareToIgnoreCase(s2);  
// where s1 ans s2 are 
// strings to be compared
 This returns difference s1-s2. If :
 out < 0  // s1 comes before s2
 out = 0   // s1 and s2 are equal.
 out > 0   // s1 comes after s2.
Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).
13)String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"
14)String toUpperCase(): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”
15)String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
16)String replace (char oldChar, char newChar): Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “javaselenium“;
String s2 = s1.replace(‘a’ ,’@’); // returns “j@v@selenium”
This replace method in String takes one character and replaces all of its occurrence in provided
String with new character provided to it. Here is an String replace Example of changing character
String replaceSample = "This String replace Example shows how to replace one char from String";
String newString = replaceSample.replace('r', 't');
Output: This Stting teplace Example shows how to teplace one chat ftom Stting
You can see all occurrence of "r" has been replaced by "t".
Important points:
1. This replace method of String will return a new String object if there is a replace.
2. It will return same String objects if there is no matching char and there is no replace.
3. Replacement of String is Case Sensitive, so replacing "c" will only replace small case not Capital Case.
2. Replace method to replace character sequence in String
replace(CharSequence target, CharSequence replacement)
This String replace method replaces one character sequence with other. This method has added from JDK 1.5 onwards. Here is a String replace example of replacing character sequence form String
String replaceSample = "String replace Example of replacing Character Sequence";
String newString = replaceSample.replace("re", "RE");
Output: String REplace Example of REplacing Character Sequence
In this String replace Example, we have replaced "re" with "RE".
Important points:
1) This String replace method will throw NullPointerException if either oldCharSequence or newCharSequence is null.
2) Replacement of String starts from beginning and proceed towards end. So in a String "ccc" replacing "cc" with "d" will result in "dc" rather than "cd".
3. Replace method to replace all matched pattern in String
replaceAll(String regex, String replacement)
Good thing about replace method of String Class in Java is that it supports regular expression. With regex capability you can perform sophisticated Search on String and than replace characters. This String replace method replaces each matched substring with the replacement String provided. Let's see String replace example with regular expression:
String replaceSample = "String replace Example with regular expression";
String newString = replaceSample.replaceAll("^S","R");
Output: Rtring replace Example with regular expression
This String replace replaces any "S" wiht "R" if it comes at beginning of line "^" denotes beginning of line you can also apply pattern matching wildcards and charset while replacing String in Java.
Important points:
1. This String replace method will throPatternSyntaxException in case regular expression's syntax is not valid.
4. Replace method to replace first matched pattern in SString
replaceFirst(String regex, String replacement)
This String replace method is similar to above method but it only replaces first occurrence of matching pattern instead of all occurrence. Very handy some time. Here is an example of String replace with replaceFirst() method.
String replaceSample = "String replace Example with replaceFirst";
String newString = replaceSample.replaceFirst("re","RE");
Output: String REplace Example with replaceFirst
You can see only first occurrence of "re" is replaced with "RE" while second occurrence remains same
17)boolean contains(CharSequence s):returns true or false after matching the sequence of char value.
18)boolean isEmpty():checks if string is empty.

isEmpty():

  • This method checks if the string is empty, meaning it has a length of 0.

  • It returns true if the string is empty, false otherwise.

  • Example:

  • String str = ""; System.out.println(str.isEmpty()); // Output: true String str2 = "Hello"; System.out.println(str2.isEmpty()); // Output: false

isBlank():

  • This method checks if the string is empty or consists only of whitespace characters (e.g., spaces, tabs, line breaks).

  • It returns true if the string is empty or contains only whitespace, false otherwise.

  • Example:

  • String str = " "; System.out.println(str.isBlank()); // Output: true String str2 = "Hello"; System.out.println(str2.isBlank()); // Output: false

  • In summary, isEmpty() checks if the string has a length of 0, while isBlank() checks if the string is empty or contains only whitespace characters. Use isEmpty() when you want to check for an empty string specifically, and use isBlank() when you want to check for a string that is empty or consists only of whitespace characters.

    String s8 = "null"; String s9 = null; System.out.println(s8.isBlank()); System.out.println(s8.isEmpty());
  1. For s8, which is "null", the following will be the output:

    • s8.isBlank() will return false. This is because although "null" contains characters, it is not considered blank because it contains non-whitespace characters.
    • s8.isEmpty() will return false. This is because "null" has a length of 4, so it is not considered empty.
  2. For s9, which is null (not the string "null" but a null reference):

    • If you try to call isBlank() or isEmpty() on s9, you will get a NullPointerException because you cannot call methods on a null reference.

If you want to check if a string is "null" (the string literal), you can compare it directly like this:

if ("null".equals(s8)) { // s8 is the string "null" }

Or if you want to check if a string is null (not the string literal "null"), you can do this:
if (s9 == null) { // s9 is null }

19)char[] toCharArray(): Converts the given String into char[]
20)byte[] getBytes(): method returns the byte array of the string. In other words, it returns sequence of bytes.
21)String valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
Syntax:
  1. public static String valueOf(boolean b)  
  1. public static String valueOf(char c)  
  1. public static String valueOf(char[] c)  
  1. public static String valueOf(int i)  
  1. public static String valueOf(long l)  
  1. public static String valueOf(float f)  
  1. public static String valueOf(double d)  
  1. public static String valueOf(Object o) 

22)String join() method returns a string joined with given delimiter. In string join method, delimiter is copied for each elements.
===============================================

Java StringBuffer class:

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class
ConstructorDescription
StringBuffer()creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str)creates a string buffer with the specified string.
StringBuffer(int capacity)creates an empty string buffer with the specified capacity as length.
Important methods of StringBuffer class
Modifier and TypeMethodDescription
public synchronized StringBufferappend(String s)is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBufferinsert(int offset, String s)is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public synchronized StringBufferreplace(int startIndex, int endIndex, String str)is used to replace the string from specified startIndex and endIndex.
public synchronized StringBufferdelete(int startIndex, int endIndex)is used to delete the string from specified startIndex and endIndex.
public synchronized StringBufferreverse()is used to reverse the string.
public intcapacity()is used to return the current capacity.
public voidensureCapacity(int minimumCapacity)is used to ensure the capacity at least equal to the given minimum.
public charcharAt(int index)is used to return the character at the specified position.
public intlength()is used to return the length of the string i.e. total number of characters.
public Stringsubstring(int beginIndex)is used to return the substring from the specified beginIndex.
public Stringsubstring(int beginIndex, int endIndex)is used to return the substring from the specified beginIndex and endIndex.

===============================================

Difference between String and StringBuffer:

There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
No.StringStringBuffer
1)String class is immutable.StringBuffer class is mutable.
2)String is slow and consumes more memory when you concat too many strings because every time it creates new instance.StringBuffer is fast and consumes less memory when you cancat strings.
3)String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.StringBuffer class doesn't override the equals() method of Object class.

Difference between StringBuilder and StringBuffer:

No.StringBufferStringBuilder
1)StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)StringBuffer is less efficient than StringBuilder.StringBuilder is more efficient than StringBuffer.
3)StringBuffer was introduced in Java 1.0StringBuilder was introduced in Java 1.5


=========================================================================
                                  String                    StringBuffer         StringBuilder
--------------------------------------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
--------------------------------------------------------------------------------------------------------------------------
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
---------------------------------------------------------------------------------------------------------------------------
Thread Safe   |           Yes                                  Yes                              No
---------------------------------------------------------------------------------------------------------------------------
 Performance |         Slow                       Slow but faster             Fast

                                                                   than String     
--------------------------------------------------------------------------------------------------------------



What is mutable string














Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.

5 Reasons of Why String is final or Immutable in Java

Why String class is made Immutable or Final in JavaThough true reasons of why String class was made final is best known to Java designers, and  apart from that hint on security by James Gosling, I think following reasons also suggest Why String is Final or Immutable in Java.

1. String Pool
Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from start. One of key step on that direction was idea of storing String literals in the String pool. The goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties that are unknown to each other. Let's take a hypothetical example, where two reference variable is pointing to same String object:

String s1 = "Java";
String s2 = "Java";

Now if s1 changes the object from "Java" to "C++", the reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, the key idea of the String pool can not be implemented without making String final or Immutable in Java.


2. Security
Java has a clear goal in terms of providing a secure environment at every level of service and String is critical in that whole security stuff. The string has been widely used as a parameter for many java classes, like for opening network connection, you can pass host and port as String, for reading files in Java you can pass the path of files and directory as String, and for opening database connection, you can pass database URL as String. 

If String was not immutable, a user might have granted to access a particular file in the system, but after authentication, he can change the PATH to something else, this could cause serious security issues. 

Similarly, while connecting to a database or any other machine in the network, mutating the String value can pose security threats. Mutable strings could also cause security problems in Reflection as well, as the parameters are strings.


3. Use of String in Class Loading Mechanism
Another reason for making String final or Immutable was driven by the fact that it was heavily used in the class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading the correct classes.


4. Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about the thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, which means much cleaner code involving sharing of String between multiple threads

This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.


5. Optimization and Performance
Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantees open path for many performance optimization e.g. caching. String itself knows that I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. 

In a simple world, when you first call hashCode() method of any String object, it calculates hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String, is heavily used in hash-based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.


Pros and Cons of String being Immutable or Final in Java

Apart from the above benefits, there is one more advantage that you can count on due to String being final in Java. It's one of the most popular objects to be used as a key in hash-based collections e.g. HashMap and Hashtable. Though immutability is not an absolute requirement for HashMap keys, its much safer to use Immutable object as key than mutable ones, because if the state of a mutable object is changed during its stay inside HashMap, it would be impossible to retrieve it back, given its equals() and hashCode() method depends upon the changed attribute. 

If a class is Immutable, there is no risk of changing its state, when it is stored inside hash-based collections.  Another significant benefit, which I have already highlighted is its thread safety. Since String is immutable, you can safely share it between threads without worrying about external synchronization. It makes concurrent code more readable and less error-prone.

Despite all these advantages, Immutability also has some disadvantages, e.g. it doesn't come without cost. Since String is immutable, it generates lots of temporary use and throw object, which creates pressure for the Garbage collector. Java designer has already thought about it and storing String literals in pool is their solution to reduce String garbage. 

It does help, but you have to be careful to create String without using constructor e.g. new String() will not pick an object from String pool. Also on average Java application generates too much garbage. Also storing Strings in pool has a hidden risk associated with it. String pool is located in PermGen Space of Java Heap, which is very limited as compared to Java Heap. 

Having too many String literals will quickly fill this space, resulting in java.lang.OutOfMemoryError: PermGen Space. Thankfully, Java language programmers has realized this problem and from Java 7 onwards, they have moved String pool to normal heap space, which is much much larger than PermGen space. 

There is another disadvantage of making String final, as it limits its extensibility. Now, you just can not extend String to provide more functionality, though more general cases its hardly needed, still its limitation for those who wants to extend java.lang.String class.

-------------------------------------------------------------------------------------------------------------------------
GIVEN A STRING, RETURN THE LENGTH OF THE STRING USING RECURSION java
public class StringLengthRecursion {

    public static int calculateLength(String str) {
        // Base case: if the string is empty, return 0
        if (str.isEmpty()) {
            return 0;
        } else {
            // Recursive case: call the function with the substring excluding the first character
            return 1 + calculateLength(str.substring(1));
        }
    }

    public static void main(String[] args) {
        String inputString = "Hello, World!";
        int length = calculateLength(inputString);
        System.out.println("Length of the string: " + length);
    }
}
In this example, the calculateLength method takes a string as input. If the string is empty, it returns 0 (base case). Otherwise, it adds 1 to the length and recursively calls itself with the substring excluding the first character. This process continues until the base case is reached.
-------------------------------------------------------------------------------------------
GIVEN AN INTEGER, RETURN TRUE IF THE INTEGER IS A PALINDROME. in java

public class PalindromeCheck {
public static boolean isPalindrome(int num) { // Convert the integer to a string String strNum = Integer.toString(num); // Use two pointers to check if the string is a palindrome int left = 0; int right = strNum.length() - 1; while (left < right) { if (strNum.charAt(left) != strNum.charAt(right)) { return false; } left++; right--; } return true; } public static void main(String[] args) { int num = 12321; // Change this to test different integers if (isPalindrome(num)) { System.out.println(num + " is a palindrome."); } else { System.out.println(num + " is not a palindrome."); } } }

This program converts the integer to a string and then uses two pointers (one starting from the beginning and the other from the end) to check if the characters are the same. If at any point the characters are different, the number is not a palindrome. Otherwise, it is a palindrome.
---------------------------------------------------------------------------------------------------------------------------
QUIZ on Strings:
1)guess the output
package strings;

public class Test {

public static void main(String[] args) {
String a="newspaper";
a=a.substring(5, 7);
char b= a.charAt(1);
a = a + b;
System.out.println(a);

}

}
1)app
ii)spa
iii)pap
------------------------------------------------------------------------------------------------------
/**
 * Write a program to print "Welcome" on Console without using Quotes like (" , ')
 * @author rames
 *
 */

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.