Home/Blog/5 simple and effective Java techniques for strings and arrays

5 simple and effective Java techniques for strings and arrays

May 06, 2019 - 6 min read
Educative
editor-page-cover

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:



Succeed in your Java interview.

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



How to find the length of a string 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:

  • Public int length()
  • The return type of the length() method is int.

Example:

Class CalcLength {
public static void main (string args[]) {
string name = "educative"; // initializing a string object name
int length = name.length(); // calling the inbuilt length method
system.out.println("The length of the string \""+name+"\" is: " +length);
}
}

Output = The length of the string “educative” is 9.


How to compare strings using the compareTo() method in Java?

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:

  • Numbers
  • Uppercase
  • Lowercase

There are three cases when the compareTo() method is used:


Case 1: Both strings are lexicographically equivalent

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


Case 2: String calling method is lexicographically first

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


Case 3: Parameter passed in the method comes lexicographically first

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));
}
}

This number represents the difference between the Unicode values of the string passed as the input parameter, str2, and the string, str1 calling the method.

result = Unicode of str2 - Unicode of str1



Keep the learning going.

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.

Data Structures for Coding Interviews in Java


How to get a substring in Java

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:


Variant 1

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


Variant 2

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.


How to initialize an array in Java

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 array
  • arrayName: Specifies the name of the array

Initializing 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 array
int[]array = new int[5];
//printing the elements of array
for(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 declaration
int[]array;
//array initialization
array = new int[]{1, 2, 3, 4, 5};
//printing the elements of array
for(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 array
for(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.


How to use 2-D arrays in Java

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 array
int 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
  • 2 is the row index
  • 3 is the column index
  • 5 is the value at this index

You can also find the length of a row or a column using the following syntax:

arr[2][].length; // prints length of 3rd row
arr[][0].length; // prints length of 1st column

What to learn next

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:

  • Complexity measures (Big-O)
  • Linked lists
  • Liked lists with tails
  • Stacks and Queues
  • Graphs and traversal algorithms
  • Balancing trees
  • Types of trees in Java
  • Using tries
  • Heaps
  • Hash tables
  • and more

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!


Continue reading about Java and data strictures


WRITTEN BYEducative

Join a community of more than 1.4 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.