Java routinely hits inside the top five most popular programming languages and understandably so; it’s versatile, fairly easy to learn being that it’s a high-level language, and it satisfies a number of use cases. For these reasons, Java is a great language to learn whether you’re experienced or just starting out your software engineering career.
Java may be a relatively easy language to learn, but that doesn’t mean we don’t have questions from time-to-time, or get stuck, or forget some nuances of the language. In this post we will look at how-to’s related to strings and arrays.
Today, we’ll cover:
compareTo()
method in Java?Get a detailed review of all the common Java data structures Java to prepare for any coding interview.
Data Structures for Coding Interviews in Java
To calculate the length of a string in Java, you can use an inbuilt length()
method of the Java string class.
In Java, strings are objects created using the string class and the length()
method is a public
member method of this class. So, any variable of type string can access this method using the .
(dot) operator.
The length()
method counts the total number of characters in a String.
The signature of the length() method is as follows:
length()
length()
method is int.Class CalcLength {public static void main (string args[]) {string name = "educative"; // initializing a string object nameint length = name.length(); // calling the inbuilt length methodsystem.out.println("The length of the string \""+name+"\" is: " +length);}}
Output = The length of the string “educative” is 9.
The Java compareTo()
method compares the given string lexicographically (order similar to the one in a dictionary) with the current string on the basis of the Unicode value of each character in the strings. This method returns an integer upon its implementation.
The Java lexicographic order is as follows:
There are three cases when the compareTo()
method is used:
The method returns 0 (zero) if the two strings are equivalent.
class MyClass {public static void main (string args[]) {string str1 = "abcd";string str2 = "abcd";system.out.println(str1.compareTo(str2));}}
Output = 0
The method returns a negative number when the string calling the method come lexicographically first.
class MyClass {public static void main (string args[]) {string str1 = "abCd";string str2 = "abcd";system.out.println(str1.compareTo(str2));}}
Output = -32
The method returns a positive number when the parameter passed in the method comes lexicographically first.
class MyClass {public static void main (string args[]) {string str1 = "abcd";string str2 = "abCd";system.out.println(str1.compareTo(str2));}}
Master data structures in JAva without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
The substring()
method in Java returns a portion of a string and is used to get substrings in java.
There are two variants for the substring()
method implementation in Java:
We specify a start index and the returned substring includes characters starting from the specified start index, of the input string, until the end of the string.
The substring function is represented as follows:
stringName.substring(int startindex)
class HelloWorld {public static void main (string args[]) {string str = "edpresso";system.out.println(str.substring(2));}}
Output = presso
We specify the start index and the end index, and the returned substring includes characters including and between the specified indexes. The character at the start index is included, but the character at the end index is not included while getting the substring. So, the characters in the extracted substring begin from start index to end index-1.
The substring function can also be represented as:
stringName.substring(int startIndex, int endIndex)
class HelloWorld {public static void main(string args[]) {string str = "edpresso";system.out.println(str.substring(2,7));}}
Note:
substring()
method does not change the original string.
Declaring an array:
The syntax for declaring an array is: datatype[] arrayName;
datatype
: The type of Objects that will be stored in the array eg. int, char, etc.[ ]
: Specifies that the declared variable points to an arrayarrayName
: Specifies the name of the arrayInitializing an array:
Declaring an array does not initialize it. In order to store values in the array, we must initialize it first, the syntax of which is as follows:
datatype [ ] arrayName = new datatype [size];
There are a few different ways to initialize an array:
1. Initializing an array without assigning values
An array can be initialized to a particular size. In this case, the default value of each element is 0.
class HelloWorld {public static void main(string args[]) {// intializing an arrayint[]array = new int[5];//printing the elements of arrayfor(int i = 0; i < 5; i++){system.out.println(array[i]);}}}
2. Initializing an array after a declaration
class HelloWorld {public static void main(string args[]) {//array declarationint[]array;//array initializationarray = new int[]{1, 2, 3, 4, 5};//printing the elements of arrayfor(int i; i < 5; i++){system.out.println(array[i]);}}}
Note: When assigning an array to a declared variable, the new keyword must be used.
3. Initializing an array and assigning values
class HelloWorld {public static void main(string args[]) {int[]array = {11, 12, 13, 14, 15};//printing the elements of arrayfor(int i = 0; i < 5; i++){system.out.println(array[i]);}}}
Note: When assigning values to an array during initialization, the size is not specified.
Similar to a 1-D array, a 2-D array is a collection of data cells. 2-D arrays work in the same way as 1-D arrays in most ways; however, unlike 1-D arrays, they allow you to specify both a column index and a row index.
All the data in a 2D array is of the same type.
Declaring 2-D arrays
Similar to the 1-D array, we must specify the data type, the name, and the size of the array. The size of a 2-D array is declared by the number of rows and number of columns. For example:
class Testarray {public static void main(string args[]) {int number_of_rows = 6;int number_of_columns = 5;int arr[][] = new int[number_of_rows][number_of_columns];}}
The total number of elements in this 2-D array is:
number_of_rows * number_of_columns
So, the total number elements in arr
are 30.
Initializing a 2-D array
//initializing a 2-D arrayint arr[][] = {{1, 2, 3},{4, 5, 6},{7,8,9}};
Accessing 2-D arrays
Like 1-D arrays, you can access individual cells in a 2-D array by using subscripts that specify the indexes of the cell you want to access. However, you now have to specify two indexes instead of one. The expression looks like this:
arr[2][3] = 5;system.out.println(arr[2][3]); // prints out 5
You can also find the length of a row or a column using the following syntax:
arr[2][].length; // prints length of 3rd rowarr[][0].length; // prints length of 1st column
Congrats! You’ve learned some great techniques for working with strings and arrays. These are foundational to your success as a Java developer. There is still more to learn! To master data structures for coding interview, you’ll need to understand:
To get started with these concepts and mater the skills with hands-on practice, check out Educative’s course Data Structures for Coding Interviews in Java. This course contains a detailed review of all the common data structures and provides implementation level details in Java to allow readers to become well equipped. Now with more code solutions, lessons, and illustrations than ever.
Happy learning!
Free Resources