DEV Community

Cover image for 5 simple and effective Java techniques for strings and arrays
Amanda Fawcett for Educative

Posted on • Edited on • Originally published at educative.io

5 simple and effective Java techniques for strings and arrays

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. The purpose of this post is to give you concise shots of information, known as EdPresso Shots, on how to perform specific actions within the Java framework. In this post we will look at how-to’s related to strings and arrays.

Let’s get started.

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output = The length of the string educative is 9.

Interested in seeing more Java how-to’s? Check out Educative’s Edpresso shots— byte-sized shots of dev knowledge.

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

Enter fullscreen mode Exit fullscreen mode

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));
  }
}
Enter fullscreen mode Exit fullscreen mode

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));
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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));
  }
}
Enter fullscreen mode Exit fullscreen mode

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));
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

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]);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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]);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: When assigning an array to a declared variable, the new keyword must be used.

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]);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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];
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

If you’d like to see more byte-sized EdPresso shots related to Java, Python, C/C++, and many other languages you can visit Educative.io.

Happy learning!


Further readings

Article: Java Multithreading & Concurrency: Cracking senior interview

Article: Learn Java from scratch with these easy steps

Article: Java interview prep: 15 Java interview questions

Course: Learn Object-Oriented Programming in Java

Course: The Definitive Java Interview Handbook

Course Track: Java for Programmers

Course Track: Ace the Java Coding Interview

Top comments (0)