Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java variables.

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name ). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Create a variable called name of type String and assign it the value " John ":

Try it Yourself »

To create a variable that should store a number, look at the following example:

Create a variable called myNum of type int and assign it the value 15 :

You can also declare a variable without assigning the value, and assign the value later:

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Change the value of myNum from 15 to 20 :

Final Variables

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):

Other Types

A demonstration of how to declare variables of other types:

You will learn more about data types in the next section.

Test Yourself With Exercises

Create a variable named carName and assign the value Volvo to it.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Vertex Academy

How to assign a value to a variable in java.

Facebook

The assigning of a value to a variable is carried out with the help of the "=" symbol.   Consider the following examples:

Example No.1

Let’s say we want to assign the value of "10" to the variable "k" of the "int" type. It’s very easy and can be done in two ways:

If you try to run this code on your computer, you will see the following:

In this example, we first declared the variable to be "k" of the "int" type:

Then in another line we assigned the value "10" to the variable "k":

As you you may have understood from the example, the "=" symbol is an assignment operation. It always works from right to left:

Variables Announement Vertex Academy

This assigns the value "10" to the variable "k."

As you can see, in this example we declared the variable as "k" of the int type and assigned the value to it in a single line:

int k = 10;

So, now you know that:

  • The "=" symbol is responsible for assignment operation and we assign values to variables with the help of this symbol.
  • There are two ways to assign a value to variables: in one line or in two lines.

What is variable initialization?

Actually, you already know what it is. Initialization is the assignment of an initial value to a variable. In other words, if you just created a variable and didn’t assign any value to it, then this variable is uninitialized. So, if you ever hear:

  • “We need to initialize the variable,” it simply means that “we need to assign the initial value to the variable.”
  • “The variable has been initialized,” it simply means that “we have assigned the initial value to the variable.”

Here's another example of variable initialization:

Example No.2

15 100 100000000 I love Java M 145.34567 3.14 true

In this line, we declared variable number1 of the byte type and, with the help of the "=" symbol, assigned the value 15 to it.

In this line, we declared variable number2 of the short type and, with the help of the "=" symbol, assigned the value 100 to it.

In this line, we declared variable number3 of the long type and, with the help of the "=" symbol, assigned the value 100000000 to it.

In this line, we declared the variable title of the string type and, with the help of the "=" symbol, assigned the value “I love Java” to it. Since this variable belongs to the string type, we wrote the value of the variable in double quotes .

In this line, we declared the variable letter of the char type and, with the help of the "=" symbol, assigned the value “M” to it. Note that since the variable belongs to the char type, we wrote the value of the variable in single quotes .

In this line, we declared the variable sum of the double type and, with the help of the "=" symbol, assigned the value "145.34567" to it.

In this line, we declared the variable pi of the float type and, with the help of the "=" symbol, assigned the value “3.14f” to it. Note that we added f to the number 3.14. This is a small detail that you'll need to remember: it's necessary to add f to the values of float variables.  However, when you see it in the console, it will show up as just 3.14 (without the "f").

In this line, we declared the variable result of the boolean type and, with the help of the "=" symbol, assigned the value "true" to it.

Then we display the values of all the variables in the console with the help of

LET’S SUMMARIZE:

  • We assign a value to a variable with the help of the assignment operator "=." It always works from right to left.

assign value to a variable Vertex Academy

2. There are two ways to assign a value to a variable:

  • in two lines
  • or in one line
  • You also need to remember:

If we assign a value to a variable of the string type, we need to put it in double quotes :

If we assign a value to a variable of the char type, we need to put it in single quotes :

If we assign a value to a variable of the float type, we need to  add the letter "f" :

  • "Initialization" means “to assign an initial value to a variable.”

Facebook

  • ← How do you add comments to your code?
  • Operators in Java →

You May Also Like

How do you display messages in the console, java - variable types. how to create a variable in java, software configuration.

Learn Java practically and Get Certified .

Popular Tutorials

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

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

Java Flow Control

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

Java OOP (I)

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

Java Strings

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

Java OOP (II)

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

Java OOP (III)

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

Java Reader/Writer

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

Additional Topics

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

Java Tutorials

Java String equals()

Java String intern()

Java String compareTo()

  • Java String 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:

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

  • ALL OUR FREE COURSES
  • | 1-Page Articles
  • | Android Programming
  • | Beginners Computing
  • | Data Analysis - Pandas
  • | Excel VBA Programming
  • | Games Programming
  • | Java for Beginners
  • | Javascript for Beginners
  • | Microsoft Access
  • | Microsoft Word
  • | Microsoft Excel
  • | Microsoft Power BI
  • | PHP for Beginners
  • | Python for Beginners
  • | Visual Basic .NET
  • | Web Design

String Variables

Start a new project for this by clicking File > New Project from the menu bar at the top of NetBeans. When the New Project dialogue box appears, make sure Java and Java Application are selected :

Click Next and type StringVars as the Project Name. Make sure there is a tick in the box for Create Main Class . Then delete Main after stringvars , and type StringVariables instead, as in the following image:

So the Project Name is StringVars , and the Class name is StringVariables . Click the Finish button and your coding window will look like this (we've deleted all the default comments). Notice how the package name is all lowercase (stringvars) but the Project name was StringVars.

To set up a string variable, you type the word String followed by a name for your variable. Note that there's an uppercase "S" for String. Again, a semicolon ends the line:

String first_name ;

Assign a value to your new string variable by typing an equals sign. After the equals sign the text you want to store goes between two sets of double quotes:

first_name = "William";

If you prefer, you can have all that on one line:

String first_name = "William";

Set up a second string variable to hold a surname/family name:

String family_name = "Shakespeare";

To print both names, add the following println( ):

System.out.println( first_name + " " + family_name );

In between the round brackets of println , we have this:

first_name + " " + family_name

We're saying print out whatever is in the variable called first_name . We then have a plus symbol, followed by a space. The space is enclosed in double quotes. This is so that Java will recognise that we want to print out a space character. After the space, we have another plus symbol, followed by the family_name variable.

Although this looks a bit messy, we're only printing out a first name, a space, then the family name. Your code window should look like this:

Run your programme and you should see this in the Output window:

If you are storing just a single character, then the variable you need is char (lowercase "c"). To store the character, you use single quotes instead of double quotes. Here's our programme again, but this time with the char variable:

If you try to surround a char variable with double quotes, NetBeans will underline the offending code in red, giving you "incompatible type" errors. You can, however, have a String variable with just a single character. But you need double quotes. So this is OK:

String first_name = "W";

But this is not:

String first_name = 'W';

The second version has single quotes, while the first has double quotes.

There are lot more to strings, and you'll meet them again later. For now, let's move on and get some input from a user.

<-- Operator Precedence | User Input -->

Email us: enquiry at homeandlearn.co.uk

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Web Browser

Related Articles

  • Java Programs - Java Programming Examples

Java Basic Programs

  • How to Read and Print an Integer value in Java
  • Ways to read input from console in Java
  • Java Program to Multiply two Floating-Point Numbers
  • Java Program to Swap Two Numbers
  • Java Program to Add Two Binary Strings
  • Java Program to Add two Complex Numbers
  • Java Program to Check if a Given Integer is Odd or Even
  • Java Program to Find the Largest of three Numbers
  • Java Program to Find LCM of Two Numbers
  • Java Program to Find GCD or HCF of Two Numbers
  • Java Program to Display All Prime Numbers from 1 to N
  • Java Program to Find if a Given Year is a Leap Year
  • Java Program to Check Armstrong Number between Two Integers
  • Java Program to Check If a Number is Neon Number or Not
  • Java Program to Check Whether the Character is Vowel or Consonant
  • Java Program for factorial of a number
  • Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
  • Java Program to Calculate Simple Interest
  • Java Program for compound interest
  • Java Program to Find the Perimeter of a Rectangle

Java Pattern Programs

  • Java Program to Print Right Triangle Star Pattern
  • Java Program to Print Left Triangle Star Pattern
  • Java Program to Print Pyramid Number Pattern
  • Java Program to Print Reverse Pyramid Star Pattern
  • Java Program to Print Upper Star Triangle Pattern
  • Java Program to Print Mirror Upper Star Triangle Pattern
  • Java Program to Print Downward Triangle Star Pattern
  • Java Program to Print Mirror Lower Star Triangle Pattern
  • Java Program to Print Star Pascal’s Triangle
  • Java Program to Print Diamond Shape Star Pattern
  • Java Program to Print Square Star Pattern
  • Java Program to Print Pyramid Star Pattern
  • Java Program to Print Spiral Pattern of Numbers

Java Conversion Programs

  • Java Program to Convert Binary to Octal
  • Java Program to Convert Octal to Decimal
  • Java Program For Decimal to Octal Conversion
  • Java Program For Hexadecimal to Decimal Conversion
  • Java Program For Decimal to Hexadecimal Conversion
  • Java Program for Decimal to Binary Conversion
  • Boolean toString() method in Java with examples
  • Convert String to Double in Java
  • Java Program to Convert Double to String
  • Java Program to Convert String to Long
  • Java Program to Convert Long to String
  • Java Program For Int to Char Conversion
  • Java Program to Convert Char to Int

Java Classes and Object Programs

  • Classes and Objects in Java
  • Abstract Class in Java
  • Singleton Method Design Pattern in Java
  • Interfaces in Java
  • Encapsulation in Java
  • Inheritance in Java
  • Abstraction in Java
  • Difference Between Data Hiding and Abstraction in Java
  • Polymorphism in Java
  • Method Overloading in Java
  • Overriding in Java
  • Super Keyword in Java
  • 'this' reference in Java
  • static Keyword in Java
  • Access Modifiers in Java

Java Methods Programs

  • Java main() Method - public static void main(String[] args)
  • Difference between static and non-static method in Java
  • HashTable forEach() method in Java with Examples
  • StringBuilder toString() method in Java with Examples
  • StringBuffer codePointAt() method in Java with Examples
  • How compare() method works in Java
  • Short equals() method in Java with Examples
  • Difference Between next() and hasNext() Method in Java Collections
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java

Java Searching Programs

  • Java Program for Linear Search
  • Binary Search in Java
  • Java Program To Recursively Linearly Search An Element In An Array

Java 1-D Array Programs

  • Check if a value is present in an Array in Java
  • Java Program to find largest element in an array
  • Arrays.sort() in Java with examples
  • Java Program to Sort the Array Elements in Descending Order
  • Java Program to Sort the Elements of an Array in Ascending Order
  • Remove duplicates from Sorted Array
  • Java Program to Merge Two Arrays
  • Java Program to Check if two Arrays are Equal or not
  • Remove all occurrences of an element from Array in Java
  • Java Program to Find Common Elements Between Two Arrays
  • Array Copy in Java
  • Java Program For Array Rotation

Java 2-D Arrays (Matrix) Programs

  • Print a 2 D Array or Matrix in Java
  • Java Program to Add two Matrices
  • Sorting a 2D Array according to values in any given column in Java
  • Java Program to Find Transpose of Matrix
  • Java Program to Find the Determinant of a Matrix
  • Java Program to Find the Normal and Trace of a Matrix
  • Java Program to Print Boundary Elements of the Matrix
  • Java Program to Rotate Matrix Elements
  • Java Program to Compute the Sum of Diagonals of a Matrix
  • Java Program to Interchange Elements of First and Last in a Matrix Across Rows
  • Java Program to Interchange Elements of First and Last in a Matrix Across Columns

Java String Programs

  • Java Program to get a character from a String
  • Replace a character at a specific index in a String in Java
  • Reverse a string in Java
  • Java Program to Reverse a String using Stack
  • Sort a String in Java (2 different ways)
  • Swapping Pairs of Characters in a String in Java
  • Check if a given string is Pangram in Java
  • Print first letter of each word in a string using regex
  • Java Program to Determine the Unicode Code Point at Given Index in String
  • Remove Leading Zeros From String in Java
  • Compare two Strings in Java
  • Compare two strings lexicographically in Java
  • Java program to print Even length words in a String

Insert a String into another String in Java

  • Split a String into a Number of Substrings in Java

Java List Programs

  • Initializing a List in Java
  • How to Find a Sublist in a List in Java?
  • Min and Max in a List in Java
  • Split a List into Two Halves in Java
  • How to remove a SubList from a List in Java
  • How to Remove Duplicates from ArrayList in Java
  • How to sort an ArrayList in Ascending Order in Java
  • Get first and last elements from ArrayList in Java
  • Convert a List of String to a comma separated String in Java
  • How to Add Element at First and Last Position of LinkedList in Java?
  • Find common elements in two ArrayLists in Java
  • Remove repeated elements from ArrayList in Java

Java Date and Time Programs

  • Java Program to Format Time in AM-PM format
  • Java Program to Display Dates of a Calendar Year in Different Format
  • Java Program to Display Current Date and Time
  • Java Program to Display Time in Different Country Format
  • How to Convert Local Time to GMT in Java?

Java File Programs

  • Java Program to Create a New File
  • Java Program to Create a Temporary File
  • Java Program to Rename a File
  • Java Program to Make a File Read-Only
  • Comparing Path of Two Files in Java
  • Different Ways to Copy Content From One File to Another File in Java
  • Java Program to Print all the Strings that Match a Given Pattern from a File
  • Java Program to Append a String in an Existing File
  • Java Program to Read Content From One File and Write it into Another File
  • Java Program to Read and Print All Files From a Zip File

Java Directory Programs

  • Java Program to Traverse in a Directory
  • Java Program to Get the Size of a Directory
  • Java Program to Delete a directory
  • Java Program to Create Directories Recursively
  • Java Program to Search for a File in a Directory
  • Java Program to Find Current Working Directory
  • Java Program to List all Files in a Directory and Nested Sub-Directories

Java Exceptions and Errors Programs

  • Exceptions in Java
  • Types of Errors in Java with Examples
  • Java Program to Handle the Exception Hierarchies
  • Java Program to Handle the Exception Methods
  • Java Program to Handle Checked Exception
  • Java Program to Handle Unchecked Exception
  • Java Program to Handle Divide By Zero and Multiple Exceptions
  • Unreachable Code Error in Java
  • Thread Interference and Memory Consistency Errors in Java

Java Collections Programs

  • Collections in Java
  • How to Print a Collection in Java?
  • Java Program to Compare Elements in a Collection
  • Java Program to Get the Size of Collection and Verify that Collection is Empty
  • Collections.shuffle() Method in Java with Examples
  • Collections.reverse() Method in Java with Examples
  • Java Program to Change a Collection to an Array
  • Convert an Array into Collection in Java
  • How to Replace a Element in Java ArrayList?
  • Java Program to Rotate Elements of the List
  • How to iterate any Map in Java

Java Multithreading Programs

  • Thread isAlive() Method in Java With Examples
  • How to Temporarily Stop a Thread in Java?
  • Joining Threads in Java
  • Daemon Thread in Java

Java More Java Programs

  • Program to Print Fibonacci Series in Java
  • How to convert LinkedList to Array in Java?
  • Program to Convert a Vector to List in Java
  • Convert a String to a List of Characters in Java
  • Convert an Iterator to a List in Java
  • Program to Convert List to Map in Java
  • Program to Convert List to Stream in Java
  • Convert List to Set in Java
  • Java Program to Convert InputStream to String
  • Convert Set of String to Array of String in Java
  • Java Program to Convert String to Object
  • How to Convert a String value to Byte value in Java with Examples

assign string value in java

  • Get the Strings and the index.
  • Create a new String
  • Traverse the string till the specified index and copy this into the new String.
  • Copy the String to be inserted into this new String
  • Copy the remaining characters of the first string into the new String
  • Return/Print the new String
  • Insert the substring from 0 to the specified (index + 1) using substring(0, index+1) method. Then insert the string to be inserted into the string. Then insert the remaining part of the original string into the new string using substring(index+1) method.
  • Create a new StringBuffer
  • Insert the stringToBeInserted into the original string using StringBuffer.insert() method.
  • Return/Print the String from the StringBuffer using StringBuffer.toString() method.

Please Login to comment...

  • Dopple.ai Outperforms Leading Social Networks in User Time Spent In-App
  • Replica Studios vs. Descript Overdub: Which AI Generates Better Synthetic Voices?
  • How To Use ChatGPT for Your Job Search (2024)
  • Android Phones Might Get a Secure Face Unlock Upgrade: Introducing PolarID by Metalenz
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Read from Text File
  • Write to File
  • Import Package
  • Primitive Data Types
  • Type Casting

Variable Declaration

  • If Statement
  • Switch Case
  • Ternary Operator
  • Do-While Loop
  • Try Catch Block
  • Class Declaration
  • Access Modifiers
  • Constructor
  • Instantiation
  • Class Variables
  • Standard Methods
  • Class Methods
  • Inheritance
  • Abstract Methods and Classes
  • Anonymous Class
  • Declaring an Exception
  • Throwing an Exception
  • String Variables
  • String Length
  • String Compare
  • String Trim
  • Split String
  • String Representation

Version: SE 8

String class, string variables in java.

String variables are variables used to hold strings.

A string is technically an object, so its contents cannot be changed (immutable). For mutable strings, use the StringBuffer or StringBuilder classes.

A string variable must be initialized with either a value (which will be permanent) or null (for later initialization).

String Class - Java Docs

Add to Slack

  • 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

Constructor summary, method summary, 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

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

Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?

Java for Android: Know the importance of Java in Android

  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?
  • Java 9 Features and Improvements
  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

How to set path in java.

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

Control Statements

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

Java Core Concepts

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

Garbage Collection in Java: All you need to know

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

What is Enumeration in Java? A Beginners Guide

  • Transient in Java : What, Why & How it works?
  • What is Wait and Notify in Java?
  • Swing In Java : Know How To Create GUI With Examples
  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?
  • What Is A Virtual Function In Java?
  • Java Regex – What are Regular Expressions and How to Use it?
  • What is PrintWriter in Java and how does it work?
  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

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

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?
  • What is Integer class in java and how it works?
  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?
  • How To Implement Multiple Inheritance In Java?
  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?
  • What is the Use of Abstract Method in Java?
  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?
  • What is Dynamic Binding In Java And How To Use It?

Java Collections

  • Java Collections – Interface, List, Queue, Sets in Java With Examples

List in Java: One Stop Solution for Beginners

  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java

How to Iterate Maps in Java?

  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

  • Palindrome in Java: How to check a number is palindrome?
  • How to check if a given number is an Armstrong number or not?
  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?

How to implement Java program to check Leap Year?

  • How to Calculate Square and Square Root in Java?
  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?
  • Top 30 Patterns in Java: How to Print Star, Number and Character

Know all about the Prime Number program in Java

  • How To Display Fibonacci Series In Java?
  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?
  • How To Practice String Concatenation In Java?
  • How To Convert Binary To Decimal In Java?

How To Convert Double To Int in Java?

  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?
  • How to Create JFrame in Java?

What is Externalization in Java and when to use it?

  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?
  • Java Programs for Practice: Know the Simple Java Programs for Beginners

Advance Java

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

Career Opportunities

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

Interview Questions

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

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

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

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

   String str =”abc”; is equivalent to :

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

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

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

Java S tring Methods

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

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

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

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

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

Let’s understand this with a programmatic example:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Recommended videos for you

Implementing web services in java, portal development and text searching with hibernate, node js express: steps to create restful web app, mastering regex in perl, php and mysql : server side scripting for web development, hibernate mapping on the fly, microsoft sharepoint-the ultimate enterprise collaboration platform, service-oriented architecture with java, rapid development with cakephp, a day in the life of a node.js developer, ms .net – an intellisense way of web development, create restful web application with node.js express, php & mysql : server-side scripting language for web development, learn perl-the jewel of scripting languages, microsoft .net framework : an intellisense way of web development, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, spring framework : introduction to spring web mvc & spring with bigdata, nodejs – communication and round robin way, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, responsive web app using cakephp, recommended blogs for you, how to implement polymorphism in php, how to create an alert in javascript, what are vectors in c++ all you need to know, struts 2 tutorial – one stop solution for beginners, how to build an impressive web developer resume, python 101 : hello world program, bootstrap validation: how to validate a form using bootsrap, all you need to know about bootstrap gallery, what is string array in java and how it works, what are comments in java – know its types.

This is wrong information. Please correct it.

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

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

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

Join the discussion Cancel reply

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

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 75k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Spring Framework Certification Course

Node.js certification training course.

  • 10k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Advanced Java Certification Training

  • 7k Enrolled Learners

Microsoft .NET Framework Certification Traini ...

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

COMMENTS

  1. Java String variable setting

    17. The following Java code segment is from an AP Computer Science practice exam. String s1 = "ab"; String s2 = s1; s1 = s1 + "c"; System.out.println(s1 + " " + s2); The output of this code is "abc ab" on BlueJ. However, one of the possible answer choices is "abc abc". The answer can be either depending on whether Java sets String reference ...

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

    In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes. int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99. char - stores single characters, such as ...

  4. String Initialization in Java

    In this article, we explored String initialization. We explained the difference between declaration and initialization. We also touched on using new and using the literal syntax. Finally, we took a look at what it means to assign a null value to a String, how the null value is represented in memory, and how it looks when we print it.

  5. How to Assign a Value to a Variable in Java • Vertex Academy

    If we assign a value to a variable of the string type, we need to put it in double quotes: 1. String title = "I love Java"; If we assign a value to a variable of the char type, we need to put it in single quotes: 1. char letter = 'M'; If we assign a value to a variable of the float type, we need to add the letter "f":

  6. Manipulating Characters in a String (The Java™ Tutorials > Learning the

    The String class has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing case, and other tasks.. Getting Characters and Substrings by Index. You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is ...

  7. Strings in Java

    Syntax. String str= "geeks"; or String str= new String("geeks") 2. StringBuffer. StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences means it is mutable in nature and it is thread safe class , we can use it when we have ...

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

  9. java for complete beginners

    To set up a string variable, you type the word String followed by a name for your variable. Note that there's an uppercase "S" for String. Again, a semicolon ends the line: String first_name; Assign a value to your new string variable by typing an equals sign. After the equals sign the text you want to store goes between two sets of double quotes:

  10. Insert a String into another String in Java

    Without using any pre-defined method Approach: Get the Strings and the index. Create a new String. Traverse the string till the specified index and copy this into the new String. Copy the String to be inserted into this new String. Copy the remaining characters of the first string into the new String.

  11. java

    String oldString = "odl Text"; String newString = oldString; Simple steps can be: get text from EditText as string. assign that to some other string variable. Provide some more information to get better solutions.

  12. How to assign strings a number value within Java [closed]

    Yes, implementing a hash table is possible in Java. You can also just use the one already implemented in java.util called HashTable. But unless you're doing funky multi threaded stuff I recommend HashMap, from the same package, which is the same except not synchronized and so is a bit faster.

  13. String Variables in Java

    modifier String stringName = "String to store"; Notes. A string is technically an object, so its contents cannot be changed (immutable). For mutable strings, use the StringBuffer or StringBuilder classes. A string variable must be initialized with either a value (which will be permanent) or null (for later initialization). Example

  14. String (Java Platform SE 8 )

    A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m -that is, the result of this.substring (k, m + 1) . This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

  15. Attaching Values to Java Enum

    The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.. However, enum values are required to be valid identifiers, and we're encouraged to use SCREAMING_SNAKE_CASE by convention. Given those limitations, the enum value alone is not suitable for ...

  16. java

    When you do: String[] fields = {firstNameField, lastNameField, firstName, lastName}; you set reference of fields array value with index 0 to same object that firstNameField is referring to (in this case null ), index 1 to refer to same object as lastNameField, etc. Then, if you do: fields[ctr] = temp[ctr];

  17. String in Java

    For Example: String s="Welcome"; By new keyword : Java String is created by using a keyword "new". For example:String s=new String ("Welcome");It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap. Now, let us understand the concept of Java ...

  18. Java Enum with Strings

    In this guide to Java enum with string values, learn to create enum using strings, iterate over all enum values, get enum value and perform a reverse lookup to find an enum by string parameter. We should always create enum when we have a fixed set of related constants. Enums are inherently singleton, so they provide better performance.

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

    Strings in java are immutable, which means you cannot change the object itself (any operation returning a string (e.g. substring) will return a new one).. This means there is no need to create a new object for Strings, as there is no way for you to modify the original.Any attempt to do so will just result in wasted memory. Assigning references is only a problem when the objects in question are ...

  20. java

    Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it. Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.

  21. Converting String to BigDecimal in Java

    The BigDecimal class in Java provides operations for basic arithmetic, scale manipulation, comparison, format conversion, and hashing.. Furthermore, we use BigDecimal for high-precision arithmetic, calculations requiring control over the scale, and rounding off behavior.One such example is calculations involving financial transactions. We can convert a String into BigDecimal in Java using one ...