Learn Java practically and Get Certified .

Popular Tutorials

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

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword

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 Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • 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 ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • 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 Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

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

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

Java String equals()

Java String intern()

Java String compareTo()

  • Java String concat()

Java String equalsIgnoreCase()

  • Java String compareToIgnoreCase()

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 provides various string methods to perform different operations on strings. We will look into some of the commonly used string operations.

1. Get the Length of a String

To find the length of a string, we use the length() method. 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 thoroughly, 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
  • assigns 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 constructors, 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 existing string ( Java ).
  • If the string doesn't exist , a 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:

Methods Description
Checks whether the string contains a substring.
Returns the substring of the string.
Joins the given strings using the delimiter.
Replaces the specified old character with the specified new character.
Replaces all substrings matching the regex pattern.
Replaces the first matching substring.
Returns the character present in the specified location.
Converts the string to an array of bytes.
Returns the position of the specified character in the string.
Compares two strings in the dictionary order.
Compares two strings, ignoring case differences.
Removes any leading and trailing whitespaces.
Returns a formatted string.
Breaks the string into an array of strings.
Converts the string to lowercase.
Converts the string to uppercase.
Returns the string representation of the specified argument.
Converts the string to a array.
Checks whether the string matches the given regex.
Checks if the string begins with the given string.
Checks if the string ends with the given string.
Checks whether a string is empty or not.
Returns the canonical representation of the string.
Checks whether the string is equal to charSequence.
Returns a hash code for the string.
Returns a subsequence from the string.

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
  • Creating strings using the new keyword
  • String literals vs new keyword

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Library

Javatpoint Logo

Java String

Java string methods.

JavaTpoint

In , string is basically an object that represents sequence of char values. An of characters works same as Java string. For example:

is same as:

class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements , and .

The CharSequence interface is used to represent the sequence of characters. String, and classes implement it. It means, we can create strings in Java by using these three classes.

We will discuss immutable string later. Let's first understand what String in Java is and how to create the String object.

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

There are two ways to create String object:

Java String literal is created by using double quotes. For Example:

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:


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

In such case, 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 a heap (non-pool).

The above code, converts a array into a object. And displays the String objects , and on console using method.

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No.MethodDescription
1 It returns char value for the particular index
2 It returns string length
3 It returns a formatted string.
4 It returns formatted string with given locale.
5 It returns substring for given begin index.
6 It returns substring for given begin index and end index.
7 It returns true or false after matching the sequence of char value.
8 It returns a joined string.
9 It returns a joined string.
10 It checks the equality of string with the given object.
11 It checks if string is empty.
12 It concatenates the specified string.
13 It replaces all occurrences of the specified char value.
14 It replaces all occurrences of the specified CharSequence.
15 It compares another string. It doesn't check case.
16 It returns a split string matching regex.
17 It returns a split string matching regex and limit.
18 It returns an interned string.
19 It returns the specified char value index.
20 It returns the specified char value index starting with given index.
21 It returns the specified substring index.
22 It returns the specified substring index starting with given index.
23 It returns a string in lowercase.
24 It returns a string in lowercase using specified locale.
25 It returns a string in uppercase.
26 It returns a string in uppercase using specified locale.
27 It removes beginning and ending spaces of this string.
28 It converts given type into string. It is an overloaded method.
  • 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

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

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

Preparation

Aptitude

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

RSS Feed

Concatenating Strings in Java

Last updated: May 11, 2024

string assignment java

  • Java String
  • StringBuilder

announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Download the E-book

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

1. Introduction

Java provides a substantial number of methods and classes dedicated to concatenating  Strings.

In this tutorial, we’ll dive into several of them as well as outline some common pitfalls and bad practices.

2. StringBuilder

First up is the humble  StringBuilder.  This class provides an array of  String- building utilities that makes easy work of  String  manipulation.

Let’s build a quick example of  String  concatenation using the  StringBuilder  class:

Internally,  StringBuilder  maintains a mutable array of characters. In our code sample, we’ve declared this to have an initial size of 100 through the  StringBuilder  constructor. Because of this size declaration, the  StringBuilder  can be a very efficient way to concatenate  Strings .

It’s also worth noting that the  StringBuffer  class is the synchronized version of  StringBuilder . 

Although synchronization is often synonymous with thread safety, it’s not recommended for use in multithreaded applications due to  StringBuffer’s  builder pattern. While individual calls to a synchronized method are thread safe, multiple calls are not .

3. Addition Operator

Next up is the addition operator (+). This is the same operator that results in the addition of numbers and is overloaded to concatenate when applied to  Strings.

Let’s take a quick look at how this works:

At first glance, this may seem much more concise than the  StringBuilder  option. However, when the source code compiles, the + symbol translates to chains of  StringBuilder.append()  calls. Due to this, mixing the  StringBuilder  and + method of concatenation is considered bad practice .

Additionally,  String  concatenation using the + operator within a loop should be avoided. Since the  String  object is immutable, each call for concatenation will result in a new  String  object being created.

4.  String Methods

The  String  class itself provides a whole host of methods for concatenating Strings.

4.1.  String.concat

Unsurprisingly, the  String.concat  method is our first port of call when attempting to concatenate  String  objects. This method returns a  String  object, so chaining together the method is a useful feature.

In this example, our chain is started with a  String  literal, the  concat  method then allows us to chain the calls to append further Strings .

4.2.  String.format

Next up is the  String.format  method , which allows us to inject a variety of Java Objects  into a  String  template.

The  String.format  method signature takes a single  String  denoting our template . This template contains ‘%’ characters to represent where the various  Objects   should be placed within it.

Once our template is declared, it then takes a varargs   Object  array which is injected into the template.

Let’s see how this works with a quick example:

As we can see above, the method has injected our  Strings  into the correct format.

4.3.  String.join (Java 8+)

If our application is running on Java 8 or above , we can take advantage of the  String.join  method. With this, we can join an array of  Strings  with a common delimiter , ensuring no spaces are missed.

A huge advantage of this method is not having to worry about the delimiter between our strings.

5.  StringJoiner  (Java 8+)

StringJoiner  abstracts all of the  String.join  functionality into a simple to use class. The constructor takes a delimiter, with an optional prefix and suffix . We can append  Strings  using the well-named  add  method.

By using this class, instead of the  String.join  method, we can append  Strings  as the program runs ; There’s no need to create the array first!

Head over to our article on StringJoiner for more information and examples.

6.  Arrays.toString

On the topic of arrays, the  Array  class also contains a handy  toString  method which nicely formats an array of objects. The Arrays. toString  method also calls the  toString  method of any enclosed object – so we need to ensure we have one defined.

Unfortunately, the  Arrays. toString  method is not customizable and only outputs a  String  encased in square brackets.

7.  Collectors.joining  (Java 8+)

Finally, let’s take a look at the  Collectors.joining  method which allows us to funnel the output of a  Stream  into a single  String.

Using streams unlocks all of the functionality associated with the Java 8  Stream  API , such as filtering, mapping, iterating and more.

In this article, we’ve taken a deep dive into the multitude of classes and methods used to concatenate Strings   in the Java language.

As always, the source code is available over on GitHub .

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

RWS Course Banner

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.

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

One of the most common operators that you'll encounter is the simple assignment operator " = ". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

This operator can also be used on objects to assign object references , as discussed in Creating Objects .

The Arithmetic Operators

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.

Operator Description
Additive operator (also used for String concatenation)
Subtraction operator
Multiplication operator
Division operator
Remainder operator

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments . For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Operator Description
Unary plus operator; indicates positive value (numbers are positive without this, however)
Unary minus operator; negates an expression
Increment operator; increments a value by 1
Decrement operator; decrements a value by 1
Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo , tests the unary operators:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version ( ++result ) evaluates to the incremented value, whereas the postfix version ( result++ ) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo , illustrates the prefix/postfix unary increment operator:

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

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

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 Pattern Program 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?
  • Basic Java Programs for Practice With Examples

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

  • Java Interview Questions and Answers
  • Top MVC Interview Questions and Answers You Need to Know in 2024
  • Top 50 Java Collections Interview Questions You Need to Know in 2024
  • Top 50 JSP Interview Questions You Need to Know in 2024
  • Top 50 Hibernate Interview Questions That Are A Must in 2024

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.

Java Full Course – 10 Hours | Java Full Course for Beginners | Java Tutorial for Beginners | Edureka

🔥𝐄𝐝𝐮𝐫𝐞𝐤𝐚 𝐉𝐚𝐯𝐚 𝐂𝐨𝐮𝐫𝐬𝐞 𝐓𝐫𝐚𝐢𝐧𝐢𝐧𝐠: https://www.edureka.co/java-j2ee-training-course (Use code “𝐘𝐎𝐔𝐓𝐔𝐁𝐄𝟐𝟎”) This Edureka Java Full Course will help you understand the various fundamentals of Java programm…

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 () : This 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

The above code returns “hellohow are you”.

  • 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 }}

In the above code, the first print statement will print “hello how are you” while the second statement will print “hellohow are you” using the trim() function.

The above code will return “hello how are you”.

The above code will return “HELLO HOW ARE YOU”.

  • 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.

The above code will return “Welcome to Edureka”.

In the above code, it will return the value 65 ,66 ,67.

  • 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 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 blog  and we will get back to you.

Course NameDateDetails

Class Starts on 5th October,2024

5th October

SAT&SUN (Weekend Batch)

Recommended videos for you

Learn perl-the jewel of scripting languages, introduction to java/j2ee & soa, building application with ruby on rails framework, microsoft sharepoint-the ultimate enterprise collaboration platform, mastering regex in perl, ms .net – an intellisense way of web development, building web application using spring framework, hibernate mapping on the fly, create restful web application with node.js express, rapid development with cakephp, service-oriented architecture with java, php & mysql : server-side scripting language for web development, effective persistence using orm with hibernate, portal development and text searching with hibernate, hibernate-the ultimate orm framework, node js : steps to create restful web app, microsoft .net framework : an intellisense way of web development, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, node js express: steps to create restful web app, recommended blogs for you, full stack developer salary in india (2024), what is bootstrap testimonial slider and how to design it, how are bootstrap colors implemented, how to implement event handling in java, everything you need to know about variables in java, what is json know how it works with examples, php tutorial: data types and declaration of variables & strings in php, web development tutorial: a complete guide for beginners, an easy way to implement anagram program in java, how to implement interface in php, top java interview questions you must prepare in 2024, parsing xml file using sax parser, what is java a beginner’s guide to java and its evolution, linked list in c: how to implement a linked list in c, array methods in javascript: everything you need to know about array methods, 11 best programming languages for hacking in 2024, know how to reverse a string in java – a beginners guide.

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 Course Online

  • 78k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Mastering Java Programming and Microservices ...

  • 1k Enrolled Learners

Flutter App Development Certification Course

  • 13k Enrolled Learners

Spring Framework Certification Course

  • 12k Enrolled Learners

Node.js Certification Training Course

  • 10k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k 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.

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java string concatenation, string concatenation.

The + operator can be used between strings to combine them. This is called concatenation :

Try it Yourself »

Note that we have added an empty text (" ") to create a space between firstName and lastName on print.

You can also use the concat() method to concatenate two strings:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Java Course
  • 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

String Arrays in Java

In programming, an array is a collection of the homogeneous types of data stored in a consecutive memory location and each data can be accessed using its index. 

In the Java programming language, we have a String data type. The string is nothing but an object representing a sequence of char values. Strings are immutable in java. Immutable means strings cannot be modified in java.

When we create an array of type String in Java, it is called String Array in Java.

To use a String array, first, we need to declare and initialize it. There is more than one way available to do so.

Declaration:

The String array can be declared in the program without size or with size. Below is the code for the same –  

In the above code, we have declared one String array (myString0) without the size and another one(myString1) with a size of 4. We can use both of these ways for the declaration of our String array in java.

Initialization:

In the first method , we are declaring the values at the same line. A second method is a short form of the first method and in the last method first, we are creating the String array with size after that we are storing data into it.

To iterate through a String array we can use a looping statement.

Time Complexity: O(N), where N is length of array. Auxiliary Space: O(1)

So generally we are having three ways to iterate over a string array.  The first method is to use a for-each loop. The second method is using a simple for loop and the third method is to use a while loop. You can read more about iterating over array from Iterating over Arrays in Java

To find an element from the String Array we can use a simple linear search algorithm. Here is the implementation for the same –

In the above code, we have a String array that contains three elements Apple, Banana & Orange. Now we are searching for the Banana. Banana is present at index location 1 and that is our output.

Sorting of String array means to sort the elements in ascending or descending lexicographic order.

We can use the built-in sort() method to do so and we can also write our own sorting algorithm from scratch but for the simplicity of this article, we are using the built-in method.

Here our String array is in unsorted order, so after the sort operation the array is sorted in the same fashion we used to see on a dictionary or we can say in lexicographic order.

String array to String:

To convert from String array to String, we can use a toString() method.

Here the String array is converted into a string and it is stored into a string type variable but one thing to note here is that comma(,) and brackets are also present in the string. To create a string from a string array without them, we can use the below code snippet.

In the above code, we are having an object of the StringBuilder class. We are appending that for every element of the string array (myarr). After that, we are storing the content of the StringBuilder object as a string using the toString() method.

author

Please Login to comment...

Similar reads.

  • Java-Strings
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Get early access and see previews of new features.

String Array Assignment in Java [duplicate]

Error at Line 2: Illegal Start of expression The code works if I say:

Why does this happen, and how should I do the required without generating an error? This also happens with other data types. Would appreciate if you could explain in layman terms .

  • variable-assignment

Stephen Allen's user avatar

  • 4 The compiler want's you to specifiy that {"foo", ...} is meant to be an array, so use new String[]{"foo", ...} . Besides that, do yourself a favor and let variable names start with a lower case character, i.e. String foo instead of String Foo (and I personally like to have the array declaration at the type, i.e. String[] foo ). –  Thomas Commented Sep 24, 2018 at 9:24
  • Initialization and Assignment these are two words that makes the difference. I believe. :) –  miiiii Commented Sep 24, 2018 at 9:28
  • FYI: alternatively, for unmodifiable list rather than simple array, List<String> list = List.of( "foo" , "bar" ) ; as a single line or two lines. –  Basil Bourque Commented Sep 24, 2018 at 9:30
  • normally you have to use new String[] { ...} (this was an always must in earlier versions of Java), but, as a syntactic sugar, the compiler accepts just { ... } in a field declaration or variable declaration. Why? it is specified that way in the Java Language Specification (probably it would be to messy to accept it everywhere) –  user85421 Commented Sep 24, 2018 at 9:44

2 Answers 2

{"foo","Foo"} is an array initializer and it isn't a complete array creation expression :

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values. Java Specification

Use new String[] {"foo","Foo"} instead.

Andrew Tobilko's user avatar

  • What does '§' mean? –  Stephen Allen Commented Sep 24, 2018 at 9:37
  • @StephenAllen a link to a specification section –  Andrew Tobilko Commented Sep 24, 2018 at 9:40
  • 1 @StephenAllen actually it is just an abbreviation for Section Sign - apple.stackexchange.com/q/176968 or en.wiktionary.org/wiki § (happens to be a link to the given section in the Java Language Specification) –  user85421 Commented Sep 24, 2018 at 9:52

You have to initialize the string array:

Modern IDEs give error for not initializing the array objects. You can refer more details here: http://grails.asia/java-string-array-declaration

Nishu Tayal's user avatar

Not the answer you're looking for? Browse other questions tagged java arrays variable-assignment or ask your own question .

  • The Overflow Blog
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • The evolution of full stack engineers
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • subtle racism in the lab
  • What is the purpose of long plastic sleeve tubes around connections in appliances?
  • How to create rounded arrows to highlight inflection points in a TikZ graph?
  • How cheap would rocket fuel have to be to make Mars colonization feasible (according to Musk)?
  • On the convex cone of convex functions
  • Advanced Composite Solar Sail (ACS3) Orbit
  • How are you supposed to trust SSO popups in desktop and mobile applications?
  • Looking for the name of a possibly fictional science fiction TV show
  • What's the best format or way to generate a short-lived access token?
  • Children's book about intelligent bears or maybe cats
  • How Would I Interpret This Harmonically?
  • Are there epistemic vices?
  • Mistake on car insurance policy about use of car (commuting/social)
  • Convert double rocker switch into single digital timer - how to make this work
  • Advice how to prevent sin
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • The Chofetz Chaim's Shocking View of Baalei Teshuva
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • Colossians 1:16 New World Translation renders τα πάντα as “all other things” but why is this is not shown in their Kingdom Interlinear?
  • Can someone confirm this observed bug for `bc`? `scale=0` has no effect!
  • Correct anonymization of submission using Latex
  • Inertia Action on Kummer Sheaves
  • Can the planet Neptune be seen from Earth with binoculars?
  • Would superhuman elites allow for more liberal governance?

string assignment java

COMMENTS

  1. Strings in Java

    Strings in Java

  2. Java Strings

    Java Strings - W3Schools ... Java Strings

  3. String Initialization in Java

    String Initialization in Java

  4. Java String (With Examples)

    Java String (With Examples)

  5. Strings (The Java™ Tutorials > Learning the Java Language

    Strings - Learning the Java Language

  6. String in Java (Examples and Practice)

    Creating Strings. In Java, a String is used to store text. It's a sequence of characters enclosed in double quotes. Here's how you can create a String: String fruit = "Apple"; System.out.println(fruit); In this example, we've created a String variable named fruit and assigned it the value "Apple". When we print it, the output will be: Apple.

  7. Java

    In java, string is an immutable object which means it is constant and can cannot be changed once it is created. In this tutorial we will learn about String class and String methods with examples. ... else it allocates the memory space to the specified string and assign the reference to it.

  8. String (Java Platform SE 8 )

    String (Java Platform SE 8 )

  9. Java String Manipulation: Functions and Methods with EXAMPLE

    In technical terms, the String is defined as follows in the above example-. = new (argument); Now we always cannot write our strings as arrays; hence we can define the String in Java as follows: //Representation of String. String strSample_2 = "ROSE"; In technical terms, the above is represented as: = ; The String Class Java extends the Object ...

  10. Java String

    Java String - javatpoint ... Java String

  11. Concatenating Strings in Java

    Concatenating Strings in Java

  12. Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials

    Assignment, Arithmetic, and Unary Operators

  13. Java Assignment Operators with Examples

    Java Assignment Operators with Examples

  14. Assign a String content to a new String in Java from parameter

    5. String copy = new String(original); Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.

  15. Java String Programs

    Java String Programs

  16. String in Java

    How to Declare String in Java With Examples

  17. Java Strings Concatenation

    Java Strings Concatenation

  18. String Arrays in Java

    String Arrays in Java

  19. java

    The String objects that represent string literals in your Java source code are added to a shared String pool when the classes that defines them are loaded 1.This ensures that all "copies" of a String literal are actually the same object ... even if the literal appears in multiple classes. That is why s3 == s4 is true.. By contrast, when you new a String, a distinct new String object is created.

  20. String Array Assignment in Java

    4. The compiler want's you to specifiy that {"foo", ...} is meant to be an array, so use new String[]{"foo", ...}. Besides that, do yourself a favor and let variable names start with a lower case character, i.e. String foo instead of String Foo (and I personally like to have the array declaration at the type, i.e. String[] foo). - Thomas.