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.

Related Tutorials

Java Library

Guru99

Java String Manipulation: Functions and Methods with EXAMPLE

James Hartman

What are Strings?

A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an array of characters.

So my above string of “ ROSE ” can be represented as the following –

Java String

Why use Strings?

One of the primary functions of modern computer science, is processing human language.

Similarly to how numbers are important to math, language symbols are important to meaning and decision making. Although it may not be visible to computer users, computers process language in the background as precisely and accurately as a calculator. Help dialogs provide instructions. Menus provide choices. And data displays show statuses, errors, and real-time changes to the language.

As a Java programmer, one of your main tools for storing and processing language is going to be the String class.

String Syntax Examples

Now, let’s get to some syntax,after all, we need to write this in Java code isn’t it.

String is an array of characters, represented as:

In technical terms, the String is defined as follows in the above example-

Now we always cannot write our strings as arrays; hence we can define the String in Java as follows:

In technical terms, the above is represented as:

The String Class Java extends the Object class.

  • Program to Print Prime Number From 1 to 100 in Java
  • Palindrome Number Program in Java Using while & for Loop
  • Bubble Sort Algorithm in Java: Array Sorting Program & Example

String Concatenation:

Concatenation is joining of two or more strings.

Have a look at the below picture-

String Syntax Examples

We have two strings str1 = “Rock” and str2 = “Star”

If we add up these two strings, we should have a result as str3= “RockStar”.

Check the below code snippet,and it explains the two methods to perform string concatenation.

First is using “ concat ” method of String class and second is using arithmetic “+” operator. Both results in the same output

Important Java string methods:

Java string methods

Let’s ask the Java String class a few questions and see if it can answer them:

String “Length” Method

How will you determine the length of given String? I have provided a method called as “ length “. Use it against the String you need to find the length.

Expected Output:

String “indexOf” Method

If I know the length, how would I find which character is in which position? In short, how will I find the index of a character?

You answered yourself, buddy, there is an “indexOf” method that will help you determine the location of a specific character that you specify.

String “charAt” Method

Similar to the above question, given the index, how do I know the character at that location?

Simple one again!! Use the “ charAt ” method and provide the index whose character you need to find.

String “CompareTo” Method

Do I want to check if the String that was generated by some method is equal to something that I want to verify with? How do I compare two Strings?

Use the method “ compareTo ” and specify the String that you would like to compare.

Use “compareToIgnoreCase” in case you don’t want the result to be case sensitive.

The result will have the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

String “Contain” Method

I partially know what the string should have contained, how do I confirm if the String contains a sequence of characters I specify?

Use the method “ contains ” and specify the characters you need to check.

Returns true if and only if this string contains the specified sequence of char values.

String “endsWith” Method

How do I confirm if a String ends with a particular suffix? Again you answered it. Use the “endsWith” method and specify the suffix in the arguments.

Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object.

String “replaceAll” & “replaceFirst” Method

I want to modify my String at several places and replace several parts of the String?

Java String Replace, replaceAll and replaceFirst methods. You can specify the part of the String you want to replace and the replacement String in the arguments.

String Java “tolowercase” & Java “touppercase” Method

I want my entire String to be shown in lower case or Uppercase?

Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be converted.

Important Points to Note:

  • String is a Final class ; i.e once created the value cannot be altered. Thus String objects are called immutable.
  • The Java Virtual Machine(JVM) creates a memory location especially for Strings called String Constant Pool . That’s why String can be initialized without ‘new’ keyword.
  • String class falls under java.lang.String hierarchy . But there is no need to import this class. Java platform provides them automatically.
  • String reference can be overridden but that does not delete the content ; i.e., if

String h1 = “hello”;

h1 = “hello”+”world”;

then “hello” String does not get deleted. It just loses its handle.

  • Multiple references can be used for same String but it will occur in the same place ; i.e., if

String h2 = “hello”;

String h3 = “hello”;

then only one pool for String “hello” is created in the memory with 3 references-h1,h2,h3

  • If a number is quoted in ” “ then it becomes a string , not a number anymore. That means if

String S1 =”The number is: “+ “123”+”456″;

System. out .println(S1);

then it will print: The number is: 123456

If the initialization is like this:

String S1 = “The number is: “+(123+456);

System.out.println(S1);

then it will print: The number is:579

That’s all to Strings!

  • Prev Class
  • Next Class
  • No Frames
  • All Classes
  • Summary: 
  • Nested | 
  • Field  | 
  • Constr  | 
  • Detail: 

Class String

  • java.lang.Object
  • java.lang.String
String str = "abc";
char data[] = {'a', 'b', 'c'}; String str = new String(data);
System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); String d = cde.substring(1, 2);

Field Summary

Fields 
Modifier and Type Field and Description
< > objects as by .

Constructor Summary

Constructors 
Constructor and Description
() object so that it represents an empty character sequence.
(byte[] bytes) by decoding the specified array of bytes using the platform's default charset.
(byte[] bytes,  charset) by decoding the specified array of bytes using the specified .
(byte[] ascii, int hibyte)   constructors that take a , charset name, or that use the platform's default charset.
(byte[] bytes, int offset, int length) by decoding the specified subarray of bytes using the platform's default charset.
(byte[] bytes, int offset, int length,  charset) by decoding the specified subarray of bytes using the specified .
(byte[] ascii, int hibyte, int offset, int count)   constructors that take a , charset name, or that use the platform's default charset.
(byte[] bytes, int offset, int length,  charsetName) by decoding the specified subarray of bytes using the specified charset.
(byte[] bytes,  charsetName) by decoding the specified array of bytes using the specified .
(char[] value) so that it represents the sequence of characters currently contained in the character array argument.
(char[] value, int offset, int count) that contains characters from a subarray of the character array argument.
(int[] codePoints, int offset, int count) that contains characters from a subarray of the array argument.
(  original) 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.
(  buffer)
(  builder)

Method Summary

All Methods         
Modifier and Type Method and Description
(int index) value at the specified index.
(int index)
(int index)
(int beginIndex, int endIndex) .
(  anotherString)
(  str)
(  str)
(  s)
(  cs) .
(  sb) .
(char[] data) .
(char[] data, int offset, int count) .
(  suffix)
(  anObject)
(  anotherString) to another , ignoring case considerations.
(  l,  format, ... args)
(  format, ... args)
() into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
(  charset) into a sequence of bytes using the given , storing the result into a new byte array.
(int srcBegin, int srcEnd, byte[] dst, int dstBegin)   method, which uses the platform's default charset.
(  charsetName) into a sequence of bytes using the named charset, storing the result into a new byte array.
(int srcBegin, int srcEnd, char[] dst, int dstBegin)
()
(int ch)
(int ch, int fromIndex)
(  str)
(  str, int fromIndex)
()
() if, and only if, is .
(  delimiter, ... elements) joined together with a copy of the specified .
(  delimiter, <? extends > elements) composed of copies of the joined together with a copy of the specified .
(int ch)
(int ch, int fromIndex)
(  str)
(  str, int fromIndex)
()
(  regex) .
(int index, int codePointOffset) that is offset from the given by code points.
(boolean ignoreCase, int toffset,  other, int ooffset, int len)
(int toffset,  other, int ooffset, int len)
(char oldChar, char newChar) in this string with .
(  target,  replacement)
(  regex,  replacement) with the given replacement.
(  regex,  replacement) with the given replacement.
[] (  regex) .
[] (  regex, int limit) .
(  prefix)
(  prefix, int toffset)
(int beginIndex, int endIndex)
(int beginIndex)
(int beginIndex, int endIndex)
()
() to lower case using the rules of the default locale.
(  locale) to lower case using the rules of the given .
()
() to upper case using the rules of the default locale.
(  locale) to upper case using the rules of the given .
()
(boolean b) argument.
(char c) argument.
(char[] data) array argument.
(char[] data, int offset, int count) array argument.
(double d) argument.
(float f) argument.
(int i) argument.
(long l) argument.
(  obj) argument.

Methods inherited from class java.lang. Object

Methods inherited from interface java.lang. charsequence, field detail, case_insensitive_order, constructor detail.

c == (char)(((hibyte & 0xff) << 8) | ( b & 0xff))

Method Detail

Codepointat, codepointbefore, codepointcount, offsetbycodepoints.

dstBegin + (srcEnd-srcBegin) - 1
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

contentEquals

Equalsignorecase.

  • Applying the method Character.toLowerCase(char) to each character produces the same result Parameters: anotherString - The String to compare this String against Returns: true if the argument is not null and it represents an equivalent String ignoring case; false otherwise See Also: equals(Object)
this.charAt(k)-anotherString.charAt(k)
this.length()-anotherString.length()

compareToIgnoreCase

Regionmatches.

  • There is some nonnegative integer k less than len such that: this.charAt(toffset + k ) != other.charAt(ooffset + k ) Parameters: toffset - the starting offset of the subregion in this string. other - the string argument. ooffset - the starting offset of the subregion in the string argument. len - the number of characters to compare. Returns: true if the specified subregion of this string exactly matches the specified subregion of the string argument; false otherwise.
this.charAt(toffset+k) != other.charAt(ooffset+k)
Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k))
Character.toUpperCase(this.charAt(toffset+k)) != Character.toUpperCase(other.charAt(ooffset+k))
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
this.charAt( k ) == ch
this.codePointAt( k ) == ch
(this.charAt( k ) == ch) && ( k >= fromIndex)
(this.codePointAt( k ) == ch) && ( k >= fromIndex)

lastIndexOf

(this.charAt( k ) == ch) && ( k <= fromIndex)
(this.codePointAt( k ) == ch) && ( k <= fromIndex)
this.startsWith(str, k )
k >= fromIndex && this.startsWith(str, k )
k <= fromIndex && this.startsWith(str, k )
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"

subSequence

str.subSequence(begin, end)
str.substring(begin, end)
"cares".concat("s") returns "caress" "to".concat("get").concat("her") returns "together"
"mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar" "the war of baronets".replace('r', 'y') returns "the way of bayonets" "sparring with a purple porpoise".replace('p', 't') returns "starring with a turtle tortoise" "JonL".replace('q', 'x') returns "JonL" (no change)
Pattern . matches( regex , str )

replaceFirst

Pattern . compile ( regex ). matcher ( str ). replaceFirst ( repl )
Pattern . compile ( regex ). matcher ( str ). replaceAll ( repl )
Regex Limit Result : 2 { "boo", "and:foo" } : 5 { "boo", "and", "foo" } : -2 { "boo", "and", "foo" } o 5 { "b", "", ":and:f", "", "" } o -2 { "b", "", ":and:f", "", "" } o 0 { "b", "", ":and:f" }
Pattern . compile ( regex ). split ( str ,  n )
Regex Result : { "boo", "and", "foo" } o { "b", "", ":and:f" }
For example, String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool"
For example, List<String> strings = new LinkedList<>(); strings.add("Java");strings.add("is"); strings.add("cool"); String message = String.join(" ", strings); //message returned is: "Java is cool" Set<String> strings = new LinkedHashSet<>(); strings.add("Java"); strings.add("is"); strings.add("very"); strings.add("cool"); String message = String.join("-", strings); //message returned is: "Java-is-very-cool"

toLowerCase

Language Code of Locale Upper Case Lower Case Description
tr (Turkish) \u0130 \u0069 capital letter I with dot above -> small letter i
tr (Turkish) \u0049 \u0131 capital letter I -> small letter dotless i
(all) French Fries french fries lowercased all chars in String
(all) lowercased all chars in String

toUpperCase

Language Code of Locale Lower Case Upper Case Description
tr (Turkish) \u0069 \u0130 small letter i -> capital letter I with dot above
tr (Turkish) \u0131 \u0049 small letter dotless i -> capital letter I
(all) \u00df \u0053 \u0053 small letter sharp s -> two letters: SS
(all) Fahrvergnügen FAHRVERGNÜGEN

toCharArray

Copyvalueof.

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .

Scripting on this page tracks web page traffic, but does not change the content in any way.

StringBuffer

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

  • 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 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 28th September,2024

28th September

SAT&SUN (Weekend Batch)

Recommended videos for you

Spring framework : introduction to spring web mvc & spring with bigdata, building web application using spring framework, introduction to java/j2ee & soa, hibernate-the ultimate orm framework, nodejs – communication and round robin way, portal development and text searching with hibernate, node js express: steps to create restful web app, ms .net – an intellisense way of web development, node js : steps to create restful web app, service-oriented architecture with java, implementing web services in java, building application with ruby on rails framework, learn perl-the jewel of scripting languages, rapid development with cakephp, microsoft sharepoint-the ultimate enterprise collaboration platform, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, microsoft .net framework : an intellisense way of web development, effective persistence using orm with hibernate, a day in the life of a node.js developer, recommended blogs for you, everything you need to know about phpstorm, how to create a file in java – file handling concepts, understanding java input and output, all you need to know about array search in php, dynamic data allocation in java, how to create a bootstrap button, how to build a regular expression in php, how to handle custom exceptions in java, know how to build rest api with node.js from scratch, linked list in c: how to implement a linked list in c, 5 ways for comparing two strings in java, how to implement virtual function in c++, how to implement quicksort in java.

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

Flutter App Development Certification Course

  • 13k Enrolled Learners

Mastering Java Programming and Microservices ...

  • 1k 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

Comprehensive Java Course Certification Train ...

  • 19k 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 Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Java is a popular programming language that software developers use to construct a wide range of applications. It is a simple, robust, and platform-independent object-oriented language. There are various types of assignment operators in Java, each with its own function.

In this section, we will look at Java's many types of assignment operators, how they function, and how they are utilized.

To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side.

In the above example, the variable x is assigned the value 10.

To add a value to a variable and subsequently assign the new value to the same variable, use the addition assignment operator (+=). It takes the value on the right side of the operator, adds it to the variable's existing value on the left side, and then assigns the new value to the variable.

To subtract one numeric number from another, use the subtraction operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we create two integer variables, a and b, subtract b from a, and then assign the result to the variable c.

To combine two numerical numbers, use the multiplication operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, multiply their values using the multiplication operator, and then assign the outcome to the third variable, c.

To divide one numerical number by another, use the division operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, divide them by one another using the division operator, and then assign the outcome to the variable c.

It's vital to remember that when two numbers are divided, the outcome will also be an integer, and any residual will be thrown away. For instance:

The modulus assignment operator (%=) computes the remainder of a variable divided by a value and then assigns the resulting value to the same variable. It takes the value on the right side of the operator, divides it by the current value of the variable on the left side, and then assigns the new value to the variable on the left side.





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

  • ▼Java Exercises
  • ▼Java Basics
  • Basic Part-I
  • Basic Part-II
  • ▼Java Data Types
  • Java Enum Types
  • ▼Java Control Flow
  • Conditional Statement
  • Recursive Methods
  • ▼Java Math and Numbers
  • ▼Object Oriented Programming
  • Java Constructor
  • Java Static Members
  • Java Nested Classes
  • Java Inheritance
  • Java Abstract Classes
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • Object-Oriented Programming
  • ▼Exception Handling
  • Exception Handling Home
  • ▼Functional Programming
  • Java Lambda expression
  • ▼Multithreading
  • Java Thread
  • Java Multithreading
  • ▼Data Structures
  • ▼Strings and I/O
  • File Input-Output
  • ▼Date and Time
  • ▼Advanced Concepts
  • Java Generic Method
  • ▼Algorithms
  • ▼Regular Expressions
  • Regular Expression Home
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java String: Exercises, Practice, Solution

Java string exercises [112 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

1. Write a Java program to get the character at the given index within the string.

Sample Output:

Click me to see the solution

2. Write a Java program to get the character (Unicode code point) at the given index within the string.

3. Write a Java program to get the character (Unicode code point) before the specified index within the string.

4. Write a Java program to count Unicode code points in the specified text range of a string.

5. Write a Java program to compare two strings lexicographically. Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions.

6. Write a Java program to compare two strings lexicographically, ignoring case differences.

7. Write a Java program to concatenate a given string to the end of another string.

8. Write a Java program to test if a given string contains the specified sequence of char values.

9. Write a Java program to compare a given string to the specified character sequence.

10. Write a Java program to compare a given string to a specified string buffer.

11. Write a Java program to create a String object with a character array.

12. Write a Java program to check whether a given string ends with another string.

13. Write a Java program to check whether two String objects contain the same data.

14. Write a Java program to compare a given string to another string, ignoring case considerations.

15. Write a Java program to print the current date and time in the specified format.

16. Write a Java program to get the contents of a given string as a byte array.

17. Write a Java program to get the contents of a given string as a character array.

18. Write a Java program to create a distinct identifier for a given string.

19. Write a Java program to get the index of all the characters of the alphabet.

Sample string of all alphabet: "The quick brown fox jumps over the lazy dog."

20. Write a Java program to get the Canonical representation of the string object.

21. Write a Java program to get the last index of a string within a string.

22. Write a Java program to get the length of a given string.

23. Write a Java program to find out whether a region in the current string matches a region in another string.

24. Write a Java program to replace a specified character with another character.

25. Write a Java program to replace each substring of a given string that matches the given regular expression with the given replacement.

Sample string : "The quick brown fox jumps over the lazy dog."

In the above string replace all the fox with cat.

26. Write a Java program to check whether a given string starts with another string.

27. Write a Java program to get a substring of a given string at two specified positions.

28. Write a Java program to create a character array containing a string.

29. Write a Java program to convert all characters in a string to lowercase.

30. Write a Java program to convert all characters in a string to uppercase.

31. Write a Java program to trim leading or trailing whitespace from a given string.

32. Write a Java program to find the longest Palindromic Substring within a string.

33. Write a Java program to find all interleavings of given strings.

34. Write a Java program to find the second most frequent character in a given string.

35. Write a Java program to print all permutations of a given string with repetition.

36. Write a Java program to check whether two strings interlive of a given string. Assuming that unique characters are present in both strings.

37. Write a Java program to find the length of the longest substring of a given string without repeating characters.

38. Write a Java program to print the result of removing duplicates from a given string.

39. Write a Java program to find the first non-repeating character in a string.

40. Write a Java program to divide a string into n equal parts.

41. Write a Java program to remove duplicate characters from a given string that appear in another given string.

42. Write a Java program to print a list of items containing all characters of a given word.

43. Write a Java program to find the character in a string that occurs the most frequently.

44. Write a Java program to reverse a string using recursion.

45. Write a Java program to reverse words in a given string.

46. Write a Java program to reverse every word in a string using methods.

47. Write a Java program to rearrange a string so that the same characters are positioned a distance away.

48. Write a Java program to remove "b" and "ac" from a given string.

49. Write a Java program to find the first non-repeating character from a stream of characters.

50. Write a Java program to find the lexicographic rank of a given string.

N.B.: Total possible permutations of BDCA are(lexicographic order) : ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA 1   2   3   4   5   6   7   8   9   10   11   12 The BDCA appear in 12 position of permutation (lexicographic order).

51. Write a Java program to count and print all duplicates in the input string.

52. Write a Java program to check if two given strings are rotations of each other.

53. Write a Java program to match two strings where one string contains wildcard characters.

54. Write a Java program to find the smallest window in a string containing all characters in another string.

55. Write a Java program to remove all adjacent duplicates recursively from a given string.

56. Write a Java program that appends two strings, omitting one character if the concatenation creates double characters.

57. Write a Java program to create a string from a given string by swapping the last two characters of the given string. The string length must be two or more.

58. Write a Java program to read a string and return true if it ends with a specified string of length 2.

59. Write a Java program to read a string. If the string begins with "red" or "black" return that color string, otherwise return the empty string.

60. Write a Java program to read two strings append them together and return the result. If the strings are different lengths, remove characters from the beginning of the longer string and make them equal lengths.

61. Write a Java program to create a new string taking specified number of characters from first and last position of a given string.

62. Write a Java program to read a string and return true if "good" appears starting at index 0 or 1 in the given string.

63. Write a Java program to check whether the first two characters appear at the end of a given string.

64. Write a Java program to read a string. If a substring of length two appears at both its beginning and end, return a string without the substring at the beginning; otherwise, return the original string unchanged.

65. Write a Java program to read a given string and return the string without the first or last characters if they are the same, otherwise return the string without the characters.

66. Write a Java program to read a string and return it without the first two characters. Keep the first character if it is 'g' and keep the second character if it is 'h'.

67. Write a Java program to read a string and remove the first two characters if one or both are equal to a specified character, otherwise leave them unchanged.

68. Write Java program to read a string and return after removing specified characters and their immediate left and right adjacent characters.

69. Write a Java program to return the substring that is between the first and last appearance of the substring 'toast' in the given string, or return an empty string if the substring 'toast' does not exist.

70. Write a Java program that checks if a string has pq-balance if it contains at least one 'q' directly after each ‘p’. But a 'q' before the 'p' invalidates pq-balance.

71. Write a Java program to check two given strings whether any of them appears at the end of the other string (ignore case sensitivity).

72. Write a Java program to return true if a given string contains the string 'pop', but the middle 'o' also may contain another character.

73. Write a Java program to check whether a substring appears before a period(.) within a given string.

74. Write a Java program to check whether a prefix string created using the first specific character in a given string appears somewhere else in the string.

75. Write a Java program to check whether a given substring appears in the middle of another string. Here middle means the difference between the number of characters to the left and right of the given substring is not more than 1.

76. Write a Java program to count how many times the substring 'life' appears anywhere in a given string. Counting can also happen with the substring 'li?e', any character instead of 'f'.

77. Write a Java program to add a string with a specific number of times separated by a substring.

78. Write a Java program to repeat a specific number of characters for a specific number of times from the last part of a given string.

79. Write a Java program to create a string from a given string. This is done after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string.

80. Write a Java program to check whether the character immediately before and after a specified character is the same in a given string.

81. Write a Java program to check whether two strings of length 3 and 4 appear the same number of times in a given string.

82. Write a Java program to create a string containing every character twice of a given string.

83. Write a Java program to create a string from two given strings. This is so that each character of the two strings appears individually in the created string.

84. Write a Java program to make an original string made of p number of characters from the first character in a given string. This is followed by p-1 number of characters till p is greater than zero.

85. Write a Java program to make up a string with each character before and after a non-empty substring whichever it appears in a non-empty given string.

86. Write a Java program to count the number of triples (characters appearing three times in a row) in a given string.

87. Write a Java program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a string.

88. Write a Java program to return a string where every appearance of the lowercase word 'is' has been replaced with 'is not'.

89. Write a Java program to calculate the sum of the numbers that appear in a given string.

90. Write a Java program to check the number of times the two substrings appearing anywhere in a string.

91. Write a Java program to count the number of words ending in 'm' or 'n' (not case sensitive) in a given text.

92. Write a Java program that returns a substring after removing all instances of remove string as given from the given main string.

93. Write a Java program to find the longest substring that appears at both ends of a given string.

94. Write a Java program to find the longest mirror image string at both ends of a given string.

95. Write a Java program to return the sum of the digits present in the given string. In the absence of digits, the sum is 0.

96. Write a Java program to create a new string after removing a specified character from a given string. This is except the first and last position.

97. Write a Java program to return a string with characters at index positions 0,1,2,5,6,7, ... from a given string.

98. Write a Java program to check whether the first instance of a given character is immediately followed by the same character in a given string.

99. Write a Java program to return an updated string using every character of even position from a given string.

100. Write a Java program to check if a given string contains another string. Returns true or false.

101. Write a Java program to test if a string contains only digits. Returns true or false.

102. Write a Java program to convert a given string to int, long, floating and double.

103. Write a Java program to remove a specified character from a given string.

104. Write a Java program to sort in ascending and descending order by the length of the given array of strings.

105. Write a Java program to count the occurrences of a given string in another given string.

106. Write a Java program to concatenate a given string with itself a given number of times.

107. Write a Java program to count occurrences of a certain character in a given string.

108. Write a Java program to check whether there are two consecutive (following each other continuously), identical letters in a given string.

109. Write a Java program that reverses all odd-length words in a string.

110. Write a Java program to count the number of characters (alphanumeric only) that occur more than twice in a given string.

111. Write a Java program that removes a specified word from given text. Return the updated string..

112. A string is created by using another string's letters. Letters are case sensitive. Write a Java program that checks the letters of the second string are present in the first string. Return true otherwise false.

Java Code Editor

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • 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
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

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

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Advertisement

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

Operator Name Example Try it
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example Try it
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001  1
| OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101  5
~ NOT - Inverts all the bits ~ 5  ~0101 1010  10
^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100  4
<< Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4

Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

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.

Remove All Elements From a String Array in Java

Last updated: August 20, 2024

string assignment in java

It's finally here:

>> The Road to Membership and Baeldung Pro .

Going into ads, no-ads reading , and bit about how Baeldung works if you're curious :)

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

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

1. Overview

In Java, working with arrays is a common task when dealing with collections of data. Sometimes, we may find ourselves in situations where we need to remove all elements from a String array. This task is straightforward, though it requires us to consider how arrays work in Java.

In this quick tutorial, let’s explore how to remove all elements from a String array.

2. Introduction to the Problem

Removing all elements from an array can be helpful in cleaning up data or resetting the array for new input. Before we dive into the implementations, let’s quickly understand how arrays work in Java.

Arrays in Java are fixed in size. In other words, once we create an array, we cannot change its length. This characteristic impacts how we handle operations like “removing” or “inserting” elements, which is not as simple as in Collections like ArrayList .

When we talk about removing all elements from a String array, we have two options:

  • Reinitialize a new array (Depending on the requirement, the new array can be empty or the same size.)
  • Reset all elements in the array to null values.

Next, let’s take a closer at these two approaches. For simplicity, we’ll leverage unit test assertions to verify if each approach works as expected.

3. Non-Final Array Variable: Reinitializing and Reassignment

The idea of this approach is pretty straightforward. Let’s say we have one array variable,  myArray , containing some elements. To empty myArray , we can reinitialize an empty array and reassign it to the myArray variable.

Next, let’s understand how it works through an example:

In this example, we’re creating a new array of size 0 and assigning it back to myArray1 . This effectively removes all elements by creating an entirely new, empty array.

Sometimes, we want the new array to have the same length as the original one. In this case, we can initialize the new array with the desired size:

As the test shows, the new array has the same size (6) as the original one, and all elements are null values.

Removing all elements by reinitializing and reassignment is straightforward. This approach is useful if we want to completely reset the array and potentially use a different size . However, since we need to assign the new array back to the same variable, this approach works only if the array variable isn’t  final .

Next, let’s explore how to remove all array elements if the array variable is declared as final .

4. Resetting All Elements to null

We’ve mentioned that arrays in Java are fixed in size. That is to say, when an array has been initialized and assigned to a final variable, we cannot remove its elements to get an empty array ( length=0 ) .

One approach to “removing” elements from an array is to set each element to null . This method doesn’t change the array’s size but effectively clears its content.

Next, let’s check an example:

As the above example shows, we loop through myArray and assign a null to each element. After running the loop, the array myArray will still have the same length, but all its elements will be null .

5. Using the Arrays.fill() Method

Java’s Arrays class provides a convenient fill() method that allows us to set all elements of an array to a specific value . We can use this method to set all elements to null , similar to the resetting in loop approach, but with less code:

As we can see, using the Arrays.fill() method , we can achieve array resetting with a single line of code, making it more concise.

6. Conclusion

Removing all elements from an array in Java is a common task when working with arrays, and it can be done in several ways.

In this article, we’ve explored three different approaches to achieve that through examples:

  • Reinitializing the array – This is ideal when we want to start fresh with a new array, possibly of a different size. However, it only works for non-final array variables.
  • Resetting to null – This is appropriate to clear the content but maintain the array size for future use.
  • Using Arrays.fill() – A clean and concise way to reset all elements when maintaining array size.

By understanding the available options, we can choose the best approach for our specific situation, ensuring our code is efficient and clear.

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

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

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:

Build your API with SPRING - book cover

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

Java: assign String[] array element to a String?

I'm pretty new at this, and this is probably a pretty obvious answer. In my csv script, i'm trying to figure out how to read a csv file using the CSVReader class and write to a new csv file. The error is telling me writeNext(java.lang.String[]) cannot be applied to (java.lang.String). I've tried using a direct assignment and getString() method however nothing works. Any ideas?

I have the following code: UPDATED

Error: c:\java\examples\ETHImport.java:46: cannot find symbo symbol : variable newRow location: class ETHImport writer2.writeAll(newRow);

Thanks in advance.

phill's user avatar

  • I'm tired and lazy and don't care enough to do everything for you: where does the error occur? –  Pesto Commented May 27, 2009 at 20:01
  • In your new code, you're simply missing "new". It should be "String [] newRow = new String[] ..." –  Michael Myers ♦ Commented May 27, 2009 at 20:58
  • cool.. that really helped..not sure why i'm getting a on the variable thats declared in the while loop –  phill Commented May 27, 2009 at 21:05
  • See the comment in my answer - you need writer2.writeNext(newRow) inside the loop. Remove the line outside it. –  Jon Skeet Commented May 27, 2009 at 21:54

4 Answers 4

You need a string array, not a single string. Are you really sure you want to pull all the values into a single string to start with? I'd expect writeNext to write a single line based on the string values you give it, with it putting in the commas etc. After all, it's a CsvWriter - it should be doing the comma separating.

It looks to me like the writeAll method you're already using does what you want it to, and writeNext will just write a single line... what are you trying to achieve that writeAll doesn't do for you? Why do you need to read it line by line and construct entries in the first place? Can't you just call:

My guess is that's going to write a tab -separated file though, given how writer2 is constructed.

EDIT: Given the additional information in the comments, I suspect you want to:

  • Open a CsvReader
  • Open a CsvWriter (with an appropriate Writer and ; as the constructor arguments)
  • Loop reading a line at a time as a string array (using CsvReader.readNext() ), creating a new string array for the output, and then calling CsvWriter.writeNext() to write that string array out to the file.
  • Close the CsvReader and CsvWriter in finally blocks (so they'll still get closed if anything goes wrong)

Building the new string array from the existing one would be something like (following your example):

That would basically just keep the first three columns, switching round the second and third ones. If you need other columns, just change it in the same kind of way.

Note that I wouldn't recommend using FileWriter to write to a file - use a FileOutputStream and an OutputStreamWriter chained onto it, as this lets you set the character encoding instead of using the platform default one.

Jon Skeet's user avatar

  • I'm pretty sure you're right. The Javadoc for CsvWriter agrees with your expectation, but I haven't ever used it. –  Matt K Commented May 27, 2009 at 20:04
  • the goal is to extract a select number of columns in the csv file, manipulate/format some of them and then insert them into an output file with commas and using a semicolon as a line terminator. The writeall just dumps everything out rather than just outputing the columns i need –  phill Commented May 27, 2009 at 20:15
  • I updated it with the suggested changes however i'm resulting in a different error now. It is saying '.class' is expected and there is an carrot pointing to nextLine.. Is it correct syntax to declare a string like this in a while loop? –  phill Commented May 27, 2009 at 20:54
  • I'm not sure why you've got an error like that, but you're trying to use newRow outside the loop. You should be calling writer2.writeNext(newRow); inside the loop. –  Jon Skeet Commented May 27, 2009 at 21:46

It is expecting an array of entries rather than just one String. If you are following this example http://opencsv.sourceforge.net/ notice that

the split call at the end results in a String[].

for your code:

Clint's user avatar

  • what i'm struggling with is just building a string with selected columns for each recordset so i can write it to a new file –  phill Commented May 27, 2009 at 20:17
  • You shouldn't be building a string. You should be building a string array with the selected columns. –  Jon Skeet Commented May 27, 2009 at 20:22
  • awesome! I didn't know i could declare something in a method. thanks! –  phill Commented May 27, 2009 at 21:16

To easily put a String into a String[] use:

or the shortcut

Now entriesArr is a String[] containing one element, entries .

jjnguy's user avatar

  • Or the shortcut, as this is a declaration: String[] strs = { str }; –  Tom Hawtin - tackline Commented May 27, 2009 at 21:19
  • Note that the element should be a String literal value, so actually the line should be String[] entriesArr = new String[] {"entries"}. –  portfoliobuilder Commented Feb 12, 2015 at 0:42

writer.writeNext(String[]) is looking for an array that it will then write as "[0],[1],[2]"

Since you are storing the entire csv file as one string, you need to split that string backup. Really you should instead not combine every item into one string but instead store it as an array of strings representing each individual line in the csv file.

Stephan's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

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

  • The Overflow Blog
  • LLMs evolve quickly. Their underlying architecture, not so much.
  • From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • In theory, could an object like 'Oumuamua have been captured by a three-body interaction with the sun and planets?
  • My enemy sent me this puzzle!
  • Is it OK to make an "offshape" bid if you can handle any likely response?
  • What are the limits of Terms of Service as a legal shield for a company?
  • How does current in the cable shield affect the signal in the wires within
  • Why are volumes of revolution typically taught in Calculus 2 and not Calculus 3?
  • Inconsistent “unzip -l … | grep -q …” results with pipefail
  • Create k nodes evenly spaced below another node
  • What's the origin of the colloquial "peachy", "simply peachy", and "just peachy"?
  • "can-do" vs. "can-explain" fallacy
  • A short story about a SF author telling his friends, as a joke, a harebrained SF story, and what follows
  • How does one go about writing papers as a nobody?
  • Electric skateboard: helmet replacement
  • Solve an equation perturbatively
  • What food plants/algae are viable to grow 9,000 meters beneath the sea, if given plenty of light and air?
  • Is it possible to create a board position where White must make the move that leads to stalemating Black to avoid Black stalemating White?
  • Did US troops insist on segregation in British pubs?
  • Why cant we save the heat rejected in a heat engine?
  • When a submarine blows its ballast and rises, where did the energy for the ascent come from?
  • How to make a ParametricPlot3D into solid shape
  • using a tikz foreach loop inside a newcommand
  • Can my players use both 5e-2014 and 5e-2024 characters in the same adventure?
  • How can I draw water level in a cylinder like this?
  • If physics can be reduced to mathematics (and thus to logic), does this mean that (physical) causation is ultimately reducible to implication?

string assignment in java

IMAGES

  1. Java String

    string assignment in java

  2. Introduction to Strings in Java

    string assignment in java

  3. java for complete beginners

    string assignment in java

  4. Java String startsWith() Method with examples

    string assignment in java

  5. Java Assignment Operators

    string assignment in java

  6. Java Assignment operators

    string assignment in java

COMMENTS

  1. Strings in Java

    Ways of Creating a String. There are two ways to create a string in Java: String Literal. Using new Keyword. Syntax: <String_Type> <string_variable> = "<sequence_of_string>"; . 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. Java Strings

    String Length. A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method: ... Fill in the missing part to create a greeting variable of type String and assign it the value Hello.

  3. String with new keyword and direct assignment in java

    In Java 7 that's in the Heap with other objects, but prior to that it was created in the Perm-Gen. String s = "hi"; String s1 = new String("hi"); new String("hi") creates a new String object on the heap, separate from the existing one. s and s1 are references to the two separate objects. References themselves actually live on the stack, even ...

  4. Java String (With Examples)

    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, // create a string String type = "Java programming"; Here, we have created a string variable named type.The variable is initialized with the string Java Programming.

  5. String Initialization in Java

    5. String Initialization Using new. We'll see some different behavior, though, if we use the new keyword. String newStringOne = new String ( "Baeldung" ); String newStringTwo = new String ( "Baeldung" ); Although the value of both String s will be the same as earlier, we'll have to different objects this time:

  6. Java String

    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.

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

    Creating Strings. The most direct way to create a string is to write: String greeting = "Hello world!"; 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 ...

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

  9. String (Java Platform SE 8 )

    Constructor and Description. String () Initializes a newly created String object so that it represents an empty character sequence. String (byte[] bytes) Constructs a new String by decoding the specified array of bytes using the platform's default charset.

  10. Java Strings Operators

    The assignment operator is used to assign values to string objects. The size of the resulting string object will be the number of characters in the string value being assigned. The size of the resulting string object will be the number of characters in the string value being assigned.

  11. String in Java

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

  12. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  13. Java String Programs

    A String in Java is a sequence of characters that can be used to store and manipulate text data and It is basically an array of characters that are stored in a sequence of memory locations. All the strings in Java are immutable in nature, i.e. once the string is created we can't change it. This article provides a variety of programs on strings, that are frequently asked in the technical ...

  14. Types of Assignment Operators in Java

    To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side. Example: int x = 10; int x = 10; In the above example, the variable x is assigned the value 10.

  15. Java Exercises: String exercises

    5. Write a Java program to compare two strings lexicographically. Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions. Sample Output: String 1: This is Exercise 1 String 2: This is Exercise 2 "This is Exercise 1" is less than "This is Exercise 2".

  16. String Arrays 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 -. String[] myString0; // without size. String[] myString1=new String[4]; //with size.

  17. Java String Reference

    Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer. boolean. copyValueOf () Returns a String that represents the characters of the character array. String. endsWith () Checks whether a string ends with the specified character (s) boolean.

  18. Java Operators

    Java Comparison Operators. Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If ...

  19. String Array Assignment in Java

    I believe. :) FYI: alternatively, for unmodifiable list rather than simple array, List<String> list = List.of( "foo" , "bar" ) ; as a single line or two lines. 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 ...

  20. Remove All Elements From a String Array in Java

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

  21. java

    I am new to JAVA programming. I have read it in my book. String a="Hello"; String b="Hello"; System.out.println(a==b); This should return false as a & b refer to different instances of String objects.. Bcoz the assignments operator compares the instances of objects but Still I am getting a true. I am using Eclipse IDE.

  22. Java: assign String[] array element to a String?

    To easily put a String into a String[] use: or the shortcut. Now entriesArr is a String[] containing one element, entries. Note that the element should be a String literal value, so actually the line should be String [] entriesArr = new String [] {"entries"}.