HomeAbout Me

String fundamentals in Java

By Arvind Pandey
Published in Programming
May 09, 2020
1 min read

What is a String?

Observe the below picture for a good 10 seconds.

"Char cloud"
"Char cloud"
Figure 1.1

What do you see?

  1. Lot of characters?
  2. Do you see any meaning in them? hmmm for some character yes.

Next game. Now, let’s arrange those characters in such a way that it becomes arvind. What? Yes, you get my name.

Let’s arrange in such a way that it becomes darvin, may be someone else’s name.

Anyway, thanks for playing.

WTF is your point Arvind?

My point is, when you arrange characters in certain way they become more meaninful. When you put together those characters they are also called String in some world. They does not need to be meaningful though. But let’s not fail to define formal definition of String.

Array of characters is called String.

How to create String in Java

This is how one can create String in Java.

String name = "arvind";

There is another way to create String using new keyword.

String name = new String("arvind");

Important methods and fields in String

When working with String, it’s good to know some inbuilt methods and fields that would come handy when wrting code.

  1. length() returns length of the string
String name = "arvind";
System.out.println(name.length()); // Prints => 6
  1. charAt(int i) return character at the index i
String name = "arvind";
System.out.println(name.charAt(0)); // Prints => a
  1. concat(String s) concat the string s
String name = "arvind";
String fullName = name.concat(" pandey");
System.out.println(fullName);  // Prints => arvind pandey
  1. toCharArray() convert string to character array
String name = "arvind";
char[] nameArr = name.toCharArray();  // Converts to char array
  1. codePointAt(int i) the code point value of the character at the index i
String name = "arvind";
System.out.println(name.codePointAt(0));  // Prints => 97
  1. contains(String s) true if this string contains s, false otherwise
String name = "arvind";
System.out.println(name.contains("a")); // Prints => true
System.out.println(name.contains("b")); // Prints => false
  1. toUpperCase() the String, converted to uppercase
String name = "arvind";
System.out.println(name.toUpperCase());  // Prints => ARVIND
  1. toLowerCase() the String, converted to lowercase
String name = "Arvind Pandey";
System.out.println(name.toLowerCase()); // Prints => arvind pandey

There is huge list of other important methods inside String class. I leave it to you to explore further.

Hope you liked this tutorial. You might also like other tutorials in this series here


Tags

#ds#programming#java
Previous Article
Array Fundamentals in Java

Topics

Life & Productivity
Programming
Running

Related Posts

Build Rest API from scratch in Node.js
July 24, 2020
4 min
Arvind Pandey © 2022, All Rights Reserved.

Quick Links

About Me

Social Media