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.

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

As you learned in the previous lesson, an object stores its state in fields .

The What Is an Object? discussion introduced you to fields, but you probably have still a few questions, such as: What are the rules and conventions for naming a field? Besides int , what other data types are there? Do fields have to be initialized when they are declared? Are fields assigned a default value if they are not explicitly initialized? We'll explore the answers to such questions in this lesson, but before we do, there are a few technical distinctions you must first become aware of. In the Java programming language, the terms "field" and "variable" are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing.

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
  • Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
  • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables . The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0; ). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
  • Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args) . Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.

Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields and variables. If we are talking about "fields in general" (excluding local variables and parameters), we may simply say "fields". If the discussion applies to "all of the above", we may simply say "variables". If the context calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate. You may also occasionally see the term "member" used as well. A type's fields, methods, and nested types are collectively called its members .

Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with " _ ", this practice is discouraged. White space is not permitted.
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence , speed , and gear , for example, are much more intuitive than abbreviated versions, such as s , c , and g . Also keep in mind that the name you choose must not be a keyword or reserved word .
  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6 , the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

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

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

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

In the previous tutorial you learnt about Java comments . Now, let's learn about variables and literals in Java.

  • Java Variables

A variable is a location in memory (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier). Learn more about Java identifiers .

  • Create Variables in Java

Here's how we create a variable in Java,

Here, speedLimit is a variable of int data type and we have assigned value 80 to it.

The int data type suggests that the variable can only hold integers. To learn more, visit Java data types.

In the example, we have assigned value to the variable during declaration. However, it's not mandatory.

You can declare variables and assign variables separately. For example,

Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.

  • Change values of variables

The value of a variable can be changed in the program, hence the name variable . For example,

Here, initially, the value of speedLimit is 80 . Later, we changed it to 90 .

However, we cannot change the data type of a variable in Java within the same scope.

What is the variable scope?

Don't worry about it for now. Just remember that we can't do something like this:

To learn more, visit: Can I change declaration type for a variable in Java?

Java programming language has its own set of rules and conventions for naming variables. Here's what you need to know:

1. Java is case sensitive. Hence, age and AGE are two different variables. For example,

2. Variables must start with either a letter or an underscore, _ or a dollar, $ sign. For example,

3. Variable names cannot start with numbers. For example,

4. Variable names can't use whitespace. For example,

Here, we need to use variable names having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, myAge .

5. When creating variables, choose a name that makes sense. For example, score , number , level makes more sense than variable names such as s , n , and l .

6. If you choose one-word variable names, use all lowercase letters. For example, it's better to use speed rather than SPEED , or sPEED .

  • Java literals

Literals are data used for representing fixed values. They can be used directly in the code. For example,

Here, 1 , 2.5 , and 'F' are literals.

There are different types of literals in Java. let's discuss some of the commonly used types in detail.

  • Integer Literals

Integer literals are numeric values (associated with numbers) without any fractional or exponential part. There are 4 types of integer literals in Java:

  • binary (base 2)
  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

For example:

In Java, binary starts with 0b , octal starts with 0 , and hexadecimal starts with 0x .

Note : Integer literals are used to initialize variables of integer types like byte , short , int , and long .

  • Floating-point Literals

Floating-point literals are numeric literals that have either a fractional form or an exponential form. For example,

Note : The floating-point literals are used to initialize float and double type variables.

  • Character Literals

Character literals are unicode characters enclosed inside single quotes. For example,

Here, a is the character literal.

We can also use escape sequences as character literals. For example, \b (backspace), \t (tab), \n (new line), etc.

  • String Literals

A string literal is a sequence of characters enclosed inside double-quotes. For example,

Here, Java Programming and Programiz are two string literals.

  • Boolean Literals

In Java, boolean literals are used to initialize boolean data types. They can store two values: true and false. For example,

Here, false and true are two boolean literals

Table of Contents

Sorry about that.

Related Tutorials

Java Tutorial

  • 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

  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

Java assignment operators are classified into two types: simple and compound .

The Simple assignment operator is the equals ( = ) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left.

Compound operators are comprised of both an arithmetic, bitwise, or shift operator in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * and = operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign = is used as the assignment operator . The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the =  operator. For example:

In the above assignment statement, the result of x + 1  is assigned to the variable x . Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation  x = 2 * x + 1  ≠ the Java expression x = 2 * x + 1

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting .

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

Subscribe to Receive Free Bio Hacking, Nootropic, and Health Information

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

HTML for Simple Website Customization My Personal Web Customization Personal Insights SEO Checklist Publishing Checklist My Tools

Top Posts & Pages

15. VbScript | Copy, Move, Rename Files & Folder

Javatpoint Logo

Java Tutorial

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

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Live Training, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Java Interview Questions and Answers
  • Java Developer Salary Guide in India – For Freshers & Experienced

02 Beginner

  • Hierarchical Inheritance in Java
  • Arithmetic operators in Java
  • Unary operator in Java
  • Relational operators in Java

Assignment operator in Java

  • Logical operators in Java
  • Primitive Data Types in Java
  • Multiple Inheritance in Java
  • Parameterized Constructor in Java
  • Constructor Chaining in Java
  • What is a Bitwise Operator in Java? Type, Example and More
  • Constructor Overloading in Java
  • Ternary Operator in Java
  • For Loop in Java: Its Types and Examples
  • Best Java Developer Roadmap 2024
  • While Loop in Java
  • What are Copy Constructors In Java? Explore Types,Examples & Use
  • Do-While Loop in Java
  • Hybrid Inheritance in Java
  • Single Inheritance in Java
  • Top 10 Reasons to know why Java is Important?
  • What is Java? A Beginners Guide to Java
  • Differences between JDK, JRE, and JVM: Java Toolkit
  • Variables in Java: Local, Instance and Static Variables
  • Data Types in Java - Primitive and Non-Primitive Data Types
  • Conditional Statements in Java: If, If-Else and Switch Statement
  • What are Operators in Java - Types of Operators in Java ( With Examples )
  • Java VS Python
  • Looping Statements in Java - For, While, Do-While Loop in Java
  • Jump Statements in JAVA - Types of Statements in JAVA (With Examples)
  • Java Arrays: Single Dimensional and Multi-Dimensional Arrays
  • What is String in Java - Java String Types and Methods (With Examples)

03 Intermediate

  • OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism
  • What is Class in Java? - Objects and Classes in Java {Explained}
  • Access Modifiers in Java: Default, Private, Public, Protected
  • Constructors in Java: Types of Constructors with Examples
  • Polymorphism in Java: Compile time and Runtime Polymorphism
  • Abstract Class in Java: Concepts, Examples, and Usage
  • What is Inheritance in Java: Types of Inheritance in Java
  • Exception handling in Java: Try, Catch, Finally, Throw and Throws

04 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • MERN: Full-Stack Web Developer Certification Training
  • Data Structures and Algorithms Training
  • Assignment Operator In Ja..

Assignment operator in Java

Java Programming For Beginners Free Course

Assignment operators in java: an overview.

We already discussed the Types of Operators in the previous tutorial Java. In this Java tutorial , we will delve into the different types of assignment operators in Java, and their syntax, and provide examples for better understanding. Because Java is a flexible and widely used programming language. Assignment operators play a crucial role in manipulating and assigning values to variables. To further enhance your understanding and application of Java assignment operator's concepts, consider enrolling in the best Java Certification Course .

What are the Assignment Operators in Java?

Assignment operators in Java are used to assign values to variables . They are classified into two main types: simple assignment operator and compound assignment operator.

The general syntax for a simple assignment statement is:

And for a compound assignment statement:

Read More - Advanced Java Interview Questions

Types of Assignment Operators in Java

  • Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign, where the operand is on the left side and the value is on the right. The right-side value must be of the same data type as that defined on the left side.
  • Compound Assignment Operator:  Compound assignment operators combine arithmetic operations with assignments. They provide a concise way to perform an operation and assign the result to the variable in one step. The Compound Operator is utilized when +,-,*, and / are used in conjunction with the = operator.

1. Simple Assignment Operator (=):

The equal sign (=) is the basic assignment operator in Java. It is used to assign the value on the right-hand side to the variable on the left-hand side.

Explanation

2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):.

Read More - Java Developer Salary

5. Division Operator (/=):

6. modulus assignment operator (%=):, example of assignment operator in java.

Let's look at a few examples in our Java Playground to illustrate the usage of assignment operators in Java:

  • Unary Operator in Java
  • Arithmetic Operators in Java
  • Relational Operators in Java
  • Logical Operators in Java

Q1. Can I use multiple assignment operators in a single statement?

Q2. are there any other compound assignment operators in java, q3. how many types of assignment operators.

  • 1. (=) operator
  • 1. (+=) operator
  • 2. (-=) operator
  • 3. (*=) operator
  • 4. (/=) operator
  • 5. (%=) operator

About Author

Author image

  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

Upcoming Master Classes  

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

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

  • Skip to content
  • Accessibility Policy
  • Oracle blogs
  • Lorem ipsum dolor

April 2024 Critical Patch Update Released

java variables assignments

Oracle today released the April 2024 Critical Patch Update .

This Critical Patch Update provides security updates for a wide range of product families, including: Oracle Database Server (including Oracle Application Express, Oracle Autonomous Health Framework, Oracle Big Data Spatial and Graph, Oracle GoldenGate, Oracle TimesTen In-Memory Database), Oracle Communications Applications, Oracle Communications, Oracle Construction and Engineering, Oracle E-Business Suite, Oracle Enterprise Manager, Oracle Financial Services Applications, Oracle Food and Beverage Applications, Oracle Fusion Middleware, Oracle Analytics, Oracle Health Sciences Applications, Oracle HealthCare Applications, Oracle Hospitality Applications, Oracle Hyperion, Oracle Insurance Applications, Oracle Java SE, Oracle MySQL, Oracle PeopleSoft, Oracle Retail Applications, Oracle Siebel CRM, Oracle Support Tools, Oracle Systems, Oracle Utilities Applications, and Oracle Virtualization.

For more information about the April 2024 Critical Patch Update, customers should refer to the Critical Patch Update advisory located at https://oracle.com/security-alerts/cpuapr2024.htm and the executive summary published on My Oracle Support ( Doc ID 2998382.1 ).

For more information about the Critical Patch Update program, see the security vulnerability remediation practices page located on the Oracle Trust Center . 

Eric Maurice

Vice president of security assurance.

With over 20 years experience in helping customers deal with securing complex IT systems, responding to cyber incidents, and developing comprehensive security strategies to manage technological risks and meet regulatory requirements, Eric Maurice helps define corporate security assurance policies and programs for Oracle’s on-premises and cloud offerings.

  • Analyst Reports
  • Cloud Economics
  • Corporate Responsibility
  • Diversity and Inclusion
  • Security Practices
  • What is Customer Service?
  • What is ERP?
  • What is Marketing Automation?
  • What is Procurement?
  • What is Talent Management?
  • What is VM?
  • Try Oracle Cloud Free Tier
  • Oracle Sustainability
  • Oracle COVID-19 Response
  • Oracle and SailGP
  • Oracle and Premier League
  • Oracle and Red Bull Racing Honda
  • US Sales 1.800.633.0738
  • How can we help?
  • Subscribe to Oracle Content
  • © 2024 Oracle
  • Privacy / Do Not Sell My Info

IMAGES

  1. Types of Variables in Java with Examples

    java variables assignments

  2. Variables and types of variables in java with examples

    java variables assignments

  3. Variables in Java

    java variables assignments

  4. Variables in Java

    java variables assignments

  5. Introduction To Java Variables With Examples

    java variables assignments

  6. Variables in Java

    java variables assignments

VIDEO

  1. #20. Assignment Operators in Java

  2. Java Fundamentals

  3. Instance Variables

  4. Java Essentials: How to Properly Name Your Variables

  5. Java: Variables

  6. 07: CHALLENGE

COMMENTS

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

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

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

    This beginner Java tutorial describes fundamentals of programming in the Java programming language ... You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; ... the variable thirdString contains "This is a concatenated string.", ...

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

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

    In the Java programming language, the terms "field" and "variable" are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing. The Java programming language defines the following kinds of variables: Instance Variables (Non-Static Fields) Technically speaking, objects store their ...

  6. Java Variables and Literals (With Examples)

    Here, speedLimit is a variable of int data type and we have assigned value 80 to it. The int data type suggests that the variable can only hold integers. To learn more, visit Java data types. In the example, we have assigned value to the variable during declaration. However, it's not mandatory. You can declare variables and assign variables ...

  7. All Java Assignment Operators (Explained With Examples)

    Java Assignment Operators are used to assign values to variables. The left operand of the assignment operator is a variable, whereas the right operand is a value or another variable. However, the value or variable given on the assignment operator's right side must be the same data type as the operand on the left side.

  8. Java Assignment operators

    The Java Assignment operators are used to assign the values to the declared variables. The equals ( = ) operator is the most commonly used Java assignment operator. For example: int i = 25; The table below displays all the assignment operators in the Java programming language. Operators.

  9. Java Variables

    Java Variable Assignment. Assigning a value to a variable in Java follows this pattern: variableName = value ; Here are three concrete examples which assign values to three different variables with different data types myByte = 127; myFloat = 199.99; myString = "This is a text";

  10. Java Assignment Operators

    Java assignment operators are classified into two types: simple and compound. The Simple assignment operator is the equals ( =) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...

  11. 1.7 Java

    An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows: variable ...

  12. Types of Assignment Operators in Java

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

  13. Java Variables

    A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type. Variable is a name of memory location. There are three types of variables in java: local, instance and static. There are two types of data types in Java: primitive and non-primitive.

  14. Java: define terms initialization, declaration and assignment

    assignment: throwing away the old value of a variable and replacing it with a new one. initialization: it's a special kind of assignment: the first.Before initialization objects have null value and primitive types have default values such as 0 or false.Can be done in conjunction with declaration. declaration: a declaration states the type of a variable, along with its name.

  15. Java Assignment Operators

    Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8;

  16. Assignment operator in Java

    They provide a concise way to perform an operation and assign the result to the variable in one step. The Compound Operator is utilized when +,-,*, and / are used in conjunction with the = operator. 1. Simple Assignment Operator (=): The equal sign (=) is the basic assignment operator in Java. It is used to assign the value on the right-hand ...

  17. Chapter 2: Variables and Assignments

    How variables and assignments work in Java.

  18. Variables in Java

    Variables are containers for storing data values, and they play a crucial role in any programming language. Join us as we unravel the intricacies of variables in Java, discussing topics such as variable declaration, initialization, naming conventions, and best practices. We'll explore how variables are used to store different types of data ...

  19. Java programming Exercises, Practice, Solution

    Java is the foundation for virtually every type of networked application and is the global standard for developing and delivering embedded and mobile applications, games, Web-based content, and enterprise software. With more than 9 million developers worldwide, Java enables you to efficiently develop, deploy and use exciting applications and ...

  20. Initializing multiple variables to the same value in Java

    76. You can declare multiple variables, and initialize multiple variables, but not both at the same time: String one,two,three; one = two = three = ""; However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".

  21. Introduction to Variables in Java

    Java Programming: Introduction to Variables in Java ProgrammingTopics discussed:1. Variables.2. Memory.3. Declaration of variables.4. Initialization of varia...

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

  23. April 2024 Critical Patch Update Released

    Oracle today released the April 2024 Critical Patch Update. This Critical Patch Update provides security updates for a wide range of product families, including: Oracle Database Server (including Oracle Application Express, Oracle Autonomous Health Framework, Oracle Big Data Spatial and Graph, Oracle GoldenGate, Oracle TimesTen In-Memory ...