• 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

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

  • Java Tutorial
  • What is Java?
  • Installing the Java SDK
  • Your First Java App
  • Java Main Method
  • Java Project Overview, Compilation and Execution
  • Java Core Concepts
  • Java Syntax

Java Variables

  • Java Data Types
  • Java Math Operators and Math Class
  • Java Arrays
  • Java String
  • Java Operations
  • Java if statements
  • Java Ternary Operator
  • Java switch Statements
  • Java instanceof operator
  • Java for Loops
  • Java while Loops
  • Java Classes
  • Java Fields
  • Java Methods
  • Java Constructors
  • Java Packages
  • Java Access Modifiers
  • Java Inheritance
  • Java Nested Classes
  • Java Record
  • Java Abstract Classes
  • Java Interfaces
  • Java Interfaces vs. Abstract Classes
  • Java Annotations
  • Java Lambda Expressions
  • Java Modules
  • Java Scoped Assignment and Scoped Access
  • Java Exercises

Java Variable Types

Java variable declaration, java variable assignment, java variable reading, java variable naming conventions, java local-variable type inference.

A Java variable is a piece of memory that can contain a data value. A variable thus has a data type. Data types are covered in more detail in the text on Java data types .

Variables are typically used to store information which your Java program needs to do its job. This can be any kind of information ranging from texts, codes (e.g. country codes, currency codes etc.) to numbers, temporary results of multi step calculations etc.

In the code example below, the main() method contains the declaration of a single integer variable named number . The value of the integer variable is first set to 10, and then 20 is added to the variable afterwards.

In Java there are four types of variables:

  • Non-static fields
  • Static fields
  • Local variables

A non-static field is a variable that belongs to an object. Objects keep their internal state in non-static fields. Non-static fields are also called instance variables, because they belong to instances (objects) of a class. Non-static fields are covered in more detail in the text on Java fields .

A static field is a variable that belongs to a class. A static field has the same value for all objects that access it. Static fields are also called class variables. Static fields are also covered in more detail in the text on Java fields .

A local variable is a variable declared inside a method. A local variable is only accessible inside the method that declared it. Local variables are covered in more detail in the text on Java methods .

A parameter is a variable that is passed to a method when the method is called. Parameters are also only accessible inside the method that declares them, although a value is assigned to them when the method is called. Parameters are also covered in more detail in the text on Java methods .

Exactly how a variable is declared depends on what type of variable it is (non-static, static, local, parameter). However, there are certain similarities that

In Java you declare a variable like this:

Instead of the word type , you write the data type of the variable. Similarly, instead of the word name you write the name you want the variable to have.

Here is an example declaring a variable named myVariable of type int .

Here are examples of how to declare variables of all the primitive data types in Java:

Here are examples of how to declare variables of the object types in Java:

Notice the uppercase first letter of the object types.

When a variable points to an object the variable is called a "reference" to an object. I will get back to the difference between primitive variable values and object references in a later text.

The rules and conventions for choosing variable names are covered later in this text.

Assigning a value to a variable in Java follows this pattern:

Here are three concrete examples which assign values to three different variables with different data types

The first line assigns the byte value 127 to the byte variable named myByte . The second line assigns the floating point value 199.99 to the floating point variable named myFloat . The third line assigns the String value (text) this is a text to the String variable named myString .

You can also assign a value to a variable already when it is declared. Here is how that is done:

You can read the value of a Java variable by writing its name anywhere a variable or constant variable can be used in the code. For instance, as the right side of a variable assignment, as parameter to a method call, or inside a arithmetic expression. For instance:

There are a few rules and conventions related to the naming of variables.

The rules are:

  • Java variable names are case sensitive. The variable name money is not the same as Money or MONEY .
  • Java variable names must start with a letter, or the $ or _ character.
  • After the first character in a Java variable name, the name can also contain numbers (in addition to letters, the $, and the _ character).
  • Variable names cannot be equal to reserved key words in Java. For instance, the words int or for are reserved words in Java. Therefore you cannot name your variables int or for .

Here are a few valid Java variable name examples:

There are also a few Java variable naming conventions. These conventions are not necessary to follow. The compiler to not enforce them. However, many Java developers are used to these naming conventions. Therefore it will be easier for them to read your Java code if you follow them too, and easier for you to read the code of other Java developers if you are used to these naming conventions. The conventions are:

  • Variable names are written in lowercase. For instance, variable or apple .
  • If variable names consist of multiple words, each word after the first word has its first letter written in uppercase. For instance, variableName or bigApple .
  • Even though it is allowed, you do not normally start a Java variable name with $ or _ .
  • Static final fields (constants) are named in all uppercase, typically using an _ to separate the words in the name. For instance EXCHANGE_RATE or COEFFICIENT .

From Java 10 it is possible to have the Java compiler infer the type of a local variable by looking at what actual type that is assigned to the variable when the variable is declared. This enhancement is restricted to local variables, indexes in for-each loops and local variables declared in for-loops.

To see how the Java local-variable type inference works, here is first an example of a pre Java 10 String variable declaration:

From Java 10 it is no longer necessary to specify the type of the variable when declared, if the type can be inferred from the value assigned to the variable. Here is an example of declaring a variable in Java 10 using local-variable type inference:

Notice the var keyword used in front of the variable name, instead of the type String . The compiler can see from the value assigned that the type of the variable should be String , so you don't have to write it explicitly.

Here are a few additional Java local-variable type inference examples:

P2P Networks Introduction

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:

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

string variable assignment java

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Preface
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Variables
  • 1.7 Java Development Environments (optional)
  • 1.8 Unit 1 Summary
  • 1.9 Unit 1 Mixed Up Code Practice
  • 1.10 Unit 1 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Lesson Workspace
  • 1.3. Variables and Data Types" data-toggle="tooltip">
  • 1.5. Compound Assignment Operators' data-toggle="tooltip" >

1.4. Expressions and Assignment Statements ¶

In this lesson, you will learn about assignment statements and expressions that contain math operators and variables.

1.4.1. Assignment Statements ¶

Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator = . An assignment statement always has a single variable on the left hand side of the = sign. The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side.

Assignment statement

Figure 1: Assignment Statement (variable = expression) ¶

Instead of saying equals for the = operator in an assignment statement, say “gets” or “is assigned” to remember that the variable on the left hand side gets or is assigned the value on the right. In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.

The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.

As we saw in the video, we can set one variable to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.

coding exercise

Click on the Show CodeLens button to step through the code and see how the values of the variables change.

The program is supposed to figure out the total money value given the number of dimes, quarters and nickels. There is an error in the calculation of the total. Fix the error to compute the correct amount.

Calculate and print the total pay given the weekly salary and the number of weeks worked. Use string concatenation with the totalPay variable to produce the output Total Pay = $3000 . Don’t hardcode the number 3000 in your print statement.

exercise

Assume you have a package with a given height 3 inches and width 5 inches. If the package is rotated 90 degrees, you should swap the values for the height and width. The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w’s initial value of 5 and w should get h’s initial value of 3. Unfortunately this code has an error and does not work. Use the CodeLens to step through the code to understand why it fails to swap the values in h and w.

1-4-7: Explain in your own words why the ErrorSwap program code does not swap the values stored in h and w.

Swapping two variables requires a third variable. Before assigning h = w , you need to store the original value of h in the temporary variable. In the mixed up programs below, drag the blocks to the right to put them in the right order.

The following has the correct code that uses a third variable named “temp” to swap the values in h and w.

The code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right, then check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.

After three incorrect attempts you will be able to use the Help Me button to make the problem easier.

Fix the code below to perform a correct swap of h and w. You need to add a new variable named temp to use for the swap.

1.4.2. Incrementing the value of a variable ¶

If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. The formula looks a little crazy in math class, but it makes sense in coding because the variable on the left is set to the value of the arithmetic expression on the right. So, the score variable is set to the previous value of score + 1.

Click on the Show CodeLens button to step through the code and see how the score value changes.

1-4-11: What is the value of b after the following code executes?

  • It sets the value for the variable on the left to the value from evaluating the right side. What is 5 * 2?
  • Correct. 5 * 2 is 10.

1-4-12: What are the values of x, y, and z after the following code executes?

  • x = 0, y = 1, z = 2
  • These are the initial values in the variable, but the values are changed.
  • x = 1, y = 2, z = 3
  • x changes to y's initial value, y's value is doubled, and z is set to 3
  • x = 2, y = 2, z = 3
  • Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
  • x = 1, y = 0, z = 3

1.4.3. Operators ¶

Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Arithmetic expressions can be of type int or double. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to put text together in the input program above – more on this when we talk about strings.)

Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. Don’t get one equal sign = confused with two equal signs == ! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you’ll see below. Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.

Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3 ? Isn’t surprising that it prints 0 ? See the note below.

When Java sees you doing integer division (or any operation with integers) it assumes you want an integer result so it throws away anything after the decimal point in the answer, essentially rounding down the answer to a whole number. If you need a double answer, you should make at least one of the values in the expression a double like 2.0.

With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an ArithmeticException error message. Try it in one of the active code windows above.

Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first.

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence .

1-4-15: Consider the following code segment. Be careful about integer division.

What is printed when the code segment is executed?

  • 0.666666666666667
  • Don't forget that division and multiplication will be done first due to operator precedence.
  • Yes, this is equivalent to (5 + ((a/b)*c) - 1).
  • Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int result where it is rounded down to the nearest int.

1-4-16: Consider the following code segment.

What is the value of the expression?

  • Dividing an integer by an integer results in an integer
  • Correct. Dividing an integer by an integer results in an integer
  • The value 5.5 will be rounded down to 5

1-4-17: Consider the following code segment.

  • Correct. Dividing a double by an integer results in a double
  • Dividing a double by an integer results in a double

1-4-18: Consider the following code segment.

  • Correct. Dividing an integer by an double results in a double
  • Dividing an integer by an double results in a double

1.4.4. The Modulo Operator ¶

The percent sign operator ( % ) is the mod (modulo) or remainder operator. The mod operator ( x % y ) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? That remainder is what is returned by the modulo operator.

../_images/mod-py.png

Figure 2: Long division showing the whole number result and the remainder ¶

In the example below, try to guess what it will print out and then run it to see if you are right.

The result of x % y when x is smaller than y is always x . The value y can’t go into x at all (goes in 0 times), since x is smaller than y , so the result is just x . So if you see 2 % 3 the result is 2 .

1-4-21: What is the result of 158 % 10?

  • This would be the result of 158 divided by 10. modulo gives you the remainder.
  • modulo gives you the remainder after the division.
  • When you divide 158 by 10 you get a remainder of 8.

1-4-22: What is the result of 3 % 8?

  • 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
  • This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
  • What is the remainder after you divide 3 by 8?

1.4.5. FlowCharting ¶

Assume you have 16 pieces of pizza and 5 people. If everyone gets the same number of slices, how many slices does each person get? Are there any leftover pieces?

In industry, a flowchart is used to describe a process through symbols and text. A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid).

The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices.

Flow Chart

Figure 3: Example Flow Chart ¶

A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms.

Complete the program based on the process shown in the Figure 3 flowchart. Note the first line of code declares all 4 variables as type int. Add assignment statements and print statements to compute and print the slices per person and leftover slices. Use System.out.println for output.

1.4.6. Storing User Input in Variables ¶

Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables.

Program input and output

Figure 4: Program input and output ¶

A Java program can ask the user to type in one or more values. The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in . Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. The code below shows an example of prompting the user to enter a name and then printing a greeting. The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable.

Run the program a few times, typing in a different name. The code works for any name: behold, the power of variables!

Run this program to read in a name from the input stream. You can type a different name in the input window shown below the code.

Try stepping through the code with the CodeLens tool to see how the name variable is assigned to the value read by the scanner. You will have to click “Hide CodeLens” and then “Show in CodeLens” to enter a different name for input.

The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space.

Run this program to read in an integer from the input stream. You can type a different integer value in the input window shown below the code.

A rhomboid (slanted rectangle) is used in a flowchart to depict data flowing into and out of a program. The previous flowchart in Figure 3 used a rhomboid to indicate program output. A rhomboid is also used to denote reading a value from the input stream.

Flow Chart

Figure 5: Flow Chart Reading User Input ¶

Figure 5 contains an updated version of the pizza calculator process. The first two steps have been altered to initialize the pizzaSlices and numPeople variables by reading two values from the input stream. In Java this will be done using a Scanner object and reading from System.in.

Complete the program based on the process shown in the Figure 5 flowchart. The program should scan two integer values to initialize pizzaSlices and numPeople. Run the program a few times to experiment with different values for input. What happens if you enter 0 for the number of people? The program will bomb due to division by zero! We will see how to prevent this in a later lesson.

The program below reads two integer values from the input stream and attempts to print the sum. Unfortunately there is a problem with the last line of code that prints the sum.

Run the program and look at the result. When the input is 5 and 7 , the output is Sum is 57 . Both of the + operators in the print statement are performing string concatenation. While the first + operator should perform string concatenation, the second + operator should perform addition. You can force the second + operator to perform addition by putting the arithmetic expression in parentheses ( num1 + num2 ) .

More information on using the Scanner class can be found here https://www.w3schools.com/java/java_user_input.asp

1.4.7. Programming Challenge : Dog Years ¶

In this programming challenge, you will calculate your age, and your pet’s age from your birthdates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out.

Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years. If you want an extra challenge, try reading the values using a Scanner.

1.4.8. Summary ¶

Arithmetic expressions include expressions of type int and double.

The arithmetic operators consist of +, -, * , /, and % (modulo for the remainder in division).

An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away, essentially rounding down the answer to a whole number.

An arithmetic operation that uses at least one double value will evaluate to a double value.

Operators can be used to construct compound expressions.

During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped. (*, /, % have precedence over + and -, unless parentheses are used to group those.)

An attempt to divide an integer by zero will result in an ArithmeticException to occur.

The assignment operator (=) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.

During execution, expressions are evaluated to produce a single value.

The value of an expression has a type based on the evaluation of the expression.

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

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.

  • 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

  • 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

Array Variable Assignment in Java

  • Iterating over Arrays in Java
  • Array vs ArrayList in Java
  • String Arrays in Java
  • Array Literals in Java
  • Arrays in Java
  • Interesting facts about Array assignment in Java
  • Java Assignment Operators with Examples
  • Java Variables
  • How to Create Array of Objects in Java?
  • Array set() method in Java
  • How to Initialize an Array in Java?
  • Array Declarations in Java (Single and Multidimensional)
  • How to Take Array Input From User in Java
  • How Objects Can an ArrayList Hold in Java?
  • Java Program to Print the Elements of an Array
  • Java Array Exercise
  • Array setInt() method in Java
  • How to Fill (initialize at once) an Array in Java?
  • Array setShort() method in Java
  • Spring Boot - Start/Stop a Kafka Listener Dynamically
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Split() String method in Java with examples
  • Arrays.sort() in Java with examples
  • For-each loop in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Reverse a string in Java
  • HashMap in Java
  • How to iterate any Map in Java

An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition.

1. Element Level Promotion

Element-level promotions are not applicable at the array level. Like a character can be promoted to integer but a character array type cannot be promoted to int type array.

2. For Object Type Array

In the case of object-type arrays, child-type array variables can be assigned to parent-type array variables. That means after creating a parent-type array object we can assign a child array in this parent array.

When we assign one array to another array internally, the internal element or value won’t be copied, only the reference variable will be assigned hence sizes are not important but the type must be matched.

3. Dimension Matching

When we assign one array to another array in java, the dimension must be matched which means if one array is in a single dimension then another array must be in a single dimension. Samely if one array is in two dimensions another array must be in two dimensions. So, when we perform array assignment size is not important but dimension and type must be matched.

Please Login to comment...

Similar reads.

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. java for complete beginners

    string variable assignment java

  2. Java String

    string variable assignment java

  3. Introduction to Strings in Java

    string variable assignment java

  4. Java String startsWith() Method with examples

    string variable assignment java

  5. How to add double quotes around java object and string variable

    string variable assignment java

  6. 10 Important String Methods In Java You Must Know

    string variable assignment java

VIDEO

  1. 11 Create a string variable

  2. 5 Implementation of String Variable in Java Class file

  3. Assignment operators in java

  4. Infosys Springboard Lex Assignment Answers

  5. Learn Java in Hindi 5: More on Int and String Variable

  6. Demo Assignment Java 4 Fpoly

COMMENTS

  1. java

    I need to assign variables in a string. String s = "102, 145, 163, 124"; I want to assign a separate variable like below; num1 = 102; num2 = 145; num3 = 163; num4 = 124; I need to do it programatically since the values will change and increase so whatever is in string s is assigned a variable. Thanks

  2. java

    So, we all should know that you can include variables into strings by doing: String string = "A string " + aVariable; Is there a way to do it like: String string = "A string {aVariable}"; In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive. java. variables. insert.

  3. Java Strings

    For a complete reference of String methods, go to our Java String Methods Reference. The reference contains descriptions and examples of all string methods. Test Yourself With Exercises. Exercise: Fill in the missing part to create a greeting variable of type String and assign it the value Hello.

  4. String Initialization in Java

    Let's now create three empty Strings: String emptyLiteral = ""; String emptyNewString = new String(""); String emptyNewStringTwo = new String(); As we know by now, the emptyLiteral will be added to the String pool, while the other two go directly onto the heap. Although these won't be the same objects, all of them will have the same value:

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

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

  7. String (Java Platform SE 8 )

    All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc";

  8. Java Variables

    The third line assigns the String value (text) this is a text to the String variable named myString. You can also assign a value to a variable already when it is declared. Here is how that is done: byte myByte = 127; float myFloat = 199.99; String myString = "string value"; Java Variable Reading

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

  10. Java Assignment Operators

    Java Assignment Operators: Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. ... We can assign newly created object to object reference variable as below. String s = new String("Amit"); Employee e = New Employee(); First line will do following ...

  11. Java Variables

    Variables in Java. Java variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Variables in Java are only a name given to a memory location. All the operations done on the variable affect that memory location.

  12. How to assign value in string in Java?

    Yes, you can assign an empty string to a string variable by simply using double quotation marks without any characters between them, like this: "`java String myString = ""; "` 2. How can I assign a null value to a string variable? To assign a null value to a string variable, you can use the assignment operator (=) along with the keyword ...

  13. Concatenating Strings in Java

    Learn different ways to concatenate Strings in Java. First up is the humble StringBuilder. This class provides an array of String-building utilities that makes easy work of String manipulation. Let's build a quick example of String concatenation using the StringBuilder class: StringBuilder stringBuilder = new StringBuilder(100); stringBuilder.append("Baeldung"); stringBuilder.append(" is ...

  14. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator =.

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

  16. Java Assignment Operators with Examples

    variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

  17. String Variables in Java

    String Variables in Java. String variables are variables used to hold strings. Syntax 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.

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

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

  19. 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];

  20. Array Variable Assignment in Java

    Array Variable Assignment in Java. An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1.

  21. java

    There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.