Java has gained a lot of respect among programmers because of its object-oriented programming support and pre-defined functions for data types provided. Strings are one of the impressing data types provided by java.
They are immutable and stored on the heap area in a separate memory block called String Constant Pool. There are many pre-defined functions for strings in java, let’s explore them!
To access the character at a particular position we don’t need a loop for iterating to that index, charAt() function does the hard work for you!. The charAt() function returns the character at a particular position in the string, remember that the index starts from 0 in java.
This function is defined with access modifier as public and it returns a char. This method expects an integer as the parameter and accessing the function with a parameter greater than the string length returns an IndexOutOfBounds Exception, which is a runtime exception.
|String str = “hey there“;
char first = str.charAt(0);
char second = str.charAt(1);
The above snippet will give ‘h e’ as output because the variable first is assigned with the character ‘h’ and the variable second is assigned with the character ‘e’.
compareTo() and compareToIgnoreCase()
Comparing two strings will not work with a == operator in java, because it checks if the address of both the variables and returns true if both the variables have the same address. So a == operator fails to compare the content of the strings, here comes the compareTo() method into action.
This public method expects a string or an object as a parameter which is to be compared and returns an integer value after a lexicographic comparison, remember that this method is case sensitive. But we can use compareToIgnoreCase() for a comparison ignoring the lower case and upper case of characters.
|String str1 = “Hello“;
String str2 = “Hello“;
String str3 = “hello“;
int i1 = str1.comapreTo(str2);
int i2 = str2.compareTo(str3);
int i3 = str2.compareToIgnoreCase(str3);
System.out.println(i1+“ “i2+“ “+i3);
The above snippet will print ‘1 0 1’ as output because the variable i1 is assigned with 1 since both the strings are equal, variable i2 is assigned with 0 since we are comparing strings by case sensitivity. Similarly, variable i3 is assigned with 1 since we are comparing the strings by ignoring the upper and lower cases.
Since strings are immutable we cannot edit the value of a string instead we can just reassign the updated value to the same variable. We can use the concat() method for concatenating both strings. This method expects a string as a parameter which is to be concatenated and returns a new concatenated string.
|String s1 = “first “;
String s2 = “second“;
The above snippet prints a string “first second”.
Checking if a string is present as a subsequence of another string is now a cakewalk. contains() method in java is a boolean public function and returns true if a sequence of characters is present in a string and false if not. This method expects a character sequence as the parameter and returns a NullPointerException if a null object is passed as a parameter.
|String s1 = “Hey there“;
The above snippet prints True for line 1 because the sequence “the” is present in the string, similarly line 2 prints True because an empty sequence returns True by default. And line 3 throws a NullPointerException since a null is passed a parameter.
We have seen a java function which returns the character present at a given index, but what if we want the index of the first occurrence of a given character. Relax, indexOf() function does the job. This function is internally overridden with four different signatures, let’s walk through them.
|String s1 = “Hey there, hey There, Hey There, hey there“;
System.out.println(s1.indexOf(“there“)); //line 1
System.out.println(s1.indexOf(“there“,5)); //line 2
System.out.println(s1.indexOf(‘T‘)); //line 3
System.out.println(s1.indexOf(‘T‘,16)); //line 4
In the above snippet, the function called in line1 expects a string and this returns the starting index of the first occurrence of a given string, it prints 4 in this case. The function called in line2 expects a string along with an integer as the parameters, now this integer refers to the starting index where the searching for a given string starts from that index, it prints 37 in this case.
The function called in line3 expects a character as the parameter, it returns the first occurrence of the given character, it prints 15 in this case. Similarly, the function present in line4 expects a character and an integer.
Where the integer represents the starting index and then searching for the given character starts from that character, it prints 26 in this case. Remember that this function is completely case sensitive, which we can see in the above snippet.
This function does a simple task but a very useful one from the programmer’s point of view. This boolean function returns True if the string is empty and False if not. This function helps to check if a string is empty before performing any tasks on the string because few of the functions throw an exception for empty strings which interrupts the flow of execution.
|String s1 = “Hey there“;
String s2 = “”;
Above snippet prints False for line1, and True for line2.
Finding out the length of a string is no more a tedious task, the length() function in java returns the length of the given string. This returns zero if an empty string is passed as a parameter.
|String s1 = “abcdefghijklmnopqrstuvwxyz“;
The above code prints 26.
Unlike the indexOf() function, where it returns only the first occurrence of the sequence, The replace() function replaces all the specified characters with the given new character and returns a new string. This public function expects two characters, say c1 and c2 as the parameters. Where it searches for all characters equal to c1 and replaces them with c2.
|String s1 = “helloHELLO“;
Remember this function is case sensitive, so the above snippet prints “heppoHELLO”.
toLowerCase() and toUpperCase()
Converting a string to lower case or vice versa is a fun task in java, which just needs the art of a single line of code, and toLowerCase(), toUpperCase() functions are the artists.
These public functions expect no parameters and return a new string with the updated lower and upper case of characters.
|String s1 = “Hey There“;
In the above snippet line2 prints “hey there” and line1 prints “HEY THERE”.
A naive approach to remove the trailing and leading white spaces in a string is to loop over the string and remove the character if it is a white space, but there’s an optimal way. The trim() function removes all the leading and trailing spaces of the string and returns a new string. This public function doesn’t expect any parameter.
|String s1 = “ Hey There “;
The above snippet prints “Hey There” which is the new string after trimming the trailing and leading white spaces.
We’ve walked through a few of the string functions in java, understood how they work, what they expect, and what they return. Explored the overridden signatures of few functions, walked through a sample code snippet for a proper understanding. Now that you are aware of a few functions, start utilizing them whenever it is required.
If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
What is the importance of design skills in software development?
From the first idea to the finished product, design encompasses all phases required to develop a product or service. Research, planning, drawing, prototyping, and testing are all part of the process. Design abilities are vital in software development because they enable developers to create user interfaces and interactivity that are both simple to use and pleasing to the eye. Good design skills can also assist developers in writing more efficient code, which can improve the software's overall quality. Design skills can be thought of as the user interface for software development. Design skills contribute to a more user-friendly and efficient software development process.
What is the demand for web developers in the current market?
Web developers are in charge of website design, development, and upkeep. They collaborate with designers and content producers to develop an aesthetically appealing and user-friendly website. Web developers must be well-versed in both front-end and back-end development, as well as the integration of several technologies into a cohesive website. In today's economy, web developers are in high demand. The key reason for this is that companies are increasingly using the internet to reach out to new clients and market their goods and services. As a result, the demand for web developers who can construct and manage websites is increasing.
How can AI replace real developers?
AI refers to a computer program's ability to learn and work independently, making decisions based on data it has analyzed. Artificial Intelligence is employed in the business world for a variety of reasons. It can be used to automate processes, saving both time and money. It can also be used to examine data to aid in decision-making. AI won't be able to take the job of professional developers, but it can help automate some of the work they do. This frees up developers’ time to work on more sophisticated or human-interactive jobs. AI can also assist in identifying potential issues and faults in code and recommending fixes.