Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Big Data Hadoop & Spark by (11.4k points)

Assume the following:

String example      = "something";
String firstLetter  = "";


Are there differences to be aware of with the following ways of assigning firstLetter that could impact performance; which would be best, and why?

firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);

1 Answer

0 votes
by (32.3k points)
edited by

I tried all three methods:

  • String.valueOf

  • Character.toString

  • substring

And came to know that the fastest method to get the first letter of any string in Java, based on performance is the “substring” method.

Here is the code:

     String example = "something";

    String firstLetter  = "";

    long l=System.nanoTime();

    firstLetter = String.valueOf(example.charAt(0));

    System.out.println("String.valueOf: "+ (System.nanoTime()-l));

    l=System.nanoTime();

    firstLetter = Character.toString(example.charAt(0));

    System.out.println("Character.toString: "+ (System.nanoTime()-l));

    l=System.nanoTime();

    firstLetter = example.substring(0, 1);

    System.out.println("substring: "+ (System.nanoTime()-l));

Note: nanoTime() - The java.lang.System.nanoTime() method returns the current time value in nanoseconds, basically used to make a comparison between the two methods.

If you want more information regarding the Apache Spark, refer the following link:

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...