Udemy logo

Strings in Java Programming Language

Strings are essential elements in a programmer’s toolkit. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user. Strings in Java are first-class objects, with a wide set of methods to operate on them; it is a breeze to search, sort, compare, find things in a string, and query their length, emptiness, digit/letter nature etc, compared to old procedural languages like C or C++.

In this blog post we are going to see how you can create strings, write them to the output, read user input as strings, and count them. As a modern programming languages Java offers capabilities like other comparable systems in Python, or Ruby. String handling is way superior to C language.

String Operations

Strings in Java language are fully specified objects, and are encoded in UTF-8 characters.

This article is fully concerned with the ASCII base 0-127 values of the 7-bit character set. For internationalization applications we will need wide-characters, and we will worry about the encoding. But these are not concerns now; we settle with ASCII encoding and basic ISO-Latin/English scripts.

Setting Up Your Environment

If you a beginning Java user, you need to have the JAVA SDK from Oracle.com installed on your system by yourself, or via an IDE tool like NetBeans or Eclipse.

Strings in Java

To include the string input-output operations in your program you already have the default package from java.lang.String.

where the strings are not NUL terminated, instead have a equivalent character array notation. We can declare a string as follows in the Java language

		String roman_emperor_name = “Julius Caesar”;

                System.out.writeln( roman_emperor_name.length() );

and access the length property of the variable to print it to the console

Example – Listing Length Of Input Strings

In this example we try to print out the list of command line arguments to the program with the length. This is done by accessing the string array ‘args’ in the Java program.

Together our code listing for ‘Beans.java’ is the following,

import java.io.*; 

import java.lang.*; //default include 

class StringyBeans { 

   static void printAllArgs( String [] args ) { 

        for( String str : args) { 

            System.out.println( str + "  | L = " + Integer.toString( str.length() ) ); 

        } 

   } 

} 

public class Beans { 

    public static void main( String [] args) throws Exception { 

        StringyBeans.printAllArgs( args ); 

    } 

} 

Compiling and running the program as,

java Beans french Indian kidney soaked pickled cooked briny BBQ 

you should see the terminal message,

french  | L = 6 

Indian  | L = 6 

kidney  | L = 6 

soaked  | L = 6 

pickled  | L = 7 

cooked  | L = 6 

briny  | L = 5 

BBQ  | L = 3 

Immutable Strings

Strings in Java are immutable, meaning once created they we may not modify them. Each modification on the string creates a new string. In the following listing called ‘Beans2.java’, we will load two strings g, and f. Initially both these strings point to the same object, but when you modify the string f to be lower case, you basically make a new copy and store it on string g. Now the object pointed to by f, has still not changed, except its reference count kept internally has reduced by 1 – as you guess it – because g now points to a new object.

public class Beans2 { 

	public static void main(String [] args) { 

		String g = "New Girl"; 

		String f; 

		f = g; 

		System.out.println(g.hashCode());

System.out.println(f.hashCode());



		// f and g point to same object 

		System.out.println(f.charAt(0)); 

		System.out.println(g.charAt(0)); 

		// g becomes a new string 

		g = f.toLowerCase(); 

		System.out.println(f.charAt(0)); 

		System.out.println(g.charAt(0));

System.out.println(g.hashCode());

System.out.println(f.hashCode());

}

}

You get the following output, and the hash-codes will also show the different objects.

N 

N 

N 

n 

Related functions

You can also compare strings, copy strings fully or upto n-characters, duplicate strings and use routines to check if characters are alphabetic, numeric, space etc.

String Processing

In this example we will take a string, and replace text that has words ‘hello, Mars!’ with ‘goodbye, Mars!’. We add extra code using math library so the match-string can occur in both the beginning or end of the input. This could be your beginning Java development, and may even take you to develop mobile smartphone applications for Android!

We have a program listing for the code, ‘Beans3.java’ as,

public class Beans3 {

public static String proc_str(String in) {	

		String out = in;

		String match="Hello Mars!";

                int pos;

                do {

		pos = out.indexOf(match);

                if ( pos >= 0 ) {

                 // 	found the string

				out = out.substring(0,Math.max(0,pos-1))+"Goodbye Mars!"+out.substring(pos+match.length());					

			}

		} while( pos >= 0 ); 

                return out;

	}

public static void main(String [] args) {

		String orig = "Hello Mars! Veronica Mars is not relevant; Hello Mars! is.";

		String proc = Beans3.proc_str( orig );

		System.out.println(orig);

		System.out.println(proc);

	}

}

When you compile the code, and then run program, you will see the following output,

 Hello Mars! Veronica Mars is not relevant; Hello Mars! is.

 Goodbye Mars! Veronica Mars is not relevant;Goodbye Mars! is.

Summary

Java String API is rich resource for Software developers. You can use strings pervasively in code to achieve essential tasks in your growing toolkit as a programmer. They are one of the most commonly used elementary data types, while writing code, and debugging during the development; as also while formatting output for the user. You can learn more about algorithms and data structures in Java; you can build on Java collections API, on top of the strings lessons you have learnt today.

Page Last Updated: May 2014

Top courses in Java

Java Tutorial for Beginners
Navin Reddy
4.5 (544)
Complete Java SE 8 Developer Bootcamp - OCA Prep Included
Intertech Training, Jeff Jensen
4.6 (9,174)
Highest Rated
Java 8 New Features In Simple Way
DURGASOFT DURGA
4.7 (13,816)
Complete Core Java In Simple Way
DURGASOFT NAGOOR BABU
4.7 (744)
Java Interview Help
Bharath Thippireddy
4.6 (1,189)
Java Programming for Complete Beginners
in28Minutes Official
4.5 (38,991)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,390)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.4 (3,652)
Bestseller
Learn Selenium with Java, Cucumber + Live Project
Pavan Kumar
4.6 (4,305)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 2
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.2 (994)
Modern Java - Learn Java 8 features by coding it
Pragmatic Code School
4.5 (9,565)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo