• Awards Season
  • Big Stories
  • Pop Culture
  • Video Games
  • Celebrities

Mastering Java Development: Best Free Online Courses

Java is one of the most popular programming languages in the world, and for good reason. It’s versatile, powerful, and can be used to develop a wide variety of applications and software. If you’re interested in becoming a Java developer or simply want to improve your coding skills, taking an online course is a great way to get started. In this article, we’ll explore some of the best free Java developer courses available online.

Introduction to Java

The first section of any good Java development course should cover the basics of the language. This includes things like syntax, data types, operators, and control structures. The goal of this section is to give you a solid foundation in Java that you can build upon as you progress through the course.

One great option for an introduction to Java course is “Java Programming Basics” on Udemy. This course covers all the basics of Java programming in just over 3 hours of video content. The best part? It’s completely free.

Oriented Programming

Once you have a solid understanding of the basics, it’s time to move on to object-oriented programming (OOP). OOP is a programming paradigm that focuses on creating reusable code by organizing it into objects that interact with each other.

For learning OOP concepts in Java, “Object Oriented Programming in Java” offered by Coursera is an excellent option. This course covers everything from inheritance and polymorphism to abstract classes and interfaces. And yes, it’s also free.

Web Development with Spring Framework

Java isn’t just limited to desktop applications – it’s also widely used for web development. One popular framework for building web applications with Java is Spring Framework. Spring provides developers with tools for building everything from simple web apps to complex enterprise-grade software.

To learn about web development using Spring Framework, check out “Spring Framework 5: Beginner to Guru” on Udemy. This course covers everything from the basics of Spring to advanced topics like security and data access. And the best part? It’s completely free.

Java Tools and Libraries

As you become more familiar with Java, you’ll want to start exploring some of the many tools and libraries available to developers. These can help streamline your development process, improve your code quality, and make your applications more powerful.

One great resource for learning about Java tools and libraries is “Java Tools and Libraries for Developers” on Coursera. This course covers topics like debugging, testing, and performance tuning using popular tools like Eclipse and JUnit.

Becoming a master Java developer takes time, dedication, and practice. But with the right resources at your disposal – including these free online courses – you can get started on the path to becoming a Java pro today.

This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability.


string assignment in java

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Write an Interview Experience
  • Share Your Campus Experience
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted output in Java
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java

Strings in Java

  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • ‘this’ reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • List of all Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Java Singleton Class
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Try, catch, throw and throws in Java
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

In the given example only one object will be created. Firstly JVM will not find any string object with the value “Welcome” in the string constant pool, so it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance. In this article, we will learn about Java Strings.

What are Strings in Java?

Strings are the type of objects that can store the character of values. A string acts the same as an array of characters in Java.


String Example in Java

Below is an example of a String in Java:

Ways of Creating a String

There are two ways to create a string in Java: 

  • String Literal
  • Using new Keyword


1. String literal

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool). 

2. Using new keyword

  • String s = new String(“Welcome”);
  • In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in the heap (non-pool)

Interfaces and Classes in Strings in Java

CharBuffer : This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.

String : It is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created.

CharSequence Interface

CharSequence Interface is used for representing the sequence of Characters in Java. Classes that are implemented using the CharSequence interface are mentioned below:

  • StringBuffer
  • StringBuilder

1. StringBuffer

StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.

2. StringBuilder

StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternative to String Class, as it creates a mutable sequence of characters.

3. StringTokenizer

StringTokenizer class in Java is used to break a string into tokens. 

A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.

StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be done with the help of the StringBuilder class to append a delimiter after each string, StringJoiner provides an easy way to do that without much code to write.

Above we saw we can create a string by  String Literal. 

String demoString =”Welcome”; 

Here the JVM checks the String Constant Pool. If the string does not exist, then a new string instance is created and placed in a pool. If the string exists, then it will not create a new object. Rather, it will return the reference to the same instance. The cache that stores these string instances is known as the String Constant pool or String Pool. In earlier versions of Java up to JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is moved to the main heap area. 

Immutable String in Java

In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once a string object is created its data or state can’t be changed but a new string object is created.

Below is the implementation of the topic:

Here Sachin is not changed but a new object is created with “Sachin Tendulkar”. That is why a string is known as immutable.

As you can see in the given figure that two objects are created but s reference variable still refers to “Sachin” and not to “Sachin Tendulkar”. But if we explicitly assign it to the reference variable, it will refer to the “Sachin Tendulkar” object.           

For Example:

Memory Allotment of String

Whenever a String Object is created as a literal, the object will be created in the String constant pool. This allows JVM to optimize the initialization of String literal.


The string can also be declared using a new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in the heap. This string will not be added to the String constant pool.


If you want to store this string in the constant pool then you will need to “intern” it.

It is preferred to use String literals as it allows JVM to optimize memory allocation.

An example that shows how to declare a String 

Note: String objects are stored in a special memory area known as string constant pool.

Why did the String pool move from PermGen to the normal heap area? 

PermGen space is limited, the default size is just 64 MB. it was a problem with creating and storing too many string objects in PermGen space. That’s why the String pool was moved to a larger heap area. To make Java more memory efficient, the concept of string literal is used. By the use of the ‘new’ keyword, The JVM will create a new string object in the normal heap area even if the same string object is present in the string pool. 

For example:

Let us have a look at the concept with a Java program and visualize the actual JVM memory structure: 

Below is the implementation of the above approach:

String Pool in Java

Note:  All objects in Java are stored in a heap. The reference variable is to the object stored in the stack area or they can be contained in other objects which puts them in the heap area also.

Example 1: 

Frequently Asked Questions

1. what are strings in java.

Strings are the types of objects which can store characters as elements. 

2. Why string objects are immutable in Java?

Because java uses the concept of string literal. Suppose there are 5 reference variables, all refer to one object “Sachin”. If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why string objects are immutable in Java.

3. Why Java uses the concept of string literal?

Solve DSA problems on GfG Practice.

Please Login to comment...

Improve your coding skills with practice.

Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?
  • Java for Android: Know the importance of Java in Android
  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?
  • Java 9 Features and Improvements
  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

  • How To Set Path in Java?
  • How to Write Hello World Program in Java?
  • How to Compile and Run your first Java Program?
  • Learn How To Use Java Command Line Arguments With Examples

Control Statements

  • What is for loop in java and how to implement it?
  • What is a While Loop in Java and how to use it?
  • What is for-each loop in Java?
  • What is a Do while loop in Java and how to use it?
  • What is a Switch Case In Java?

Java Core Concepts

  • Java Tutorial For Beginners – Java Programming Made Easy!
  • What are the components of Java Architecture?
  • What are Comments in Java? – Know its Types
  • What are Java Keywords and reserved words?
  • What is a Constructor in Java?
  • What is the use of Destructor in Java?
  • Know About Parameterized Constructor In Java With Examples
  • What are Operators in Java and its Types?
  • What Are Methods In Java? Know Java Methods From Scratch
  • What is Conditional Operator in Java and how to write it?
  • What is a Constant in Java and how to declare it?
  • What is JIT in Java? – Understanding Java Fundamentals
  • What You Should Know About Java Virtual Machine?
  • What is the role for a ClassLoader in Java?
  • What is an Interpreter in Java?
  • What is Bytecode in Java and how it works?
  • What is a Scanner Class in Java?
  • What is the Default Value of Char in Java?
  • this Keyword In Java – All You Need To Know
  • What is Protected in Java and How to Implement it?
  • What is a Static Keyword in Java?
  • What is an Array Class in Java and How to Implement it?
  • What is Ternary Operator in Java and how can you use it?
  • What is Modulus in Java and how does it work?
  • What is the difference between Method Overloading And Overriding?
  • Instance variable In Java: All you need to know
  • Know All About the Various Data Types in Java
  • What is Typecasting in Java and how does it work?
  • How to Create a File in Java? – File Handling Concepts
  • File Handling in Java – How To Work With Java Files?
  • What is a Comparator Interface in Java?
  • Comparable in Java: All you need to know about Comparable & Comparator interfaces
  • What is Iterator in Java and How to use it?
  • Java Exception Handling – A Complete Reference to Java Exceptions
  • All You Need to Know About Final, Finally and Finalize in Java

How To Implement Volatile Keyword in Java?

  • Garbage Collection in Java: All you need to know
  • What is Math Class in Java and How to use it?
  • What is a Java Thread Pool and why is it used?
  • Synchronization in Java: What, How and Why?
  • Top Data Structures & Algorithms in Java That You Need to Know
  • Java EnumSet: How to use EnumSet in Java?
  • How to Generate Random Numbers using Random Class in Java?
  • Generics in Java – A Beginners Guide to Generics Fundamentals
  • What is Enumeration in Java? A Beginners Guide

Transient in Java : What, Why & How it works?

  • What is Wait and Notify in Java?

Swing In Java : Know How To Create GUI With Examples

  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?

What Is A Virtual Function In Java?

  • Java Regex – What are Regular Expressions and How to Use it?
  • What is PrintWriter in Java and how does it work?
  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

  • What is the concept of String Pool in java?
  • Java String – String Functions In Java With Examples
  • Substring in Java: Learn how to use substring() Method
  • What are Immutable String in Java and how to use them?
  • What is the difference between Mutable and Immutable In Java?
  • BufferedReader in Java : How To Read Text From Input Stream
  • What are the differences between String, StringBuffer and StringBuilder?
  • Split Method in Java: How to Split a String in Java?
  • Know How to Reverse A String In Java – A Beginners Guide
  • What is Coupling in Java and its different types?
  • Everything You Need to Know About Loose Coupling in Java

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?
  • What is Integer class in java and how it works?
  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?

How To Implement Multiple Inheritance In Java?

  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?
  • What is the Use of Abstract Method in Java?
  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?
  • What is Dynamic Binding In Java And How To Use It?

Java Collections

  • Java Collections – Interface, List, Queue, Sets in Java With Examples
  • List in Java: One Stop Solution for Beginners
  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java
  • How to Iterate Maps in Java?
  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

Palindrome in java: how to check a number is palindrome.

  • How to check if a given number is an Armstrong number or not?
  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?
  • How to implement Java program to check Leap Year?
  • How to Calculate Square and Square Root in Java?
  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?
  • Top 30 Patterns in Java: How to Print Star, Number and Character
  • Know all about the Prime Number program in Java
  • How To Display Fibonacci Series In Java?
  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?
  • How To Practice String Concatenation In Java?
  • How To Convert Binary To Decimal In Java?
  • How To Convert Double To Int in Java?
  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?
  • How to Create JFrame in Java?
  • What is Externalization in Java and when to use it?
  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?
  • Java Programs for Practice: Know the Simple Java Programs for Beginners

Advance Java

  • How To Connect To A Database in Java? – JDBC Tutorial
  • Advanced Java Tutorial- A Complete Guide for Advanced Java
  • Servlet and JSP Tutorial- How to Build Web Applications in Java?
  • Introduction to Java Servlets – Servlets in a Nutshell
  • What Is JSP In Java? Know All About Java Web Applications
  • How to Implement MVC Architecture in Java?
  • What is JavaBeans? Introduction to JavaBeans Concepts
  • Know what are the types of Java Web Services?
  • JavaFX Tutorial: How to create an application?
  • What is Executor Framework in Java and how to use it?
  • What is Remote Method Invocation in Java?
  • Everything You Need To Know About Session In Java?
  • Java Networking: What is Networking in Java?
  • What is logger in Java and why do you use it?
  • How To Handle Deadlock In Java?
  • Know all about Socket Programming in Java
  • Important Java Design Patterns You Need to Know About
  • What is ExecutorService in Java and how to create it?
  • Struts 2 Tutorial – One Stop Solution for Beginners
  • What is Hibernate in Java and Why do we need it?
  • What is Maven in Java and how do you use it?
  • What is Machine Learning in Java and how to implement it?

Career Opportunities

  • Java Developer Resume: How to Build an Impressive Resume?
  • What is the Average Java Developer Salary?

Interview Questions

  • Top 130+ Core Java Interview Questions for Freshers and Experienced in 2023
  • Top MVC Interview Questions and Answers You Need to Know in 2023
  • Top 50 Java Collections Interview Questions You Need to Know in 2023
  • Top 50 JSP Interview Questions You Need to Know in 2023
  • Top 50 Hibernate Interview Questions That Are A Must in 2023

Programming & Frameworks

String in java – string functions in java with examples.

What is a Java String? In Java, a string is an object that represents a sequence of characters or char values. The java.lang.String class is used to create a Java string object.

There are two ways to create a String object:

  • By string literal : Java String literal is created by using double quotes. For Example: String s= “Welcome” ;  
  • By new keyword : Java String is created by using a keyword “new”. For example:  String s= new String( “Welcome” );   It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.

Now, let us understand the concept of Java String pool.

Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. Refer to the diagrammatic representation for better understanding:

Before we go ahead, One key point I would like to add that unlike other data types in Java, Strings are immutable. By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared. For example:

   String str =”abc”; is equivalent to :

  ch ar data[] = {‘a’, ‘b’, ‘c’};     String str = new String(da ta);

Let us now look at some of the inbuilt methods in String class .

Get Certified With Industry Level Projects & Fast Track Your Career Take A Look!

Java S tring Methods

  • Java String length() :  The Java String length() method tells the length of the string. It returns count of total number of characters present in the String. For exam p le:

Here, String length()  function will return the length 5 for s1 and 7 for s2 respectively.

  • Java St ring comp areTo () : The Java String compareTo() method compares the given string with current string. It is a method of  ‘Comparable’  interface which is implemented by String class. Don’t worry, we will be learning about String interfaces later. It either returns positive number, negative number or 0.  For example:

This program shows the comparison between the various string. It is noticed that   i f s 1 > s2 ,  it  returns a positive number   i f   s1 < s 2 , it returns a negative number  i f s1 == s2, it returns 0

  • Java String IsEmpty() : This method checks whether the String contains anything or not. If the java String is Empty, it returns true else false. For example: public class IsEmptyExample{ public static void main(String args[]){ String s1=""; String s2="hello"; System.out.println(s1.isEmpty()); // true System.out.println(s2.isEmpty()); // false }}
  • Java String ValueOf() : This method converts different types of values into string.Using this method, you can convert int to string, long to string, Boolean to string, character to string, float to string, double to string, object to string and char array to string. The signature or syntax of string valueOf() method is given below: public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d) public static String valueOf(Object o)

Let’s understand this with a programmatic example:

In the above code, it concatenates the Java String and gives the output – 2017.

Java String replace() : The Java String replace() method returns a string, replacing all the old characters or CharSequence to new characters. There are 2 ways to replace methods in a Java String. 

In the above code, it will replace all the occurrences of ‘h’ to ‘t’. Output to the above code will be “tello tow are you”.  Let’s see the another type of using replace method in java string: Java String replace(CharSequence target, CharSequence replacement) method :

In the above code, it will replace all occurrences of “Edureka” to “Brainforce”. Therefore, the output would be “ Hey, welcome to Brainforce”.

In the above code, the first two statements will return true as it matches the String whereas the second print statement will return false because the characters are not present in the string.

  • Java String equals() : The Java String equals() method compares the two given strings on the basis of content of the string i.e Java String representation. If all the characters are matched, it returns true else it will return false. For example: public class EqualsExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="hi"; System.out.println(s1.equalsIgnoreCase(s2)); // returns true System.out.println(s1.equalsIgnoreCase(s3)); // returns false } }

In the above code, the first statement will return true because the content is same irrespective of the case. Then, in the second print statement will return false as the content doesn’t match in the respective strings.

  • Java String IsEmpty() : This method checks whether the String is empty or not. If the length of the String is 0, it returns true else false. For example: 

In the above code, the first print statement will return true as it does not contain anything while the second print statement will return false.

  • Java String endsWith() : The Java String endsWith() method checks if this string ends with the given suffix. If it returns with the given suffix, it will return true else returns fals e. F or example:

This is not the end. There are more Java String methods that will help you make your code simpler.  

Moving on, Java String class implements three  interfac es , namely – Serializable, Comparable and C h arSequence .

  • StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized whereas StringBuilder operations are not thread-safe.
  • StringBuffer is to be used when multiple threads are working on same String and StringBuilder in the single threaded environment.
  • StringBuilder performance is faster when compared to StringBuffer because of no overhead of synchronized.

I hope you guys are clear with Java String, how they are created, their different methods and interfaces. I would recommend you to try all the Java String examples.  Do read my next blog on Java Interview Questions which will help you set apart in the interview process. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

Now that you have understood basics of Java, check out the Java Online Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java String” blog  and we will get back to you as soon as possible or you can also join Java Training in Amritsar .

Recommended videos for you

Spring framework : introduction to spring web mvc & spring with bigdata, introduction to java/j2ee & soa, building web application using spring framework, service-oriented architecture with java, microsoft sharepoint-the ultimate enterprise collaboration platform, a day in the life of a node.js developer, ms .net – an intellisense way of web development, nodejs – communication and round robin way, learn perl-the jewel of scripting languages, building application with ruby on rails framework, hibernate-the ultimate orm framework, php and mysql : server side scripting for web development, microsoft .net framework : an intellisense way of web development, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, portal development and text searching with hibernate, node js express: steps to create restful web app, php & mysql : server-side scripting language for web development, create restful web application with node.js express, implementing web services in java, recommended blogs for you, typescript tutorial: know about the fundamentals of typescript, everything you need to know about pojo in java, how to implement a background image in html, what is vector in java and how do we use it, what is node.js one stop solution for beginners, what are vectors in c++ all you need to know, introduction to input in python, everything you need to know about bitwise operators in java, how to implement if else in java, how to implement foreach loop in php with examples, what is the concept of serialization in java, how to convert object to array in php, how to implement str_replace in php, removing elements from an array in javascript.

This is wrong information. Please correct it.

( Corrections are in bold letters) By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects ( in String pool and in heap ) and one reference variable where the variable ‘s’ will refer to the object in the heap.

Please refer to Java 8 reference books, There are changes in version of java 8.

Hello, Nice Blog, But please change the image where you are comparing two string using == there you should modify the last image as s1 == s3 Sandeep Patidar

Join the discussion Cancel reply

Trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 71k Enrolled Learners

Flutter Application Development Course

  • 11k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Python Django Certification Training Course

  • 9k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

Javatpoint Logo

Java String

Java string methods.


  • Why are String objects immutable?
  • How to create an immutable class?
  • What is string constant pool?
  • What code is written by the compiler if you concatenate any string by + (string concatenation operator)?
  • What is the difference between StringBuffer and StringBuilder class?
  • Concept of String
  • Immutable String
  • String Comparison
  • String Concatenation
  • Concept of Substring
  • String class methods and its usage
  • StringBuffer class
  • StringBuilder class
  • Creating Immutable class
  • toString() method
  • StringTokenizer class


  • Send your Feedback to [email protected]

Help Others, Please Share


Learn Latest Tutorials

Splunk tutorial


Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial



Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

In this case, "Hello world!" is a string literal —a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world! .

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

The last line of this code snippet displays hello .

String Length

Methods used to obtain information about an object are known as accessor methods . One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i) , which returns the i th character in the string, counting from 0.

Running the program produces this output:

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars() , to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

Concatenating Strings

The String class includes a method for concatenating two strings:

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

Strings are more commonly concatenated with the + operator, as in

which results in

The + operator is widely used in print statements. For example:

which prints

Such a concatenation can be a mixture of any objects. For each object that is not a String , its toString() method is called to convert it to a String .

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.

Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format() , that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

you can write

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How to including variables within strings? [duplicate]

So, we all should know that you can include variables into strings by doing:

Is there a way to do it like:

In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.

  • quotation-marks

Mark Rotteveel's user avatar

  • 20 @Chandra Please don't ask why, but rather explain if possible. It's just how I'd prefer to do it. Thanks. –  Gray Adams Mar 10, 2012 at 3:12
  • 3 Use Groovy, then you'll be able to do "A string ${aVariable}" all you want. –  Kaleb Brasee Mar 10, 2012 at 3:14
  • 3 There's a whole variety of techniques for similar things discussed in this question , but String.format() is built-in to the language. –  ig0774 Mar 10, 2012 at 3:15
  • 1 @KalebBrasee That sounds perfect, but I am always hesitant when it comes to modifying languages. I don't want to set myself back. –  Gray Adams Mar 10, 2012 at 3:17
  • 2 @GrayAdams Groovy doesn't set you back, it sets you free! :D –  Kaleb Brasee Mar 10, 2012 at 3:20

6 Answers 6

You can always use String.format(....). i.e.,

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

Hovercraft Full Of Eels's user avatar

  • 3 I know this is a matter of opinion, but I don't see how format is more attractive than a simple String concatenation expression. Where format comes into its own is when you need to do padding, number formatting, etcetera. –  Stephen C Mar 10, 2012 at 4:19
  • 1 @StephenC: I don't disagree with you at all. But it is a useful alternative for String formatting especially when needing to do padding as you say and as I say above (i.e., to show tabular numeric data). I've used it quite a bit for formatting blood chemistry and CBC result reports. –  Hovercraft Full Of Eels Mar 10, 2012 at 11:08
  • @StephenC I like format for a few reasons: first of all, '%d' uses the platform line delimiter. Second, you can easily find all variables at the end. You can easily reformat or even reorder the variables you input. It's easier to avoid mistakes (like 1 + "oops" ), especially if you use FindBugs (which parses format strings and input parameters). And, as the asker says, in many cases it's more readable. Of course, it's a shame that the format method has been made static, that was a rather stupid design mistake. –  Maarten Bodewes Mar 15, 2012 at 22:09
  • 1 @StephenC And why not? Although renaming the method to e.g. asFormat would make more sense. Of course, the fact that Eclipse does not work that well with static imports makes it a bit more painful to use the current String.format as well. –  Maarten Bodewes Mar 16, 2012 at 0:44
  • 1 @owlstead - "asFormat" wouldn't be right. It implies that the method is creating and returning a format object. –  Stephen C Mar 16, 2012 at 3:50

This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

Another approach is to use a templating library such as Velocity or FreeMarker .

Jacob Mattison's user avatar

Also consider java.text.MessageFormat , which uses a related syntax having numeric argument indexes. For example,

results in string containing the following:

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here ; the class RCInfo formats a game's status pane.

Community's user avatar

  • 2 For somebody coming from CSharp this way is more straightforward since it is similar to string.Format in C#. –  Mojtaba Aug 22, 2017 at 15:25
  • I much prefer this due to how clean and reusable a variable is, compared to the String.format() method. –  Satch Jun 12 at 12:55

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

"First foo, then bar"

Domadin's user avatar

Apache Commons Text 's StringSubstitutor can be used. See the library's Dependency Information for how to include it in a project.

This class supports providing default values for variables.

To use recursive variable replacement, call setEnableSubstitutionInVariables(true); .

The library can be found on Maven central repository . This is the Maven dependency:

Unmitigated's user avatar

  • 1 This answer really answers the question. –  AlikElzin-kilaka Jul 4, 2021 at 8:59
  • This indeed meets the requirement precisely. –  Arvind Kumar Avinash Nov 27, 2022 at 16:10

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

alinn's user avatar

Not the answer you're looking for? Browse other questions tagged java variables insert include quotation-marks or ask your own question .

  • The Overflow Blog
  • Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
  • Featured on Meta
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective

Hot Network Questions

  • How to pass a statistics exam that overly relies on memorizing formulas?
  • Confused about the notion of overfitting and noisy target function
  • Is this duplo train track under too much tension?
  • Truly Windows keyboard behavior on a MacBook Pro
  • Why do some US senators such as Mitch McConnell, Dianne Feinstein etc last for so long in the senate?
  • Can one performer manage striking tubular bells and timpani simultaneously?
  • Is there any jurisdiction where political views are a protected characteristic?
  • Calculating integral with exponential function and parameter
  • Why is there nearly no 1x road bikes?
  • Partition a random sequence composed of three numbers
  • Does query string case affect SEO?
  • Was the recent ruling against Jordan Peterson an infringement of his free speech?
  • Least Count Error is Random or Systematic?
  • All arsenic not in the ground is magically removed. What effect would that have?
  • Documents needed when travelling from the U.S. to Canada and back by land as a German citizen
  • Is this possible to boot an OS from some kind of a file?
  • Are these lines by Thomas Nuce a translation and/or taken from a longer poem?
  • Does anyone know this skyline?
  • TikZ animations key `end on` is interpreted as `begin on`
  • Golf the fast growing hierarchy
  • What order should my index's columns be for a SELECT a, b, MAX( c ) FROM d WHERE e = 1 GROUP BY a, b?
  • Manned Spacecraft/Space Station design Requirements
  • What are some good books on mathematical pedagogy?
  • How to put a tube in a used tubeless tire

string assignment in java

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor

Java Strings

  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Java String equals()

Java String intern()

Java String compareTo()

Java String equalsIgnoreCase()

  • Java String concat()
  • Java String join()

In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

We use double quotes to represent a string in Java. For example,

Here, we have created a string variable named type . The variable is initialized with the string Java Programming .

Example: Create a String in Java

In the above example, we have created three strings named first , second , and third . Here, we are directly creating strings like primitive types.

However, there is another way of creating Java strings (using the new keyword). We will learn about that later in this tutorial.

Note : Strings in Java are not primitive types (like int , char , etc). Instead, all strings are objects of a predefined class named String .

And, all string variables are instances of the String class.

Java String Operations

Java String provides various methods to perform different operations on strings. We will look into some of the commonly used string operations.

1. Get length of a String

To find the length of a string, we use the length() method of the String. For example,

In the above example, the length() method calculates the total number of characters in the string and returns it. To learn more, visit Java String length() .

2. Join Two Java Strings

We can join two strings in Java using the concat() method. For example,

In the above example, we have created two strings named first and second . Notice the statement,

Here, the concat() method joins the second string to the first string and assigns it to the joinedString variable.

We can also join two strings using the + operator in Java. To learn more, visit Java String concat() .

3. Compare two Strings

In Java, we can make comparisons between two strings using the equals() method. For example,

In the above example, we have created 3 strings named first , second , and third . Here, we are using the equal() method to check if one string is equal to another.

The equals() method checks the content of strings while comparing them. To learn more, visit Java String equals() .

Note : We can also compare two strings using the == operator in Java. However, this approach is different than the equals() method. To learn more, visit Java String == vs equals() .

Escape character in Java Strings

The escape character is used to escape some of the characters present inside a string.

Suppose we need to include double quotes inside a string.

Since strings are represented by double quotes , the compiler will treat "This is the " as the string. Hence, the above code will cause an error.

To solve this issue, we use the escape character \ in Java. For example,

Now escape characters tell the compiler to escape double quotes and read the whole text.

Java Strings are Immutable

In Java, strings are immutable . This means, once we create a string, we cannot change that string.

To understand it more deeply, consider an example:

Here, we have created a string variable named example . The variable holds the string "Hello! " .

Now suppose we want to change the string.

Here, we are using the concat() method to add another string World to the previous string.

It looks like we are able to change the value of the previous string. However, this is not true .

Let's see what has happened here,

  • JVM takes the first string "Hello! "
  • creates a new string by adding "World" to the first string
  • assign the new string "Hello! World" to the example variable
  • the first string "Hello! " remains unchanged
  • Creating strings using the new keyword

So far we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using the new keyword as well. For example,

In the above example, we have created a string name using the new keyword.

Here, when we create a string object, the String() constructor is invoked. To learn more about constructor, visit Java Constructor .

Note : The String class provides various other constructors to create strings. To learn more, visit Java String (official Java documentation) .

Example: Create Java Strings using the new keyword

Create string using literals vs new keyword.

Now that we know how strings are created using string literals and the new keyword, let's see what is the major difference between them.

In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.

1. While creating strings using string literals,

Here, we are directly providing the value of the string ( Java ). Hence, the compiler first checks the string pool to see if the string already exists.

  • If the string already exists , the new string is not created. Instead, the new reference, example points to the already existed string ( Java ).
  • If the string doesn't exist , the new string ( Java is created.

2. While creating strings using the new keyword,

Here, the value of the string is not directly provided. Hence, a new "Java" string is created even though "Java" is already present inside the memory pool.

  • Methods of Java String

Besides those mentioned above, there are various string methods present in Java. Here are some of those methods:

Table of Contents

  • Java String
  • Create a String in Java
  • Get Length of a String
  • Join two Strings
  • Compare two Strings
  • Escape character in Strings
  • Immutable Strings
  • String literals vs new keyword

Sorry about that.

Related Tutorials

Java Library


Java programming tutorial, java string is special, a brief summary of the string class.

A Java String contains an immutable sequence of Unicode characters. Unlike C/C++, where string is simply an array of char , A Java String is an object of the class java.lang.String .

Java String is, however, special. Unlike an ordinary class:

  • String is associated with string literal in the form of double-quoted texts such as " hello, world ". You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.
  • The '+' operator is overloaded to concatenate two String operands. '+' does not work on any other objects such as Point and Circle .
  • String is immutable . That is, its content cannot be modified once it is created. For example, the method toUpperCase() constructs and returns a new String instead of modifying the existing content.

Method Summary

The commonly-used method in the String class are summarized below. Refer to the JDK API for java.lang.String a complete listing.

static method String.format() (JDK 5)

The static method String.format() (introduced in JDK 5) can be used to produce a formatted String using C-like printf() 's format specifiers. The format() method has the same form as printf() . For example,

String.format() is useful if you need to produce a simple formatted String for some purposes (e.g., used in method toString() ). For complex string, use StringBuffer / StringBuilder with a Formatter . If you simply need to send a simple formatted string to the console, use System.out.printf() , e.g.,

[TODO] More examples

New Methods

Jdk 9 new methods.

  • .chars()|.codePoints() -> IntStream

JDK 11 new methods

  • .repeat(int count) -> String
  • .strip()|.stripLeading()|.stripTrailing() -> String and .isBlank() -> boolean which are unicode white-space aware.
  • .lines() to produces a Stream<String> . (JDK 9 added .chars() and .codePoints() to produce an IntStream .)

JDK 12 new methods

  • .indent(int n) -> String
  • .transform(Function<String,R> f) -> R
  • .describeConstable() -> Optional<String>
  • .resolveConstantDesc() -> String

JDK 13 new methods

String is really special.

Strings receive special treatment in Java, because they are used frequently in a program. Hence, efficiency (in terms of computation and storage) is crucial.

The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the method stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.

For performance reason, Java's String is designed to be in between a primitive and an object. The special features in String include:

  • The '+' operator, which performs addition on primitives (such as int and double ), is overloaded to operate on String objects. '+' performs concatenation for two String operands. Java does not support operator overloading for software engineering consideration. In a language that supports operator overloading like C++, you can turn a '+' operator to perform a subtraction, resulted in poor codes. The '+' operator is the only operator that is internally overloaded to support string concatenation in Java. Take note that '+' does not work on any two arbitrary objects, such as Point s or Circle s.
  • directly assigning a string literal to a String reference - just like a primitive , or
  • via the " new " operator and constructor, similar to any other classes. However, this is not commonly-used and is not recommended.

For example,

In the first statement, str1 is declared as a String reference and initialized with a string literal "Java is Hot" . In the second statement, str2 is declared as a String reference and initialized via the new operator and constructor to contain "I'm cool" .

  • String literals are stored in a common pool . This facilitates sharing of storage for strings with the same contents to conserve storage. String objects allocated via new operator are stored in the heap, and there is no sharing of storage for the same contents.

String Literal vs. String Object


As mentioned, there are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String object via the new operator and constructor. For example,

Java has provided a special mechanism for keeping the String literals - in a so-called string common pool . If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hand, String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object. There is no sharing of storage in heap even if two String objects have the same contents.

You can use the method equals() of the String class to compare the contents of two String s. You can use the relational equality operator '==' to compare the references (or pointers) of two objects. Study the following codes:

Important Notes:

  • In the above example, I used relational equality operator '==' to compare the references of two String objects. This is done to demonstrate the differences between string literals sharing storage in the common pool and String objects created in the heap. It is a logical error to use (str1 == str2) in your program to compare the contents of two String s.
  • String can be created by directly assigning a String literal which is shared in a common pool. It is uncommon and not recommended to use the new operator to construct a String object in the heap.

String is Immutable

Since string literals with the same contents share storage in the common pool, Java's String is designed to be immutable . That is, once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable. Methods such as toUpperCase() might appear to modify the contents of a String object. In fact, a completely new String object is created and returned to the caller. The original String object will be deallocated, once there is no more references, and subsequently garbage-collected.

Because String is immutable, it is not efficient to use String if you need to modify your string frequently (that would create many new String s occupying new storage areas). For example,

If the contents of a String have to be modified frequently, use the StringBuffer or StringBuilder class instead.


Stringbuffer & stringbuilder.

As explained earlier, String s are immutable because String literals with same content share the same storage in the string common pool. Modifying the content of one String directly may cause adverse side-effects to other String s sharing the same storage.

JDK provides two classes to support mutable strings: StringBuffer and StringBuilder (in core package java.lang ). A StringBuffer or StringBuilder object is just like any ordinary object, which are stored in the heap and not shared, and therefore, can be modified without causing adverse side-effect to other objects.

StringBuilder class was introduced in JDK 5. It is the same as StringBuffer class, except that StringBuilder is not synchronized for multi-thread operations. However, for single-thread program, StringBuilder , without the synchronization overhead, is more efficient.


Read the JDK API specification for java.lang.StringBuffer .

Take note that StringBuffer is an ordinary object. You need to use a constructor to create a StringBuffer (instead of assigning to a String literal). Furthermore, '+' operator does not apply to objects, including the StringBuffer . You need to use a proper method such as append() or insert() to manipulating a StringBuffer .

To create a string from parts, It is more efficient to use StringBuffer (multi-thread) or StringBuilder (single-thread) instead of via String concatenation. For example,

JDK compiler, in fact, uses both String and StringBuffer to handle string concatenation via the '+' operator. For examples,

will be compiled into the following codes for better efficiency:

Two objects are created during the process, an intermediate StringBuffer object and the returned String object.

Rule of Thumb: String s are more efficient if they are not modified (because they are shared in the string common pool). However, if you have to modify the content of a string frequently (such as a status message), you should use the StringBuffer class (or the StringBuilder described below) instead.

java.lang.StringBuilder (JDK 5)

JDK 5 introduced a new StringBuilder class (in package java.lang ), which is almost identical to the StringBuffer class, except that it is not synchronized . In other words, if multiple threads are accessing a StringBuilder instance at the same time, its integrity cannot be guaranteed. However, for a single-thread program (most commonly), doing away with the overhead of synchronization makes the StringBuilder faster.

StringBuilder is API-compatible with the StringBuffer class, i.e., having the same set of constructors and methods, but with no guarantee of synchronization. It can be a drop-in replacement for StringBuffer under a single-thread environment.

Benchmarking String/StringBuffer/StringBuilder

The following program compare the times taken to reverse a long string via a String object and a StringBuffer .

Observe StringBuilder is 2x faster than StringBuffer , and 300x faster than String . The reverse() method is the fastest, which take about the same time for StringBuilder and StringBuffer .

java.util.StringTokenizer (Obsoleted by regex)

Very often, you need to break a line of texts into tokens delimited by white spaces. The java.util.StringTokenizer class supports this.

For example, the following program reverses the words in a String.

The JDK documentation stated that " StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split() method of String or the java.util.regex package instead."

For example, the following program uses the split() method of the String class to reverse the words of a String .

Regular Expression (Regex), Patterns & Matches (JDK 4)

Read " Regular Expression in Java ".

Super-Interface CharSequence for String , StringBuffer and StringBuilder (since JDK 4)

The interface java.lang.CharSequence is implemented by classes String , StringBuffer , StringBuilder , CharBuffer and Segment .

It defines the common behavior via these abstract methods:

JDK 8 added two default methods into the interface:

JDK 11 added one static methods into the interface:

Latest version tested: JDK 1.13.1 Last modified: February, 2020


  1. string

    string assignment in java

  2. String Regular Expression. Java Core

    string assignment in java

  3. Java String indexOf() Method with example

    string assignment in java

  4. java for complete beginners

    string assignment in java

  5. Learn about the String object in Java

    string assignment in java

  6. Java String contains() method explained with examples

    string assignment in java


  1. #035 strings in java

  2. Live Java

  3. String Class in Java

  4. Java Programming

  5. String in java

  6. Java String Method


  1. What Is Concrete Class in Java?

    Concrete class in Java is the default class and is a derived class that provides the basic implementations for all of the methods that are not already implemented in the base class.

  2. Java Developer Course Online for Free: Where to Start

    Java is one of the most popular programming languages in the world, and a career in Java development can be both lucrative and rewarding. However, taking a Java developer course online for free can be a challenge. With so many options avail...

  3. Mastering Java Development: Best Free Online Courses

    Java is one of the most popular programming languages in the world, and for good reason. It’s versatile, powerful, and can be used to develop a wide variety of applications and software.

  4. Strings in Java

    Because java uses the concept of string literal. Suppose there are 5 reference variables, all refer to one object “Sachin”. If one reference

  5. How to Declare String in Java With Examples

    It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap. Now

  6. Java String

    Java String literal is created by using double quotes. For Example: String s="welcome";.

  7. Strings

    The String class includes a method for concatenating two strings: string1.concat(string2);. This returns a new string that is string1 with string2 added to it

  8. How to including variables within strings?

    You can always use String.format(....). i.e., String string = String.format("A String %s %2d", aStringVar, anIntVar);.

  9. Java String (With Examples)

    // create a string String example = "Hello! ";. Here, we have created a string variable named example . The variable holds the string "Hello! "

  10. More About Strings In Java

    When you assign a string variable to another variable, It actually copies the reference to the object but not the object itself. It means, since the string

  11. String Initialization in Java

    First, let's just declare a String, without assigning a value explicitly. We can either do this locally or as a member variable: public class

  12. java for complete beginners

    To store just one character, the char variable is used. Usually, though, you'll want to store more than one character. To do so, you need the string variable

  13. What Is a Java String?

    Java strings are created and manipulated through the string class. Once created, a string is immutable -- its value cannot be changed. A string is sequence of

  14. String is Special

    You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance. The '+' operator is overloaded